26

Environment - PDFsharp Library, Visual Studio 2012 and C# as the language.

I am trying to:

  1. read Test1.pdf (Width = 17 inches, Height – 11 inches) with 1 page
  2. add some text to it
  3. save it as another file (Test2.pdf)

I am able to do all the following. But when I open the file Test2.pdf the size of the page is getting reduced to Width = 11 inches, Height – 11 inches. These PDF files that I am using are Product Specification Sheets that I have downloaded from the internet. I believe this is happening on only certain types of file and I am not sure how to differentiate these files.

Code given below:

//File dimentions - Width = 17 inches, Height - 11 inches (Tabloid Format)
PdfDocument pdfDocument = PdfReader.Open(@"D:\Test1.pdf", PdfDocumentOpenMode.Modify);

PdfPage page = pdfDocument.Pages[0];
XGraphics gfx = XGraphics.FromPdfPage(page);
XFont font = new XFont("Verdana", 20, XFontStyle.BoldItalic);
gfx.DrawString("Hello, World!", font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), XStringFormats.Center);

//When the file is saved dimentions change to - Width = 11 inches, Height - 11 inches
pdfDocument.Save(@"D:\Test2.pdf");

I have uploaded the file here Test1.pdf

==================================================================================

As suggested by the PDFsharp Team the code should be as follows:

PdfDocument PDFDoc = PdfReader.Open(@"D:\Test1.pdf", PdfDocumentOpenMode.Import);
PdfDocument PDFNewDoc = new PdfDocument();

for (int Pg = 0; Pg < PDFDoc.Pages.Count; Pg++)
{
    PdfPage pp = PDFNewDoc.AddPage(PDFDoc.Pages[Pg]);

    XGraphics gfx = XGraphics.FromPdfPage(pp);
    XFont font = new XFont("Arial", 10, XFontStyle.Regular);
    gfx.DrawString("Hello, World!", font, XBrushes.Black, new XRect(0, 0, pp.Width, pp.Height), XStringFormats.BottomCenter);
}

PDFNewDoc.Save(@"D:\Test2.pdf");
Yuvi Dagar
  • 649
  • 2
  • 11
  • 20

1 Answers1

16

Instead of modifying the document, please create a new document and copy the pages from the old document to the new document.

Sample code can be found in this post on the PDFsharp forum:
http://forum.pdfsharp.net/viewtopic.php?p=2637#p2637

  • PDFsharp Team, thanks for the reply. I will try and restructure my code this way and get back on this. – Yuvi Dagar Jul 15 '13 at 08:20
  • PDFsharp Team, I have restructured my code. I am still facing some issues. Please take a look at the restructured code that I have posted above. – Yuvi Dagar Jul 15 '13 at 08:41
  • After following all the instructions I was able to resolve my problems. Many thanks to the PDFsharp Team. – Yuvi Dagar Jul 15 '13 at 09:31