使用PDFSharp将图像叠加到PDF上

use*_*060 17 c# pdfsharp asp.net-mvc-4

似乎没有找到很多这方面.我有一张PDF,我想在其上覆盖电子签名的图像.有关如何使用PDFSharp完成该任务的任何建议?

谢谢

Kam*_*ami 27

请尝试以下方法

private void GeneratePDF(string filename, string imageLoc)
{
    PdfDocument document = new PdfDocument();

    // Create an empty page or load existing
    PdfPage page = document.AddPage();

    // Get an XGraphics object for drawing
    XGraphics gfx = XGraphics.FromPdfPage(page);
    DrawImage(gfx, imageLoc, 50, 50, 250, 250);

    // Save and start View
    document.Save(filename);
    Process.Start(filename);
}

void DrawImage(XGraphics gfx, string jpegSamplePath, int x, int y, int width, int height)
{
    XImage image = XImage.FromFile(jpegSamplePath);
    gfx.DrawImage(image, x, y, width, height);
}
Run Code Online (Sandbox Code Playgroud)

这将生成一个新的PDF,其中指定的图像靠近页面顶部.如果需要使用现有文档,请将PdfDocument构造函数更改为

PdfDocument document = new PdfDocument(filename);
Run Code Online (Sandbox Code Playgroud)

其中filename是要加载的文件的名称并将PdfPage行更改为

PdfPage page = document.Pages[pageNum];
Run Code Online (Sandbox Code Playgroud)

这里pageNum是您需要添加的图像的页面的数量.

之后,只需通过更改DrawImage适合的参数来获取页面上的定位.

DrawImage(gfx, imageLoc, 50, 50, 250, 250);
Run Code Online (Sandbox Code Playgroud)

祝好运!

  • @gumuruh上帝与此毫无关系.还有其他可用的方法 - 也许是XImage.FromGdiPlusImage()?它允许`System.Drawing.Image`,可以从文件或流等加载. (3认同)

fff*_*f01 5

这将有助于您:

    PdfDocument document = pdf;

    // Create a new page        
    PdfPage page = document.Pages[0];
    page.Orientation = PageOrientation.Portrait;

    XGraphics gfx = XGraphics.FromPdfPage(page, XPageDirection.Downwards);

    // Draw background
    gfx.DrawImage(XImage.FromFile("pdf_overlay.png"), 0, 0);
Run Code Online (Sandbox Code Playgroud)

只需添加所需图像的路径,然后指定图像的位置即可.