简体   繁体   English

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

[英]Converting multiple TIFF Images to PDF using iTextSharp

I'm using WebSite in ASP.NET and iTextSharp PDF library .我在ASP.NETiTextSharp PDF library 中使用WebSite I have a tiff document image that contains 3 pages, I would want to convert all those 3 tiff pages into 1 PDF file with 3 pages.我有一个包含 3 页的tiff文档图像,我想将所有这 3 个tiff页转换为 1 个包含 3 页的PDF文件。

I try this but it doesn't work as well...我试试这个,但它也不起作用......

Please tell me what should I do?请告诉我该怎么办?

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

I just copied the code from this answer , and modified it to your example.我刚刚从这个答案中复制了代码,并将其修改为您的示例。 So credits go to the person who answered the question in the link.所以学分归于在链接中回答问题的人。

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

What I achieved after a long period and based on some searches.经过很长一段时间并基于一些搜索,我取得了什么。

I make a request and the response is PDF or TIFF.我提出请求,响应是 PDF 或 TIFF。 The first part is just what I get and how I call the private methods, and that is what you need.第一部分就是我得到的以及我如何调用私有方法,这就是您所需要的。

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

    }
}

and I have two private methods我有两个私有方法

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

Maybe I can work with MemoryStream but for now, is working and is what I need.也许我可以使用MemoryStream工作,但就目前而言,它正在工作并且是我所需要的。

I searched a lot, and some links that deserve to be mentioned我搜索了很多,一些值得一提的链接

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM