0
votes

I'm trying to generate an invoice with from my code. At the bottom of the page, the invoice should contain a payment slip.

I found some 3rd party library (not related to PDFsharp) which generates a PDF with the payment slip at the bottom of the page as a byte array. Now I'm trying to load that PDF with PDFsharp and use MigraDoc to render the rest of the invoice on the same page.

This is my code:

byte[] paymentSlipPdfBytes = GeneratePaymentSlipPdf();                      // payment slip generated by some other library
using (MemoryStream ms = new MemoryStream(paymentSlipPdfBytes))
using (PdfDocument pdfDoc = PdfReader.Open(ms, PdfDocumentOpenMode.Modify))
using (XGraphics graphics = XGraphics.FromPdfPage(pdfDoc.Pages[0]))
{
    Document invoiceDoc = GenerateInvoiceDocument();                        // other content of the invoice generated using MigraDoc
    DocumentRenderer docRenderer = new DocumentRenderer(invoiceDoc);
    docRenderer.PrepareDocument();
    docRenderer.RenderPage(graphics, 1, PageRenderOptions.All);             // trying to render MigraDoc content on the page imported from other library
    pdfDoc.Save("Invoice.pdf");
}

The resulting PDF does contain only the payment slip, but I don't see anything rendered from the MigraDoc document.

Interestingly, when I add a second page to pdfDoc and I render the MigraDoc document to that second page, it works fine. Only when I render to the page which already contains the payment slip, I don't see the MigraDoc content.

Could it be that the MigraDoc content gets rendered 'behind' the existing content (payment slip) on that page, so it gets occluded? How to solve this problem?

1
Most PDF documents have black text on transparent background. You can check this when you activate the transparency grid in Adobe Reader. Some PDFs are black on white and in that case the MigraDoc output could be hidden.I liked the old Stack Overflow
The payment slip pdf seems to be black on transparent, so the behavior above is even more strange. However, passing the XGraphicsPdfPageOptions.Prepend option when creating the XGraphics object did help (see my own answer below).Robert Hegner

1 Answers

0
votes

I found the solution. In line 4 where I create the XGraphics object from the imported PDF page I need to do

XGraphics.FromPdfPage(pdfDoc.Pages[0], XGraphicsPdfPageOptions.Prepend)

instead of

XGraphics.FromPdfPage(pdfDoc.Pages[0])