views:

71

answers:

2
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?

+2  A: 

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.

SLaks
+1  A: 

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.

David Crowell
I though I would have to pay for a commercial license for PDFSharp. Thanks!But just for curiosities sake, is it a real problem editing a PDF without a library?
Kristjan Oddsson
There are a number of free and open-source PDF libraries. iText.NET is another. I haven't had to use them, I used a commercial product (Dynamic PDF) a few years ago.
David Crowell
To edit a PDF document without a PDF library would require understanding the PDF file format. Then you could write your own library. :)Sorry, I know very little about that.
David Crowell
I wrote a blog post explaining the 3 reasons why you can't really just edit a PDF file at http://pdf.jpedal.org/java-pdf-blog/bid/30454/Why-can-t-I-just-open-and-edit-a-PDF-file
mark stephens