C# 中的 JPG 到 PDF 转换器

发布于 2024-08-09 10:59:25 字数 176 浏览 12 评论 0原文

我想将图像(如 jpg 或 png)转换为 PDF。

我已经查看了 ImageMagickNET,但它对于我的需求来说太复杂了。

还有哪些其他 .NET 解决方案或代码可用于将图像转换为 PDF?

I would like to convert from an image (like jpg or png) to PDF.

I've checked out ImageMagickNET, but it is far too complex for my needs.

What other .NET solutions or code are there for converting an image to a PDF?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

何时共饮酒 2024-08-16 10:59:25

使用 iTextSharp 即可轻松完成:

class Program
{
    static void Main(string[] args)
    {
        Document document = new Document();
        using (var stream = new FileStream("test.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
        {
            PdfWriter.GetInstance(document, stream);
            document.Open();
            using (var imageStream = new FileStream("test.jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                var image = Image.GetInstance(imageStream);
                document.Add(image);
            }
            document.Close();
        }
    }
}

Easy with iTextSharp:

class Program
{
    static void Main(string[] args)
    {
        Document document = new Document();
        using (var stream = new FileStream("test.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
        {
            PdfWriter.GetInstance(document, stream);
            document.Open();
            using (var imageStream = new FileStream("test.jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                var image = Image.GetInstance(imageStream);
                document.Add(image);
            }
            document.Close();
        }
    }
}
无言温柔 2024-08-16 10:59:25

iTextSharp 做得非常干净并且是开源的。此外,它还有作者的一本非常好的配套书,如果您最终做更有趣的事情,比如管理表单。对于正常使用,邮件列表和新闻组上有大量资源,提供如何执行常见操作的示例。

编辑:正如 @Chirag 的评论中提到的,@Darin 的答案 包含肯定可以与当前版本编译的代码。

用法示例:

public static void ImagesToPdf(string[] imagepaths, string pdfpath)
{
    using(var doc = new iTextSharp.text.Document())
    {
        iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new FileStream(pdfpath, FileMode.Create));
        doc.Open();
        foreach (var item in imagepaths)
        {
            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(item);
            doc.Add(image);
        }
    }
}

iTextSharp does it pretty cleanly and is open source. Also, it has a very good accompanying book by the author which I recommend if you end up doing more interesting things like managing forms. For normal usage, there are plenty resources on mailing lists and newsgroups for samples of how to do common things.

EDIT: as alluded to in @Chirag's comment, @Darin's answer has code that definitely compiles with current versions.

Example usage:

public static void ImagesToPdf(string[] imagepaths, string pdfpath)
{
    using(var doc = new iTextSharp.text.Document())
    {
        iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new FileStream(pdfpath, FileMode.Create));
        doc.Open();
        foreach (var item in imagepaths)
        {
            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(item);
            doc.Add(image);
        }
    }
}

拥有 2024-08-16 10:59:25

另一个工作代码,尝试一下

public void ImagesToPdf(string[] imagepaths, string pdfpath)
{
        iTextSharp.text.Rectangle pageSize = null;

        using (var srcImage = new Bitmap(imagepaths[0].ToString()))
        {
            pageSize = new iTextSharp.text.Rectangle(0, 0, srcImage.Width, srcImage.Height);
        }

        using (var ms = new MemoryStream())
        {
            var document = new iTextSharp.text.Document(pageSize, 0, 0, 0, 0);
            iTextSharp.text.pdf.PdfWriter.GetInstance(document, ms).SetFullCompression();
            document.Open();
            var image = iTextSharp.text.Image.GetInstance(imagepaths[0].ToString());
            document.Add(image);
            document.Close();

            File.WriteAllBytes(pdfpath+"cheque.pdf", ms.ToArray());
        }
}

Another working code, try it

public void ImagesToPdf(string[] imagepaths, string pdfpath)
{
        iTextSharp.text.Rectangle pageSize = null;

        using (var srcImage = new Bitmap(imagepaths[0].ToString()))
        {
            pageSize = new iTextSharp.text.Rectangle(0, 0, srcImage.Width, srcImage.Height);
        }

        using (var ms = new MemoryStream())
        {
            var document = new iTextSharp.text.Document(pageSize, 0, 0, 0, 0);
            iTextSharp.text.pdf.PdfWriter.GetInstance(document, ms).SetFullCompression();
            document.Open();
            var image = iTextSharp.text.Image.GetInstance(imagepaths[0].ToString());
            document.Add(image);
            document.Close();

            File.WriteAllBytes(pdfpath+"cheque.pdf", ms.ToArray());
        }
}
秋意浓 2024-08-16 10:59:25

我们非常幸运地使用了 PDFSharp(我们每天使用它进行 TIFF 和文本到 PDF 的转换,以处理数百个医疗索赔)。

http://pdfsharp.com/PDFsharp/

One we've had great luck with is PDFSharp (we use it for TIFF and Text to PDF conversion for hundreds of medical claims every day).

http://pdfsharp.com/PDFsharp/

千柳 2024-08-16 10:59:25

借助 Docotic.Pdf 库 可以轻松完成此类任务。

下面是一个从给定图像(实际上不仅仅是 JPG)创建 PDF 的示例:

public static void imagesToPdf(string[] images, string pdfName)
{
    using (PdfDocument pdf = new PdfDocument())
    {
        for (int i = 0; i < images.Length; i++)
        {
            if (i > 0)
                pdf.AddPage();

            PdfPage page = pdf.Pages[i];
            string imagePath = images[i];
            PdfImage pdfImage = pdf.AddImage(imagePath);

            page.Width = pdfImage.Width;
            page.Height = pdfImage.Height;
            page.Canvas.DrawImage(pdfImage, 0, 0);
        }

        pdf.Save(pdfName);
    }
}

免责声明:我为该库的供应商工作。

Such task can be easily done with help of Docotic.Pdf library.

Here is a sample that creates PDF from given images (not only JPGs, actually):

public static void imagesToPdf(string[] images, string pdfName)
{
    using (PdfDocument pdf = new PdfDocument())
    {
        for (int i = 0; i < images.Length; i++)
        {
            if (i > 0)
                pdf.AddPage();

            PdfPage page = pdf.Pages[i];
            string imagePath = images[i];
            PdfImage pdfImage = pdf.AddImage(imagePath);

            page.Width = pdfImage.Width;
            page.Height = pdfImage.Height;
            page.Canvas.DrawImage(pdfImage, 0, 0);
        }

        pdf.Save(pdfName);
    }
}

Disclaimer: I work for the vendor of the library.

风蛊 2024-08-16 10:59:25

如果你想以跨平台的方式做到这一点,而不需要任何三十部分库,
或支付任何许可证,您可以使用此代码。
它需要一系列图片(我认为它只适用于 jpg)及其大小并返回一个 pdf 文件,每页一张图片。

您必须创建两个文件:

文件图片:

using System;
using System.Collections.Generic;
using System.Text;

namespace PDF
{
    public class Picture
    {
        private byte[] data;
        private int width;
        private int height;

        public byte[] Data { get => data; set => data = value; }
        public int Width { get => width; set => width = value; }
        public int Height { get => height; set => height = value; }
    }
}

文件 PDF 导出:

using System;
using System.Collections.Generic;

namespace PDF
{
    public class PDFExport
    {
        private string company = "Your Company Here";

        public sbyte[] createFile(List<Picture> pictures)
        {
            int N = (pictures.Count + 1) * 3;
            string dateTimeStr = DateTime.Now.ToString("yyyyMMddhhmmss");

            string file1 =
            "%PDF-1.4\n";

            string file2 =
                "2 0 obj\n" +
                "<<\n" +
                "/Type /Pages\n" +
                getKids(pictures) +
                "/Count " + pictures.Count + "\n" +
                 ">>\n" +
                 "endobj\n" +
                "1 0 obj\n" +
                "<<\n" +
                "/Type /Catalog\n" +
                "/Pages 2 0 R\n" +
                "/PageMode /UseNone\n" +
                "/PageLayout /SinglePage\n" +
                 "/Metadata 7 0 R\n" +
                 ">>\n" +
                  "endobj\n" +
                N + " 0 obj\n" +
                "<<\n" +
                "/Creator(" + company + ")\n" +
                "/Producer(" + company + ")\n" +
                "/CreationDate (D:" + dateTimeStr + ")\n" +
                "/ModDate (D:" + dateTimeStr + ")\n" +
                ">>\n" +
                "endobj\n" +
                "xref\n" +
                "0 " + (N + 1) + "\n" +
                "0000000000 65535 f\n" +
                "0000224088 00000 n\n" +
                "0000224031 00000 n\n" +
                "0000000015 00000 n\n" +
                "0000222920 00000 n\n" +
                "0000222815 00000 n\n" +
                "0000224153 00000 n\n" +
                "0000223050 00000 n\n" +
                "trailer\n" +
                "<<\n" +
                "/Size " + (N + 1) + "\n" +
                 "/Root 1 0 R\n" +
                  "/Info 6 0 R\n" +
                   ">>\n" +
                   "startxref\n" +
                "0\n" +
                "%% EOF";

            sbyte[] part1 = file1.GetBytes();
            sbyte[] part2 = file2.GetBytes();

            List<sbyte[]> fileContents = new List<sbyte[]>();
            fileContents.Add(part1);
            for (int i = 0; i < pictures.Count; i++)
            {
                fileContents.Add(getPageFromImage(pictures[i], i));
            }
            fileContents.Add(part2);
            return getFileContent(fileContents);
        }

        private string getKids(List<Picture> pictures)
        {
            string kids = "/Kids[";
            for (int i = 0; i < pictures.Count; i++)
            {
                kids += (3 * (i + 1) + 1) + " 0 R ";
            }
            kids += "]\n";
            return kids;
        }

        private sbyte[] getPageFromImage(Picture picture, int P)
        {
            int N = (P + 1) * 3;
            string imageStart =
            N + " 0 obj\n" +
            "<<\n" +
            "/Type /XObject\n" +
            "/Subtype /Image\n" +
            "/Width " + picture.Width + "\n" +
             "/Height " + picture.Height + "\n" +
              "/BitsPerComponent 8\n" +
               "/ColorSpace /DeviceRGB\n" +
               "/Filter /DCTDecode\n" +
               "/Length " + picture.Data.Length + "\n" +
                ">>\n" +
                "stream\n";

            string dimentions = "q\n" +
            picture.Width + " 0 0 " + picture.Height + " 0 0 cm\n" +
            "/X0 Do\n" +
            "Q\n";

            string imageEnd =
                "\nendstream\n" +
                "endobj\n" +
                (N + 2) + " 0 obj\n" +
                "<<\n" +
                "/Filter []\n" +
                "/Length " + dimentions.Length + "\n" +
                ">>\n" +
                "stream\n";

            string page =
                "\nendstream\n" +
                "endobj\n" +
                (N + 1) + " 0 obj\n" +
                "<<\n" +
                "/Type /Page\n" +
                "/MediaBox[0 0 " + picture.Width + " " + picture.Height + "]\n" +
                "/Resources <<\n" +
                "/XObject <<\n" +
                "/X0 " + N + " 0 R\n" +
                ">>\n" +
                ">>\n" +
                "/Contents 5 0 R\n" +
                "/Parent 2 0 R\n" +
                ">>\n" +
                "endobj\n";

            List<sbyte[]> fileContents = new List<sbyte[]>();
            fileContents.Add(imageStart.GetBytes());
            fileContents.Add(byteArrayToSbyteArray(picture.Data));
            fileContents.Add(imageEnd.GetBytes());
            fileContents.Add(dimentions.GetBytes());
            fileContents.Add(page.GetBytes());
            return getFileContent(fileContents);
        }

        private sbyte[] byteArrayToSbyteArray(byte[] data)
        {
            sbyte[] data2 = new sbyte[data.Length];
            for (int i = 0; i < data2.Length; i++)
            {
                data2[i] = (sbyte)data[i];
            }
            return data2;
        }

        private sbyte[] getFileContent(List<sbyte[]> fileContents)
        {
            int fileSize = 0;
            foreach (sbyte[] content in fileContents)
            {
                fileSize += content.Length;
            }
            sbyte[] finaleFile = new sbyte[fileSize];
            int index = 0;
            foreach (sbyte[] content in fileContents)
            {
                for (int i = 0; i < content.Length; i++)
                {
                    finaleFile[index + i] = content[i];
                }
                index += content.Length;
            }
            return finaleFile;
        }
    }
}

您可以通过这种简单的方式使用代码

////////////////////////////// ///////////导出PDF////////////////////////////////////// /

    private sbyte[] exportPDF(List<Picture> images)
    {
        if (imageBytesList.Count > 0)
        {
            PDFExport pdfExport = new PDFExport();
            sbyte[] fileData = pdfExport.createFile(images);
            return fileData;
        }
        return null;
    }

If you want to do it in a cross-platform way, without any thirty part library,
or paying any license, you can use this code.
It takes an array of pictures (I think it only works only with jpg) with its sizes and return a pdf file, with one picture per page.

You have to create two files:

File Picture:

using System;
using System.Collections.Generic;
using System.Text;

namespace PDF
{
    public class Picture
    {
        private byte[] data;
        private int width;
        private int height;

        public byte[] Data { get => data; set => data = value; }
        public int Width { get => width; set => width = value; }
        public int Height { get => height; set => height = value; }
    }
}

File PDFExport:

using System;
using System.Collections.Generic;

namespace PDF
{
    public class PDFExport
    {
        private string company = "Your Company Here";

        public sbyte[] createFile(List<Picture> pictures)
        {
            int N = (pictures.Count + 1) * 3;
            string dateTimeStr = DateTime.Now.ToString("yyyyMMddhhmmss");

            string file1 =
            "%PDF-1.4\n";

            string file2 =
                "2 0 obj\n" +
                "<<\n" +
                "/Type /Pages\n" +
                getKids(pictures) +
                "/Count " + pictures.Count + "\n" +
                 ">>\n" +
                 "endobj\n" +
                "1 0 obj\n" +
                "<<\n" +
                "/Type /Catalog\n" +
                "/Pages 2 0 R\n" +
                "/PageMode /UseNone\n" +
                "/PageLayout /SinglePage\n" +
                 "/Metadata 7 0 R\n" +
                 ">>\n" +
                  "endobj\n" +
                N + " 0 obj\n" +
                "<<\n" +
                "/Creator(" + company + ")\n" +
                "/Producer(" + company + ")\n" +
                "/CreationDate (D:" + dateTimeStr + ")\n" +
                "/ModDate (D:" + dateTimeStr + ")\n" +
                ">>\n" +
                "endobj\n" +
                "xref\n" +
                "0 " + (N + 1) + "\n" +
                "0000000000 65535 f\n" +
                "0000224088 00000 n\n" +
                "0000224031 00000 n\n" +
                "0000000015 00000 n\n" +
                "0000222920 00000 n\n" +
                "0000222815 00000 n\n" +
                "0000224153 00000 n\n" +
                "0000223050 00000 n\n" +
                "trailer\n" +
                "<<\n" +
                "/Size " + (N + 1) + "\n" +
                 "/Root 1 0 R\n" +
                  "/Info 6 0 R\n" +
                   ">>\n" +
                   "startxref\n" +
                "0\n" +
                "%% EOF";

            sbyte[] part1 = file1.GetBytes();
            sbyte[] part2 = file2.GetBytes();

            List<sbyte[]> fileContents = new List<sbyte[]>();
            fileContents.Add(part1);
            for (int i = 0; i < pictures.Count; i++)
            {
                fileContents.Add(getPageFromImage(pictures[i], i));
            }
            fileContents.Add(part2);
            return getFileContent(fileContents);
        }

        private string getKids(List<Picture> pictures)
        {
            string kids = "/Kids[";
            for (int i = 0; i < pictures.Count; i++)
            {
                kids += (3 * (i + 1) + 1) + " 0 R ";
            }
            kids += "]\n";
            return kids;
        }

        private sbyte[] getPageFromImage(Picture picture, int P)
        {
            int N = (P + 1) * 3;
            string imageStart =
            N + " 0 obj\n" +
            "<<\n" +
            "/Type /XObject\n" +
            "/Subtype /Image\n" +
            "/Width " + picture.Width + "\n" +
             "/Height " + picture.Height + "\n" +
              "/BitsPerComponent 8\n" +
               "/ColorSpace /DeviceRGB\n" +
               "/Filter /DCTDecode\n" +
               "/Length " + picture.Data.Length + "\n" +
                ">>\n" +
                "stream\n";

            string dimentions = "q\n" +
            picture.Width + " 0 0 " + picture.Height + " 0 0 cm\n" +
            "/X0 Do\n" +
            "Q\n";

            string imageEnd =
                "\nendstream\n" +
                "endobj\n" +
                (N + 2) + " 0 obj\n" +
                "<<\n" +
                "/Filter []\n" +
                "/Length " + dimentions.Length + "\n" +
                ">>\n" +
                "stream\n";

            string page =
                "\nendstream\n" +
                "endobj\n" +
                (N + 1) + " 0 obj\n" +
                "<<\n" +
                "/Type /Page\n" +
                "/MediaBox[0 0 " + picture.Width + " " + picture.Height + "]\n" +
                "/Resources <<\n" +
                "/XObject <<\n" +
                "/X0 " + N + " 0 R\n" +
                ">>\n" +
                ">>\n" +
                "/Contents 5 0 R\n" +
                "/Parent 2 0 R\n" +
                ">>\n" +
                "endobj\n";

            List<sbyte[]> fileContents = new List<sbyte[]>();
            fileContents.Add(imageStart.GetBytes());
            fileContents.Add(byteArrayToSbyteArray(picture.Data));
            fileContents.Add(imageEnd.GetBytes());
            fileContents.Add(dimentions.GetBytes());
            fileContents.Add(page.GetBytes());
            return getFileContent(fileContents);
        }

        private sbyte[] byteArrayToSbyteArray(byte[] data)
        {
            sbyte[] data2 = new sbyte[data.Length];
            for (int i = 0; i < data2.Length; i++)
            {
                data2[i] = (sbyte)data[i];
            }
            return data2;
        }

        private sbyte[] getFileContent(List<sbyte[]> fileContents)
        {
            int fileSize = 0;
            foreach (sbyte[] content in fileContents)
            {
                fileSize += content.Length;
            }
            sbyte[] finaleFile = new sbyte[fileSize];
            int index = 0;
            foreach (sbyte[] content in fileContents)
            {
                for (int i = 0; i < content.Length; i++)
                {
                    finaleFile[index + i] = content[i];
                }
                index += content.Length;
            }
            return finaleFile;
        }
    }
}

You can use the code in this easy way

///////////////////////////////////////Export PDF//////////////////////////////////////

    private sbyte[] exportPDF(List<Picture> images)
    {
        if (imageBytesList.Count > 0)
        {
            PDFExport pdfExport = new PDFExport();
            sbyte[] fileData = pdfExport.createFile(images);
            return fileData;
        }
        return null;
    }

您需要安装 Acrobat。在 Acrobat DC 上测试。这是 VB.net 代码。由于这些对象是 COM 对象,因此您应该执行“释放对象”,而不仅仅是“=Nothing”。您可以在此处转换此代码:https://converter.telerik.com/

Private Function ImageToPDF(ByVal FilePath As String, ByVal DestinationFolder As String) As String
    Const PDSaveCollectGarbage  As Integer = 32
    Const PDSaveLinearized      As Integer = 4
    Const PDSaveFull            As Integer = 1
    Dim PDFAVDoc                As Object = Nothing
    Dim PDFDoc                  As Object = Nothing

    Try
        'Check destination requirements
        If Not DestinationFolder.EndsWith("\") Then DestinationFolder += "\"
        If Not System.IO.Directory.Exists(DestinationFolder) Then Throw New Exception("Destination directory does not exist: " & DestinationFolder)
        Dim CreatedFile As String = DestinationFolder & System.IO.Path.GetFileNameWithoutExtension(FilePath) & ".pdf"
        'Avoid conflicts, therefore previous file there will be deleted
        If File.Exists(CreatedFile) Then File.Delete(CreatedFile)

        'Get PDF document
        PDFAVDoc = GetPDFAVDoc(FilePath)
        PDFDoc = PDFAVDoc.GetPDDoc

        If Not PDFDoc.Save(PDSaveCollectGarbage Or PDSaveLinearized Or PDSaveFull, CreatedFile) Then Throw New Exception("PDF file cannot be saved: " & PDFDoc.GetFileName())
        If Not PDFDoc.Close() Then Throw New Exception("PDF file could not be closed: " & PDFDoc.GetFileName())
        PDFAVDoc.Close(1)
        Return CreatedFile
    Catch Ex As Exception
        Throw Ex
    Finally
        System.Runtime.InteropServices.Marshal.ReleaseComObject(PDFDoc)
        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(PDFDoc)
        PDFDoc = Nothing
        System.Runtime.InteropServices.Marshal.ReleaseComObject(PDFAVDoc)
        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(PDFAVDoc)
        PDFAVDoc = Nothing
        GC.Collect()
        GC.WaitForPendingFinalizers()
        GC.Collect()
    End Try
End Function

You need Acrobat to be installed. Tested on Acrobat DC. This is a VB.net code. Due to that these objects are COM objects, you shall do a 'release object', not just a '=Nothing". You can convert this code here: https://converter.telerik.com/

Private Function ImageToPDF(ByVal FilePath As String, ByVal DestinationFolder As String) As String
    Const PDSaveCollectGarbage  As Integer = 32
    Const PDSaveLinearized      As Integer = 4
    Const PDSaveFull            As Integer = 1
    Dim PDFAVDoc                As Object = Nothing
    Dim PDFDoc                  As Object = Nothing

    Try
        'Check destination requirements
        If Not DestinationFolder.EndsWith("\") Then DestinationFolder += "\"
        If Not System.IO.Directory.Exists(DestinationFolder) Then Throw New Exception("Destination directory does not exist: " & DestinationFolder)
        Dim CreatedFile As String = DestinationFolder & System.IO.Path.GetFileNameWithoutExtension(FilePath) & ".pdf"
        'Avoid conflicts, therefore previous file there will be deleted
        If File.Exists(CreatedFile) Then File.Delete(CreatedFile)

        'Get PDF document
        PDFAVDoc = GetPDFAVDoc(FilePath)
        PDFDoc = PDFAVDoc.GetPDDoc

        If Not PDFDoc.Save(PDSaveCollectGarbage Or PDSaveLinearized Or PDSaveFull, CreatedFile) Then Throw New Exception("PDF file cannot be saved: " & PDFDoc.GetFileName())
        If Not PDFDoc.Close() Then Throw New Exception("PDF file could not be closed: " & PDFDoc.GetFileName())
        PDFAVDoc.Close(1)
        Return CreatedFile
    Catch Ex As Exception
        Throw Ex
    Finally
        System.Runtime.InteropServices.Marshal.ReleaseComObject(PDFDoc)
        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(PDFDoc)
        PDFDoc = Nothing
        System.Runtime.InteropServices.Marshal.ReleaseComObject(PDFAVDoc)
        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(PDFAVDoc)
        PDFAVDoc = Nothing
        GC.Collect()
        GC.WaitForPendingFinalizers()
        GC.Collect()
    End Try
End Function
黯然#的苍凉 2024-08-16 10:59:25

不确定您是否正在寻找免费/开源解决方案或也考虑商业解决方案。但如果您要包含商业解决方案,可以使用名为 EasyPDF SDK 的工具包,它提供了用于将图像(以及许多其他文件类型)转换为 PDF 的 API。它支持 C#,可以在这里找到:

 http://www.pdfonline.com/

C# 代码如下所示:

 Printer oPrinter = new Printer();

 ImagePrintJob oPrintJob = oPrinter.ImagePrintJob;
 oPrintJob.PrintOut(imageFile, pdfFile);

为了完全透明,我应该否认我为 EasyPDF SDK 的制作者工作(因此是我的处理方式),所以这个建议不无一些个人偏见:) 但如果您有兴趣,请随时查看评估版本。干杯!

not sure if you're looking for just free / open source solutions or considering commercial ones as well. But if you're including commercial solutions, there's a toolkit called EasyPDF SDK that offers an API for converting images (plus a number of other file types) to PDF. It supports C# and can be found here:

 http://www.pdfonline.com/

The C# code would look as follows:

 Printer oPrinter = new Printer();

 ImagePrintJob oPrintJob = oPrinter.ImagePrintJob;
 oPrintJob.PrintOut(imageFile, pdfFile);

To be fully transparent, I should disclaim that I do work for the makers of EasyPDF SDK (hence my handle), so this suggestion is not without some personal bias :) But feel free to check out the eval version if you're interested. Cheers!

耀眼的星火 2024-08-16 10:59:25

我使用Sautinsoft,它非常简单:

SautinSoft.PdfMetamorphosis p = new SautinSoft.PdfMetamorphosis();
p.Serial="xxx";
p.HtmlToPdfConvertStringToFile("<html><body><img src=\""+filename+"\"></img></body></html>","output.pdf");

I use Sautinsoft, its very simple:

SautinSoft.PdfMetamorphosis p = new SautinSoft.PdfMetamorphosis();
p.Serial="xxx";
p.HtmlToPdfConvertStringToFile("<html><body><img src=\""+filename+"\"></img></body></html>","output.pdf");
蒲公英的约定 2024-08-16 10:59:25

您可以尝试使用此代码示例将任何图像转换为 PDF:

PdfVision v = new PdfVision();
        ImageToPdfOptions options = new ImageToPdfOptions();
        options.JpegQuality = 95;

        try
        {
            v.ConvertImageToPdf(new string[] {inpFile}, outFile, options);
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
            Console.ReadLine();
        }

或者如果您需要将图像类转换为 PDF:

System.Drawing.Image image = Image.FromFile(@"..\..\image-jpeg.jpg");
        string outFile = new FileInfo(@"Result.pdf").FullName;

        PdfVision v = new PdfVision();
        ImageToPdfOptions options = new ImageToPdfOptions();
        options.PageSetup.PaperType = PaperType.Auto;


        byte[] imgBytes = null;

        using (MemoryStream ms = new System.IO.MemoryStream())
        {
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            imgBytes = ms.ToArray();
        }

        try
        {
            v.ConvertImageToPdf(imgBytes, outFile, options);
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
            Console.ReadLine();
        }

You may try to convert any Images to PDF using this code sample:

PdfVision v = new PdfVision();
        ImageToPdfOptions options = new ImageToPdfOptions();
        options.JpegQuality = 95;

        try
        {
            v.ConvertImageToPdf(new string[] {inpFile}, outFile, options);
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });
        }
        catch (Exception ex)
        {
            Console.WriteLine(
quot;Error: {ex.Message}");
            Console.ReadLine();
        }

Or if you need to convert Image Class to PDF:

System.Drawing.Image image = Image.FromFile(@"..\..\image-jpeg.jpg");
        string outFile = new FileInfo(@"Result.pdf").FullName;

        PdfVision v = new PdfVision();
        ImageToPdfOptions options = new ImageToPdfOptions();
        options.PageSetup.PaperType = PaperType.Auto;


        byte[] imgBytes = null;

        using (MemoryStream ms = new System.IO.MemoryStream())
        {
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            imgBytes = ms.ToArray();
        }

        try
        {
            v.ConvertImageToPdf(imgBytes, outFile, options);
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });
        }
        catch (Exception ex)
        {
            Console.WriteLine(
quot;Error: {ex.Message}");
            Console.ReadLine();
        }
盗琴音 2024-08-16 10:59:25

有很多差异工具。我使用的一个是 PrimoPDF(免费)http://www.primopdf.com/ 你可以打印文件并将其以 pdf 格式打印到您的驱动器上。适用于 Windows

Many diff tools out there. One I use is PrimoPDF (FREE) http://www.primopdf.com/ you go to print the file and you print it to pdf format onto your drive. works on Windows

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文