這是非常奇怪的是,你需要下面一行將圖像添加到現有的PDF:
document.Add(image);
這是因爲如果您使用的是PdfWriter
而不是PdfStamper
,這會很奇怪。
也許你忽略了documentation或者你沒有搜索的StackOverflow你開始編寫代碼之前:How can I insert an image with iTextSharp in an existing PDF?
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
class Program
{
static void Main(string[] args)
{
using (Stream inputPdfStream = new FileStream("input.pdf", FileMode.Open, FileAccess.Read, FileShare.Read))
using (Stream inputImageStream = new FileStream("some_image.jpg", FileMode.Open, FileAccess.Read, FileShare.Read))
using (Stream outputPdfStream = new FileStream("result.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
{
var reader = new PdfReader(inputPdfStream);
var stamper = new PdfStamper(reader, outputPdfStream);
var pdfContentByte = stamper.GetOverContent(1);
Image image = Image.GetInstance(inputImageStream);
image.SetAbsolutePosition(100, 100);
pdfContentByte.AddImage(image);
stamper.Close();
}
}
}
您可能已經發現的例子,在使用GetUnderContent()
。這增加了內容下現有的內容。如果您希望內容覆蓋現有內容,則需要代碼示例中顯示的GetOverContent()
。
嗨,謝謝你的調查。我們使用的包裝紙是幾年前寫的,直到現在都運行良好。也許當時使用的示例引用了Document。不確定,會調查。感謝您的建議。 – TheITGuy 2014-10-31 20:04:49
好的,經過進一步調查,我們使用PdfReader和PdfWriter,但出於某種原因使用文檔添加圖像。必須是一個疏忽 - 儘管一直在努力。我們基本上合併了各種文檔,然後添加所需的圖像。對PdfContentByte.AddImage和圖像進行快速更改顯示爲正確分層。 – TheITGuy 2014-10-31 20:25:04
使用PdfWriter和Document會丟棄所有交互功能。請正確使用iText! – 2014-10-31 21:07:20