C# 在.NET中填充PDF字段而不使用API,如iTextSharp class测试 { 字符串pdfTemplate=@“c:\us.pdf”; 公共地雷测试(客户c,字符串输出) { StreamReader sr=新的StreamReader(pdfTemplate); StreamWriter sw=新StreamWriter(输出); 字符串内容=sr.ReadToEnd(); 内容。替换“((客户名称)/DA(/Verdana 10 Tf 0 g)/FT/Tx/Type/Annot/MK/V()/AP>>”,“(客户名称)/DA(/Verdana 10 Tf 0 g)/FT/Tx/Type/Annot/MK/V(约翰·约翰逊)/AP>>”; 软件编写(内容); sw.Close(); 高级关闭(); } }
为什么上面的代码无法生成有效的PDF?字符串是不可变的 调用C# 在.NET中填充PDF字段而不使用API,如iTextSharp class测试 { 字符串pdfTemplate=@“c:\us.pdf”; 公共地雷测试(客户c,字符串输出) { StreamReader sr=新的StreamReader(pdfTemplate); StreamWriter sw=新StreamWriter(输出); 字符串内容=sr.ReadToEnd(); 内容。替换“((客户名称)/DA(/Verdana 10 Tf 0 g)/FT/Tx/Type/Annot/MK/V()/AP>>”,“(客户名称)/DA(/Verdana 10 Tf 0 g)/FT/Tx/Type/Annot/MK/V(约翰·约翰逊)/AP>>”; 软件编写(内容); sw.Close(); 高级关闭(); } },c#,.net,pdf,stream,itextsharp,C#,.net,Pdf,Stream,Itextsharp,为什么上面的代码无法生成有效的PDF?字符串是不可变的 调用content.Replace(…)时,Replace函数返回一个包含替换内容的新字符串,代码将忽略该字符串。 原始的内容字符串未被修改 你需要把它改成 class mineTest { string pdfTemplate = @"c:\us.pdf"; public mineTest(Customer c, string output) { Stream
content.Replace(…)
时,Replace
函数返回一个包含替换内容的新字符串,代码将忽略该字符串。原始的
内容
字符串未被修改
你需要把它改成
class mineTest
{
string pdfTemplate = @"c:\us.pdf";
public mineTest(Customer c, string output)
{
StreamReader sr = new StreamReader(pdfTemplate);
StreamWriter sw = new StreamWriter(output);
string content = sr.ReadToEnd();
content.Replace("(Customer name)/DA(/Verdana 10 Tf 0 g)/FT/Tx/Type/Annot/MK<<>>/V()/AP<</N 13 0 R>>>>", "(Customer name)/DA(/Verdana 10 Tf 0 g)/FT/Tx/Type/Annot/MK<<>>/V(John Johnson)/AP<</N 13 0 R>>>>");
sw.Write(content);
sw.Close();
sr.Close();
}
}
顺便说一下,您应该调用File.writealText
和File.ReadAllText
字符串是不可变的
调用content.Replace(…)
时,Replace
函数返回一个包含替换内容的新字符串,代码将忽略该字符串。原始的
内容
字符串未被修改
你需要把它改成
class mineTest
{
string pdfTemplate = @"c:\us.pdf";
public mineTest(Customer c, string output)
{
StreamReader sr = new StreamReader(pdfTemplate);
StreamWriter sw = new StreamWriter(output);
string content = sr.ReadToEnd();
content.Replace("(Customer name)/DA(/Verdana 10 Tf 0 g)/FT/Tx/Type/Annot/MK<<>>/V()/AP<</N 13 0 R>>>>", "(Customer name)/DA(/Verdana 10 Tf 0 g)/FT/Tx/Type/Annot/MK<<>>/V(John Johnson)/AP<</N 13 0 R>>>>");
sw.Write(content);
sw.Close();
sr.Close();
}
}
顺便说一下,您应该调用
File.writealText
和File.ReadAllText
PDF文件是二进制文件。你把它作为文本阅读,然后重新写文本。正如SLaks也指出的,你甚至没有对替换的文本做任何事情
使用PDF库。试试看。PDF文件是二进制文件。你把它作为文本阅读,然后重新写文本。正如SLaks也指出的,你甚至没有对替换的文本做任何事情
使用PDF库。试试。我想我必须为PDFSharp支付商业许可证。谢谢但出于好奇,在没有库的情况下编辑PDF真的是个问题吗?有很多免费的开源PDF库。iText.NET是另一个例子。我没有使用它们,几年前我使用了一个商业产品(动态PDF)。要编辑没有PDF库的PDF文档,需要了解PDF文件格式。然后,您可以编写自己的库。:)很抱歉,我对此知之甚少。我写了一篇博客文章,解释了为什么你不能在我的网站上编辑PDF文件的3个原因,尽管我必须为PDFSharp支付商业许可证。谢谢但出于好奇,在没有库的情况下编辑PDF真的是个问题吗?有很多免费的开源PDF库。iText.NET是另一个例子。我没有使用它们,几年前我使用了一个商业产品(动态PDF)。要编辑没有PDF库的PDF文档,需要了解PDF文件格式。然后,您可以编写自己的库。:)对不起,我对此知之甚少。我写了一篇博文,解释了为什么你不能直接编辑PDF文件的三个原因