简体   繁体   English

PDFsharp/MigraDoc 给页面添加背景图片

[英]PDFsharp/MigraDoc Add background images to pages

GOAL目标

To open an existing PDF file with multiple pages and add background image to all pages.打开包含多个页面的现有 PDF 文件并向所有页面添加背景图像。 (Optionally the background image of the first page differs from the others) (可选择第一页的背景图片与其他页面不同)

In my current implementation (I use .NET 6 and PDFsharp btw.) I add the image to each page, which increases the size of the file dependent on the number of pages.在我当前的实现中(我使用 .NET 6 和 PDFsharp btw。)我将图像添加到每一页,这会根据页数增加文件的大小。

QUESTION问题

Is there a way in PDFsharp/MigraDoc to embed a background image only once into the document and then reference it for each page? PDFsharp/MigraDoc 中是否有一种方法可以将背景图像仅嵌入到文档中一次,然后为每个页面引用它?

CODE代码

Both PDF document and the image come from a database as byte arrays. PDF 文档和图像都来自数据库,字节为 arrays。

public byte[] AddBackgroundImgToDocument(byte[] doc, byte[] imgFirstPage, byte[]? imgOtherPages=null)
{
    using var ms = new MemoryStream(doc);
    PdfDocument pdfDoc = PdfReader.Open(ms, PdfDocumentOpenMode.Modify);
    
    for (int i = 0; i < pdfDoc.PageCount; i++)
    {
        if(i > 0 && imgOtherPages != null && imgOtherPages.Length > 0)
            AddBackgroundImageFromByteArray(pdfDoc.Pages[i], imgOtherPages);
        else
            AddBackgroundImageFromByteArray(pdfDoc.Pages[i], imgFirstPage);

        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
    using var oms = new MemoryStream();
    pdfDoc.Save(oms);
    ms.Dispose();
    pdfDoc.Dispose();
    return oms.ToArray();
}

public void AddBackgroundImageFromByteArray(PdfPage page, byte[] imgfile)
{
    XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);
    MemoryStream ms = new System.IO.MemoryStream(imgfile);
    ms.Position = 0;
    XImage image = XImage.FromStream(() => ms);
    gfx.DrawImage(image, 0, 0, page.Width, page.Height);
    ms.Dispose();
}

SOLUTION解决方案

Rewriting the method above according to accepted answer, solved my problem:根据接受的答案重写上面的方法,解决了我的问题:

public void AddBackgroundImageFromByteArray(PdfPage page, byte[] imgfile)
{
    if(!ximageLoaded)
    {
        MemoryStream ms = new System.IO.MemoryStream(imgfile);
        ms.Position = 0;
        backimg = XImage.FromStream(() => ms);
        ms.Dispose();
        ximageLoaded = true;
    }

    XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);
    gfx.DrawImage(backimg, 0, 0, page.Width, page.Height);
}

With PDFsharp and MigraDoc this optimization is done automatically if you use them as intended.对于 PDFsharp 和 MigraDoc,如果您按预期使用它们,这种优化会自动完成。

Load the image once with PDFsharp and add it to as many pages as you like, there will be only one copy of the image in the document.使用 PDFsharp 一次加载图像并将其添加到任意多的页面,文档中将只有一个图像副本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM