【问题标题】:JPG to PDF Convertor in C#C#中的JPG到PDF转换器
【发布时间】:2010-12-11 04:00:36
【问题描述】:

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

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

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

【问题讨论】:

  • 还有 graphicsmagick.org 这是 ImageMagick 的改进版本(代码方面)。不过,我不知道你是否会找到它的 .NET 库。
  • 是否适用于桌面/服务器/Web 应用程序?
  • 它是一个 Web 应用程序,但是这对应用程序的类型没有任何影响,因为编码是相同的

标签: c# pdf jpeg image-conversion


【解决方案1】:

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

【讨论】:

  • 很好,也为整理 +1。作为一个有趣的问题(我已经很久没有使用它了),是否有一种更清洁的方式来使用带有 IDisposable 的 Document 和/或是否应该尝试/最终保护 Close?如果 imageStream 是实际的资源持有者/所有者,大概不会?
  • 我收到“PdfWriter 在当前上下文中不存在”
  • 如何在pdf中添加图片的宽高?
  • 以下似乎可以在不扭曲尺寸的情况下缩小大图像:float maxWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;浮动 maxHeight = document.PageSize.Height - document.TopMargin - document.BottomMargin; if (image.Height > maxHeight || image.Width > maxWidth) image.ScaleToFit(maxWidth, maxHeight);
【解决方案2】:

iTextSharp 做得非常干净并且是开源的。此外,它还有a very good accompanying book by the author,如果您最终会做更多有趣的事情,例如管理表单,我建议您使用它。对于正常使用,邮件列表和新闻组中有大量资源可用于了解如何做常见事情的示例。

编辑:正如@Chirag's comment 中提到的,@Darin's answer 的代码肯定可以与当前版本一起编译。

用法示例:

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 是开源的,但不是免费的。由于他们使用的是 AGPL 许可证,您将不得不支付许可费或将您自己的代码开源。在这里亲自查看:itextpdf.com/terms-of-use/index.php
  • 出现错误 错误 2 'iTextSharp.text.Document':在 using 语句中使用的类型必须隐式转换为 'System.IDisposable'
  • @Chirag 我不记得我当时是否真的编译了代码,或者您是否有可能使用另一个版本(这里是an example of similar code 以确认它在某些时候是有意义的)。但是一般来说,如果它不是一次性的,那么省略using 应该是安全的。等一下,看看@Darin's answer。谢谢指点皇帝的衣服:)
  • 我也已经检查了该代码,有一个问题“该进程无法访问文件“test.jpg”,因为它正在被另一个进程使用。”
  • @Chirag 这样的错误不太可能归结为文档生成中某处缺少 Close / Dispose
【解决方案3】:

另一个工作代码,试试吧

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

【讨论】:

  • 很抱歉打扰了一个 5 岁的答案。但是第 3-8 行对我的 pdf 文件有很大的帮助,其中包含剪切图像内容。谢谢!
【解决方案4】:

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

http://pdfsharp.com/PDFsharp/

【讨论】:

【解决方案5】:

Docotic.Pdf library 的帮助下可以轻松完成此类任务。

这是一个从给定图像(实际上不仅是 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);
    }
}

免责声明:我为图书馆的供应商工作。

【讨论】:

    【解决方案6】:

    您需要安装 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
    

    【讨论】:

      【解决方案7】:

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

       http://www.pdfonline.com/
      

      C# 代码如下所示:

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

      为了完全透明,我应该否认我确实为 EasyPDF SDK 的制造商工作(因此我的处理),所以这个建议并非没有一些个人偏见 :) 但如果你可以随时查看 eval 版本重新感兴趣。干杯!

      【讨论】:

        【解决方案8】:

        我用的是Sautinsoft,很简单:

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

        【讨论】:

          【解决方案9】:

          那里有许多差异工具。我使用的一个是 PrimoPDF (FREE) http://www.primopdf.com/ 你去打印文件,然后把它打印成 pdf 格式到你的驱动器上。适用于 Windows

          【讨论】:

          • 错误答案。他想以编程方式(特别是 C#)来实现。
          猜你喜欢
          • 1970-01-01
          • 2010-11-20
          • 1970-01-01
          • 2016-09-17
          • 2019-05-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-02-21
          相关资源
          最近更新 更多