Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c# - Overlay image onto PDF using PDFSharp

Can't seem to find much out there for this. I've a PDF, onto which I'd like to overlay an image of an electronic signature. Any suggestions on how to accomplish that using PDFSharp?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try the following

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);
}

This will generate a new PDF with the specified image near the top of the page. If you need to use an existing document change the PdfDocument constructor to

PdfDocument document = new PdfDocument(filename);

where filename is the name of the file to load and change the PdfPage line to

PdfPage page = document.Pages[pageNum];

where pageNum is the number of the page on which you need to add the image.

After that, it just a matter of getting the positioning on the page by altering the parameters for DrawImage to suit.

DrawImage(gfx, imageLoc, 50, 50, 250, 250);

Good luck!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...