【发布时间】:2013-04-11 11:53:24
【问题描述】:
我正在尝试使用以下方法将图像附加到现有 PDF。
public static byte[] Append(byte[] inputPdf, params Image[] images)
{
var ms = new MemoryStream();
ms.Write(inputPdf, 0, inputPdf.Length);
ms.Seek(0, SeekOrigin.Begin);
using (Document pdf = new Document(iTextSharp.text.PageSize.A4, 10, 10, 10, 10))
using (PdfWriter writer = PdfWriter.GetInstance(pdf, ms))
{
pdf.Open();
foreach (var image in images)
{
var result = pdf.NewPage();
ImageFormat format = image.PixelFormat == PixelFormat.Format1bppIndexed
|| image.PixelFormat == PixelFormat.Format4bppIndexed
|| image.PixelFormat == PixelFormat.Format8bppIndexed
? ImageFormat.Tiff
: ImageFormat.Jpeg;
var pdfImage = iTextSharp.text.Image.GetInstance(image, format);
pdfImage.Alignment = Element.ALIGN_CENTER;
pdfImage.ScaleToFit(pdf.PageSize.Width, pdf.PageSize.Height);
pdf.Add(pdfImage);
}
pdf.Close();
}
ms.Flush();
return ms.GetBuffer();
}
result 的值没有使用,我在调试它。该值始终为 true,因此添加页面正在运行。
生成的 PDF 与原始 PDF 大小相同,但不可读。打开时出现无效的根对象错误。
有什么建议吗?
谢谢
【问题讨论】:
-
处理现有 PDF 时,您需要使用 PdfStamper,请参阅 How can I insert an image with iTextSharp in an existing PDF?
标签: c# image pdf itextsharp