C#-如何将图像转换为PDF(使用免费库) [英] C# - How to convert an image to a PDF (using a free library)

查看:805
本文介绍了C#-如何将图像转换为PDF(使用免费库)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经研究了很多,但是发现的大多数答案都涉及使用iText,而iText仅对开源软件的作者免费.

I've researched quite a bit but most answers I've found involve using iText which is only free for authors of open source software.

我的问题是如何利用免费的(最好是维护良好的)PDF库将图像转换为PDF.更具体地说,我正在使用Selenium来测试网页,部分要求是将结果页的屏幕截图保存为PDF格式.

My question is how to utilise a free (preferably well maintained) PDF library to convert an image into PDF. More specifically I'm using Selenium to test a webpage and part of the requirements are for a screenshot of a results page to be saved in PDF format.

我现在有什么:

        Screenshot screenshot = ((ITakesScreenshot)WebDriver).GetScreenshot();
        fileName =  filePath + fileName;

        screenshot.SaveAsFile($"{fileName}.png", ImageFormat.Png);

        // Convert to PDF and delete image
        // ?

推荐答案

我想出了一种方法,可以使用 PDFSharp ,希望对其他人也有用.

I've come up with a way to do this using PDFSharp, hopefully will be useful for others as well.

        // Convert to PDF and delete image
        PdfHelper.Instance.SaveImageAsPdf($"{fileName}.png", $"{fileName}.pdf", 1000, true);

新课程:

using System.IO;
using PdfSharp.Drawing;
using PdfSharp.Pdf;  

public sealed class PdfHelper
{
    private PdfHelper()
    {
    }

    public static PdfHelper Instance { get; } = new PdfHelper();

    internal void SaveImageAsPdf(string imageFileName, string pdfFileName, int width = 600, bool deleteImage = false)
    {
        using (var document = new PdfDocument())
        {
            PdfPage page = document.AddPage();
            using (XImage img = XImage.FromFile(imageFileName))
            {
                // Calculate new height to keep image ratio
                var height = (int)(((double)width / (double)img.PixelWidth) * img.PixelHeight);

                // Change PDF Page size to match image
                page.Width = width;
                page.Height = height;

                XGraphics gfx = XGraphics.FromPdfPage(page);
                gfx.DrawImage(img, 0, 0, width, height);                
            }
            document.Save(pdfFileName);
        }

    if (deleteImage)            
        File.Delete(imageFileName);
    }
}

这篇关于C#-如何将图像转换为PDF(使用免费库)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆