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

4
我正在使用ASP.NET和iTextSharp PDF库中的WebSite。我有一个包含3页的tiff文档图像,我想将这所有的3个tiff页面转换为一个有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时仅转换了图片的一小部分。 - Javad Abedi
1
请参考这个答案,其中包含了foreach循环的内容(foreach (string image in files))。 - Jesse de Wit
@jesse-de-wit,我的代码的哪一部分?你能展示一下吗? - Javad Abedi
3个回答

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

0

在长时间的探索和搜索之后,我取得了一些成果。

我发送一个请求,然后响应是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


0
我只是从这个答案中复制了代码,并将其修改为你的例子。所以功劳归于在链接中回答问题的那个人。
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文件无法打开并出现错误:( - Javad Abedi
首先尝试将它们变得非常小,看看是否有效。如果有效,您可以开始担心变量大小。 - Jesse de Wit
1
尝试70f。如果不行,再尝试3f,只是为了确保大小是否是问题。如果还是不行,恐怕我无法帮助您解决这个问题。 - Jesse de Wit
我认为大小是主要问题 :( 因为程序没有任何错误,但结果有问题。我按照您说的尝试了,但PDF无法打开。 - Javad Abedi
那么,你试过3f了吗? - Jesse de Wit
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接