【问题标题】:Populating PDF fields in .NET without a API, such as iTextSharp在没有 API 的情况下在 .NET 中填充 PDF 字段,例如 iTextSharp
【发布时间】:2010-06-14 16:30:41
【问题描述】:
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();
        }
    }

为什么上述代码无法生成有效的 PDF?

【问题讨论】:

    标签: c# .net pdf stream itextsharp


    【解决方案1】:

    PDF 文件是二进制文件。您正在将其作为文本阅读,然后重新编写文本。正如 SLaks 还指出的那样,您甚至没有对替换的文本做任何事情。

    使用 PDF 库。试试PDFSharp

    【讨论】:

    • 我需要为 PDFSharp 的商业许可证付费。谢谢!但只是出于好奇,在没有库的情况下编辑 PDF 真的有问题吗?
    • 有许多免费和开源的 PDF 库。 iText.NET 是另一个。我没用过,几年前我用过一个商业产品(Dynamic PDF)。
    • 要在没有 PDF 库的情况下编辑 PDF 文档,需要了解 PDF 文件格式。然后你可以编写自己的库。 :) 抱歉,我对此知之甚少。
    • 我在pdf.jpedal.org/java-pdf-blog/bid/30454/…写了一篇博文,解释了你不能真正编辑 PDF 文件的 3 个原因
    【解决方案2】:

    字符串是不可变的。

    当您调用 content.Replace(...) 时,Replace 函数会返回一个带有替换的新字符串,您的代码会忽略该字符串。
    content字符串没有被修改。

    你需要改成

    content = content.Replace(...);
    

    顺便说一句,你应该打电话给File.WriteAllTextFile.ReadAllText

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-26
      • 2015-12-02
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多