Question

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");
Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top