【问题标题】:How to calculate the correct image size in out pdf using itextsharp?如何使用 itextsharp 计算输出 pdf 中的正确图像大小?
【发布时间】:2010-05-02 07:43:38
【问题描述】:

我正在尝试使用 itextsharp 将图像添加到 pdf 中,无论图像大小如何,它似乎总是映射到 pdf 中更大的不同尺寸?

我添加的图像是 624x500 像素 (DPI:72):

alt text http://www.freeimagehosting.net/uploads/727711dc70.png

这是输出pdf的屏幕:

alt text http://www.freeimagehosting.net/uploads/313d49044d.png

这是我创建文档的方式:

Document document = new Document();                
                System.IO.MemoryStream stream = new MemoryStream();
                PdfWriter writer = PdfWriter.GetInstance(document, stream);
                document.Open();


                System.Drawing.Image pngImage = System.Drawing.Image.FromFile("test.png");
                Image pdfImage = Image.GetInstance(pngImage, System.Drawing.Imaging.ImageFormat.Png);


                document.Add(pdfImage);
                document.Close();

                byte[] buffer = stream.GetBuffer();
                FileStream fs = new FileStream("test.pdf", FileMode.Create);
                fs.Write(buffer, 0, buffer.Length);
                fs.Close();

关于如何计算正确尺寸的任何想法?

我已经尝试过 ScaleAbsolute,但图像仍然以不正确的尺寸呈现。

【问题讨论】:

    标签: itextsharp dpi


    【解决方案1】:

    我忘了说我使用的是 itextsharp 5.0.2。

    原来PDF DPI = 110,表示每英寸110个像素,而且由于itextsharp使用点作为测量单位,那么:

    • n 像素 = n/110 英寸。
    • n 英寸 = n * 72 点。

    我只需要一个将像素转换为点的辅助方法:

    public static float PixelsToPoints(float value,int dpi)
    {
       return value / dpi * 72;
    }
    

    通过使用上面的公式并传递 110 的 dpi 值,它可以完美地工作:

    注意:由于您可以创建任意大小的 pdf 文档,因此在打印文档时可能会导致缩放不正确。要克服这个问题,您需要做的就是在宽度和高度之间设置正确的纵横比 [大约 1:1.4142](请参阅:Paper Size - The international standard: ISO 216)。

    【讨论】:

      【解决方案2】:

      将图像的高度和宽度乘以 72,然后除以 dpi(ppi):points = pixels * 72 / dpi

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-09
        • 2011-04-01
        • 2018-05-10
        • 2018-07-10
        • 2011-05-18
        • 1970-01-01
        • 2012-02-01
        • 1970-01-01
        相关资源
        最近更新 更多