我正在嘗試使用以下方法將圖像追加到現有PDF。使用iTextSharp將圖像追加到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
值沒有使用,我正在調試它。該值始終爲真,因此添加頁面正在工作。
生成的PDF與原始大小相同,但不可讀。打開時出現無效的根對象錯誤。
有什麼建議嗎?
感謝
當與現有的PDF工作,你需要使用一個PdfStamper,請參閱[如何在現有PDF中插入iTextSharp圖像?](http://stackoverflow.com/questions/583629/how-can-i-insert-an-image-with-itextsharp-in- an-existing-pdf) – 2013-04-11 13:02:57