Bad performance convert tif to pdf using ITextSharp

后端 未结 7 1316
猫巷女王i
猫巷女王i 2021-02-15 17:03

Summary: How can I reduce the amount of time it takes to convert tifs to pdfs using itextsharp?

Background: I\'m convertin

7条回答
  •  醉酒成梦
    2021-02-15 17:26

    I'm not sure what was available when this question was originally posted but it appears iText 5.x has more to offer when converting TIFF to PDF. There is also a basic code sample in iText in Action 2nd Edition "part3.chapter10.PagedImages" and I haven't noticed any performance problems. However, the sample doesn't handle scaling well so I changed it like this:

    public static void AddTiff(Document pdfDocument, Rectangle pdfPageSize, String tiffPath)
    {
        RandomAccessFileOrArray ra = new RandomAccessFileOrArray(tiffPath);
        int pageCount = TiffImage.GetNumberOfPages(ra);
    
        for (int i = 1; i <= pageCount; i++) 
        {
            Image img = TiffImage.GetTiffImage(ra, i);
    
            if (img.ScaledWidth > pdfPageSize.Width || img.ScaledHeight > pdfPageSize.Height)
            {
                if (img.DpiX != 0 && img.DpiY != 0 && img.DpiX != img.DpiY)
                {
                    img.ScalePercent(100f);
                    float percentX = (pdfPageSize.Width * 100) / img.ScaledWidth;
                    float percentY = (pdfPageSize.Height * 100) / img.ScaledHeight;
    
                    img.ScalePercent(percentX, percentY);
                    img.WidthPercentage = 0;
                }
                else
                {
                    img.ScaleToFit(pdfPageSize.Width, pdfPageSize.Height);
                }
            }
    
            Rectangle pageRect = new Rectangle(0, 0, img.ScaledWidth, img.ScaledHeight);
    
            pdfDocument.SetPageSize(pageRect);
            pdfDocument.SetMargins(0, 0, 0, 0);
            pdfDocument.NewPage();
            pdfDocument.Add(img);
        }
    }
    

提交回复
热议问题