使用iTextSharp将多个TIFF图像转换为PDF

时间:2019-06-12 11:17:26

标签: c# asp.net itext

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

2 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分: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();