【问题标题】:Converting multiple TIFF Images to PDF using iTextSharp使用 iTextSharp 将多个 TIFF 图像转换为 PDF
【发布时间】:2019-06-12 11:17:26
【问题描述】:

我在 ASP.NET 和 iTextSharp PDF 库 中使用 WebSite。我有一个包含 3 页的 tiff 文档图像,我想将所有这 3 个 tiff 页面转换为 1 个 3 页的 PDF 文件。

我试试这个,但效果不好......

请告诉我该怎么办?

using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

Document document = new Document();
using (var stream = new FileStream(@"C:\File\0.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
{
    PdfWriter.GetInstance(document, stream);
    document.Open();
    using (var imageStream = new FileStream(@"C:\File\0.tiff", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    {
        var image = iTextSharp.text.Image.GetInstance(imageStream);
        document.Add(image);
    }
    document.Close();
}

【问题讨论】:

  • @mjwills 此代码仅将一页转换为 PDF,我在该文件中有 3 页,我应该说 TIFF 文件正在转换为 PDF 只是图片的一小部分
  • 见this answer,foreach循环的内容(foreach (string image in files))
  • @jesse-de-wit 我的代码的哪一部分?你能显示为答案吗?

标签: c# asp.net itext


【解决方案1】:
// creation of the document with a certain size and certain margins
iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0);

// creation of the different writers
iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(Server.MapPath("~/App_Data/result.pdf"), System.IO.FileMode.Create));

// load the tiff image and count the total pages
System.Drawing.Bitmap bm = new System.Drawing.Bitmap(Server.MapPath("~/App_Data/source.tif"));
int total = bm.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);

document.Open();
iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;
for (int k = 0; k < total; ++k)
{
    bm.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k);
    iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bm, System.Drawing.Imaging.ImageFormat.Bmp);
    // scale the image to fit in the page
    img.ScalePercent(72f / img.DpiX * 100);
    img.SetAbsolutePosition(0, 0);
    cb.AddImage(img);
    document.NewPage();
}
document.Close();

【讨论】:

    【解决方案2】:

    我刚刚从this answer 复制了代码,并将其修改为您的示例。因此,功劳归于在链接中回答问题的人。

    using (var stream = new FileStream(@"C:\File\0.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
    {
        Document document = new Document(PageSize.A4, 0, 0, 0, 0);
        var writer = PdfWriter.GetInstance(document, stream);    
        var bitmap = new System.Drawing.Bitmap(@"C:\File\0.tiff"); 
        var pages = bitmap.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);
    
        document.Open();
        iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;
        for (int i = 0; i < pages; ++i)
        {
            bitmap.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, i);
            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bitmap, System.Drawing.Imaging.ImageFormat.Bmp);
            // scale the image to fit in the page 
            //img.ScalePercent(72f / img.DpiX * 100);
            //img.SetAbsolutePosition(0, 0);
            cb.AddImage(img);
            document.NewPage();
        }
       }
       document.Close();
    }
    

    【讨论】:

    • 谢谢你的朋友,但请告诉我应该如何在 PDF 页面中放置图像。现在我将 TIFF 文件转换为 PDF 但 PDF 文件没有打开并且有错误:(
    • 您是否取消了缩放和位置部分的注释?另外,在第二行代码中添加了文档大小。
    • 是的。我编写了您的示例并执行了程序,它可以正常工作,但结果 PDF 没有打开
    • 如果您尝试在文档中添加页面大小。请参阅更新的答案。还是让 scalepercent 真的很小?
    • 试试 70f。如果这不起作用,请尝试 3f,以确保大小是问题所在。如果这不起作用,恐怕我无法为您提供帮助。
    【解决方案3】:

    我在很长一段时间后根据一些搜索取得的成果。

    我提出请求,响应为 PDF 或 TIFF。第一部分是我得到的以及我如何调用私有方法,这就是你所需要的。

    var httpResponse = (HttpWebResponse)(await httpWebRequest.GetResponseAsync());
    Stream stream = httpResponse.GetResponseStream();
    string contentType = httpResponse.ContentType;
    MemoryStream ms = new MemoryStream();
    stream.CopyTo(ms);
    FileStream file2;
    try
    {
        switch (contentType)
        {
            case "application/pdf":
                {
    
                    string outputfile2 = Path.Combine(zipDirectory, "ixosid_" + icxos + ".pdf");
                    file2 = new FileStream(outputfile2, FileMode.Create, FileAccess.Write);
                    ms.WriteTo(file2);
                    file2.Close();
                    break;
                }
    
            default:
                {
    
    
                    string outputfile1 = Path.Combine(zipDirectory, "ixosid_" + icxos + ".tiff");
                    file2 = new FileStream(outputfile1, FileMode.Create, FileAccess.Write);
                    ms.WriteTo(file2);
                    file2.Close();
    
                    string[] outfilesTiffPages = ConvertTiffToJpeg(outputfile1);
                    File.Delete(outputfile1);
    
                    string outputfile2 = Path.Combine(zipDirectory, "ixosid_" + icxos + ".pdf");
                    iTextSharp.text.Document doc= AddPicturesToPDF(outfilesTiffPages, outputfile2);
                    
                    break;
                }
    
        }
    }
    

    我有两个私有方法

    private string[] ConvertTiffToJpeg(string fileName)
    {
        using (System.Drawing.Image imageFile = System.Drawing.Image.FromFile(fileName))
        {
            FrameDimension frameDimensions = new FrameDimension(
                imageFile.FrameDimensionsList[0]);
    
            // Gets the number of pages from the tiff image (if multipage) 
            int frameNum = imageFile.GetFrameCount(frameDimensions);
            string[] jpegPaths = new string[frameNum];
    
            for (int frame = 0; frame < frameNum; frame++)
            {
                // Selects one frame at a time and save as jpeg. 
                imageFile.SelectActiveFrame(frameDimensions, frame);
                using (Bitmap bmp = new Bitmap(imageFile))
                {
                    jpegPaths[frame] = String.Format(@"{0}\{1}{2}.jpg",
                        Path.GetDirectoryName(fileName),
                        Path.GetFileNameWithoutExtension(fileName),
                        frame);
                    bmp.Save(jpegPaths[frame], ImageFormat.Jpeg);
                }
            }
    
            return jpegPaths;
        }
    }
    
    private iTextSharp.text.Document AddPicturesToPDF(string[] filesPaths, string outputPdf)
    {
        FileStream fs = new FileStream(outputPdf, FileMode.Create);
        Document pdfdoc = new Document();
        PdfWriter.GetInstance(pdfdoc, fs);
        pdfdoc.Open();
        int size = filesPaths.Length;
        int count = 0;
        foreach(string imagePath in filesPaths)
        {
            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imagePath);
            img.Alignment = Element.ALIGN_CENTER;
            img.SetAbsolutePosition(0, 0);
            img.ScaleToFit((PageSize.A4.Width - pdfdoc.RightMargin - pdfdoc.LeftMargin), (PageSize.A4.Height- pdfdoc.BottomMargin - pdfdoc.TopMargin));
            pdfdoc.Add(img);
            pdfdoc.NewPage();
    
        }           
        pdfdoc.Close();
        return pdfdoc;
    }
    

    也许我可以与 MemoryStream 合作,但现在,我正在工作,这正是我所需要的。

    我搜索了很多,有些链接值得一提

    https://coderedirect.com/questions/178295/convert-tiff-to-jpg-format

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-27
      • 1970-01-01
      • 2016-04-24
      • 1970-01-01
      • 2012-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多