我正在尝试使用我的代码生成发票。在页面底部,发票应包含付款单。
我发现了一些第三方库(与PDFsharp不相关),该库生成了一个PDF,其付款单在页面底部作为字节数组。现在,我尝试使用PDFsharp加载该PDF,并使用MigraDoc在同一页面上呈现其余发票。
这是我的代码:
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");
}
生成的PDF确实仅包含付款单,但我看不到MigraDoc文档中呈现的任何内容。
有趣的是,当我在pdfDoc
中添加第二页并将MigraDoc文档呈现到第二页时,它可以正常工作。仅当我渲染到已经包含付款单的页面时,我才看不到MigraDoc内容。
难道MigraDoc内容被呈现在该页面上现有内容(付款单)的“后面”,因此被遮挡了吗?如何解决这个问题?
我找到了解决方案。在第4行中,我从导入的PDF页面创建XGraphics
对象,我需要这样做
XGraphics.FromPdfPage(pdfDoc.Pages[0], XGraphicsPdfPageOptions.Prepend)
代替
XGraphics.FromPdfPage(pdfDoc.Pages[0])