开发者

Controlling Image Resolution when coverting a PNG image into a PDF using iTextSharp

开发者 https://www.devze.com 2023-01-11 01:39 出处:网络
I have created a PNG image that is 200 DPI, and perfectly sized for a landscape A4 page size.开发者_如何学运维I needed to convert this to a PDF document, so I\'ve used the iTextSharp library with the

I have created a PNG image that is 200 DPI, and perfectly sized for a landscape A4 page size.开发者_如何学运维 I needed to convert this to a PDF document, so I've used the iTextSharp library with the code below.

This all works, however the image quality has degraded. Any suggestions as to how I might improve this?

Public Sub ConvertPNGtoPDF(ByVal inputFile As String, ByVal outputFile As String)
        Using fs As New FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite, FileShare.None)
            Dim document As New Document(PageSize.A4.Rotate, 0, 0, 0, 0)

            Dim writer As PdfWriter = PdfWriter.GetInstance(document, fs)

            document.Open()

            Dim cb As PdfContentByte = writer.DirectContent

            Using bm As New Bitmap(inputFile)
                Dim total As Integer = bm.GetFrameCount(FrameDimension.Page)

                For k As Integer = 0 To total - 1
                    bm.SelectActiveFrame(FrameDimension.Page, k)
                    Dim img As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(bm, Nothing, False)

                    img.SetDpi(200, 200)
                    img.ScalePercent(72.0F / 200.0F * 100)
                    img.SetAbsolutePosition(0, 0)

                    cb.AddImage(img)
                    document.NewPage()
                Next
            End Using

            document.Close()
            writer.Close()
        End Using

    End Sub


This all works, however the image quality has degraded. Any suggestions as to how I might improve this?

Looking at the code in PngImage, it looks like iText doesn't support PNG compression as a PDF-native filter, so it has to be decompressed and recompressed as Something Else. Is this because the PDF spec doesn't support it:

Just checked, sure looks that way.

Best fix? JPEG and JPEG2000 are supported as "native" compression types within PDF (and this is echoed in iText[sharp]). So use JPEG[2k] instead, and run your images through your image conversion library of choice if need be.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号