Search code examples
pdfsharp

Keep XGraphics instance after save


How can I still have the XGraphics instance after I save the file ? I have declared PdfDocument and XGraphics globally :

    private PdfDocument pdf;
    private XGraphics gfx;

but after I use pdf.Save(filepath); the gfx becomes null. How to avoid that ?


Solution

  • With PDFsharp there are two ways to solve that issue.

    1. Create the PDF twice: once without date for preview, once with date when you finally print it. This would be a suitable way if PDF generation takes little time.

    2. Re-open the PDF file and obtain a fresh gfx to modify the page.
      Use document = PdfReader.Open(filenameDest, PdfDocumentOpenMode.Modify); to open the file, XGraphics gfx = XGraphics.FromPdfPage(document.Pages[0]); to get a fresh gfx for the first page.
      This method is also suitable if PDF generation takes longer.
      To save time, you could save to a MemoryStream and re-open the PDF for modification from the MemoryStream.

    Also discussed on the PDFsharp forum.