Search code examples
c#asp.netpdfwebformspdfsharp

PDFsharp PdfDocument.Save causing blank pages on any additional saves


While I have a workaround for this problem, I'd prefer to do it the way that I ran into this problem. Let me explain the context before getting to the problem:

I'm using a scanner to get virtual images which I want to use to create a PDF with each page being one single image. I got the working just fine using PDFsharp for creation of the PDF. display of PDF

However; if I try to re-save the PDFsharp document, it ends up blanking all the previous pages, and then adding the new image. display of broken PDF

For a little more context, I'm using ASP.NET Windows Forms, with NTwain for the scanning software, PDFsharp for creating the PDF, and PdfiumViewer to view the PDF on the Windows form.

I have a class-level variable for the document PdfDocument document = new PdfDocument();

On image save, I simply save the image to a new page

var img = pictureBox1.Image;
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
XImage image = XImage.FromGdiPlusImage(img);
gfx.DrawImage(image, 0, 0);

To render out the document, I copy the document (thought this might fix the problem) to a new document, save the contents to a new memory stream, and simply view the PDF

var viewDocument = (PdfDocument)document.Clone();
MemoryStream ms = new MemoryStream();
viewDocument.Save(ms, false);
ms.Position = 0;
var pdf = PdfiumViewer.PdfDocument.Load(ms);
pdfRenderer1.Load(pdf);

I got it working by saving the image to a list, instead of as a new page, and remade the document each time I wanted to display it. The issue is really strange, however.

Any help understanding why it does that is appreciated.


Solution

  • AFAIK this is the state of the implementation: The recommended way is to create a PdfDocument or open it from a file, make the changes you need, then save it once.
    This is what you do in the implementation that works for you.

    Saving the document, opening it, adding more pages, saving it again would also work. This way you would not need a list of all images. But IMHO using the list and creating a new PdfDocument each time you save is the cleanest way.

    Unexpected results occur when saving again after further changes. This is a known issue. Feel free to investigate this issue and fix it. Maybe it is just a simple change, maybe it is complicated.