使用ItextSharp将大PNG导出为PDF

时间:2014-09-10 07:26:20

标签: c# image pdf itextsharp

我有一张宽度为1024px,高度为100000px的图像 我想将此图像导出为完整尺寸的pdf,但图像仅放在第一页上,..

这是我的代码:

Document doc = new Document();
try
{
    iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new FileStream(generatedPdfSaveFilePath, FileMode.Create));
    doc.Open();
    Image jpg = Image.GetInstance(imagePath);
    jpg.Border = Rectangle.BOX;
    jpg.BorderWidth = 5f;
    doc.Add(jpg);
    doc.Add(new Paragraph("Original Width: " + jpg.Width.ToString()));
    doc.Add(new Paragraph("Original Height " + jpg.Height.ToString()));
    doc.Add(new Paragraph("Scaled Width: " + jpg.ScaledWidth.ToString()));
    doc.Add(new Paragraph("Scaled Height " + jpg.ScaledHeight.ToString()));
    float Resolution = jpg.Width / jpg.ScaledWidth * 72f;
    doc.Add(new Paragraph("Resolution: " + Resolution));
}
catch (Exception ex)
{
    //Log error;
}
finally
{
    doc.Close();
}

如何在多个页面上导出全尺寸的大图像?

2 个答案:

答案 0 :(得分:2)

您需要缩放图片,然后像这样添加:

Document doc = new Document();
try
{
    iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new FileStream(generatedPdfSaveFilePath, FileMode.Create));
    doc.Open();
    Image jpg = Image.GetInstance(imagePath);
    jpg.Border = Rectangle.BOX;
    jpg.BorderWidth = 5f;

    var jpeg = new Jpeg(jpg);
    jpeg.ScaleToFit(doc.PageSize.Width - (doc.LeftMargin + doc.RightMargin),
        doc.PageSize.Height - (doc.BottomMargin + doc.TopMargin));

    doc.Add(jpeg);

    doc.Add(new Paragraph("Original Width: " + jpg.Width.ToString()));
    doc.Add(new Paragraph("Original Height " + jpg.Height.ToString()));
    doc.Add(new Paragraph("Scaled Width: " + jpeg.ScaledWidth.ToString()));
    doc.Add(new Paragraph("Scaled Height " + jpeg.ScaledHeight.ToString()));
    float Resolution = jpg.Width / jpg.ScaledWidth * 72f;
    doc.Add(new Paragraph("Resolution: " + Resolution));
}
catch (Exception ex)
{
    //Log error;
}
finally
{
    doc.Close();
}

答案 1 :(得分:0)

如果您希望jpg填充页面的完整大小,则需要对其进行缩放。

例如:

Rectangle rect = document.getPageSize();
jpg.scaleAbsolute(rect.getWidth(), rect.getHeight());

我假设您希望图像在后台。在当前的代码示例中,添加图像,然后在图像下添加一些文本(或此页面上的文本和下一页上的图像,或此页面上的图像和下一页上的文本,具体取决于图像的大小)。

如果要在文本下添加图像,则需要:

jpg.setAbsolutePosition(0, 0);

最后,您要将图像添加到每个创建的页面。我刚回答了一个为每个页面添加边框的问题:How to draw border for whole pdf pages using iText library 5.5.2

请阅读我对该问题的回答,并创建一个如下所示的页面事件:

public class BackgroundImage extends PdfPageEventHelper {

    Image jpg;

    public BackgroundImage(Image jpg) {
         this.jpg = jpg;
    }

    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        PdfContentByte canvas = writer.getDirectContent();
        Rectangle rect = document.getPageSize();
        jpg.scaleAbsolute(rect.getWidth(), rect.getHeight());
        jpg.setAbsolutePosition(0, 0);
        canvas.addImage(jpg);
    }
}

我没有测试这个代码,我把它从袖口上写下来。您可能需要稍微调整一下。

相关问题