使用ItextSharp将大PNG导出为PDF
本文关键字:PDF PNG ItextSharp 将大 使用 | 更新日期: 2023-09-27 18:21:23
我有一个宽度为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();
}
如何在多页上导出全尺寸的大图像?
您需要缩放图片,然后像这样添加:
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();
}
如果你想让jpg
填满页面的全部大小,你需要缩放它。
例如:
Rectangle rect = document.getPageSize();
jpg.scaleAbsolute(rect.getWidth(), rect.getHeight());
我想你希望图像在背景中。在当前的代码示例中,添加图像,然后在图像下添加一些文本(或此页上的文本和下一页上的图像,或此页的图像和下一页面上的文本,具体取决于图像的大小)。
如果你想在文本下添加图像,你需要:
jpg.setAbsolutePosition(0, 0);
最后,您希望将图像添加到创建的每个页面中。我刚刚回答了一个为每页添加边框的问题:如何使用iText库5.5.2 为整个pdf页面绘制边框
请阅读我对这个问题的回答,并创建一个页面事件,看起来像这样:
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);
}
}
我没有测试这个代码,我即兴写的。你可能需要稍微调整一下。