简体   繁体   中英

Populating PDF fields in .NET without a API, such as iTextSharp

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();
        }
    }

Why does the above code fail at producing a valid PDF?

Strings are immutable.

When you call content.Replace(...) , the Replace function returns a new string with the replacements, which your code ignores.
The original content string is not modified.

You need to change it to

content = content.Replace(...);

By the way, you should call File.WriteAllText and File.ReadAllText .

PDF files are binary. You are reading it as text, then re-writing the text. As SLaks also points out, you're not even doing anything with the replaced text.

Use a PDF Library. Try PDFSharp .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM