Skip to main content
 首页 » 编程设计

c#之在没有 API(例如 iTextSharp)的情况下在 .NET 中填充 PDF 字段

2024年02月24日32webabcd

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?

请您参考如下方法:

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

使用 PDF 库。尝试 PDFSharp .