Overlay image onto PDF using PDFSharp

后端 未结 3 482
离开以前
离开以前 2020-12-14 17:05

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 usin

3条回答
  •  余生分开走
    2020-12-14 17:56

    To roughly maintain the aspect ratio, I used @Kami's answer and "roughly" centered it. The assumption made is that the pdf width is 600 and pdf height is 800, we will make use of the middle 500 and 700 of the page only, leaving the 4 sides have at least 50 in length as margin.

        public static void GeneratePdf(string outputPath, string inputPath)
        {
            PdfSharp.Pdf.PdfDocument document = new PdfSharp.Pdf.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, inputPath);
    
            // Save and start View
            document.Save(outputPath);
            Process.Start(outputPath);
        }
    
        public static void DrawImage(XGraphics gfx, string imagePath)
        {
            XImage image = XImage.FromFile(imagePath);
            var imageHeight = image.PixelHeight;
            var imageWidth = image.PixelWidth;
            int height;
            int width;
            int x;
            int y;
    
            width = 500;
            height = (int) Math.Ceiling((double) width * imageHeight / imageWidth);
    
            x = 50;
            y = (int) Math.Ceiling((800 - height) / 2.0);
            
            if(height > 700)
            {
                height = 700;
                width = (int) Math.Ceiling(imageWidth * (double) height / imageHeight);
    
                y = 50;
                x = (int) Math.Ceiling((600 - width) / 2.0);
            }
            
            gfx.DrawImage(image, x, y, width, height);
        }
    

提交回复
热议问题