PDFsharp edit a pdf file
Asked Answered
N

1

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");
Naturalism answered 15/7, 2013 at 6:20 Comment(2)
Try to modify the page from PDFNewDoc.Pages (not PDFDoc.Pages) - or take the page returned by AddPage().Roundhouse
I tried running this code.Its says PdfReader does not exist in the current context?Brachial
R
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

Roundhouse answered 15/7, 2013 at 7:59 Comment(3)
PDFsharp Team, thanks for the reply. I will try and restructure my code this way and get back on this.Naturalism
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.Naturalism
After following all the instructions I was able to resolve my problems. Many thanks to the PDFsharp Team.Naturalism

© 2022 - 2024 — McMap. All rights reserved.