2013-05-29 87 views
1

上下文:我打開一個包含AcroForm字段的現有交互式PDF表單。我試圖圖像中的PDF表單中添加一個矩形場是這樣的:爲什麼使用iTextSharp將圖像添加到文檔時不顯示圖像?

string path = HttpContext.Current.Server.MapPath("includes"); 
string newFile = HttpContext.Current.Server.MapPath("Tmp") + "/completed_gray" +".pdf"; 
string imagepath = HttpContext.Current.Server.MapPath("Tmp"); 
Document doc = new Document(); 
try { 
    PdfWriter.GetInstance(doc, new FileStream(newFile, FileMode.Open)); 
    doc.Open(); 
    iTextSharp.text.Image gif = iTextSharp.text.Image.GetInstance(imagepath + "/CUstomRep_Eng_Col_1_V1.png"); 
    iTextSharp.text.Rectangle rect = pdfStamper.AcroFields.GetFieldPositions("img_1_space")[0].position; 
    gif.ScaleAbsolute(rect.Width, rect.Height); 
    gif.SetAbsolutePosition(rect.Left, rect.Bottom); 
    doc.Add(gif); 
} 
catch (Exception ex) { 
    //Log error; 
} 
finally { 
    doc.Close(); 
} 

在生成的PDF圖像不顯示。

+1

請閱讀關於一些格式問題和http://meta.stackexchange.com/questions/10647/how-do-i-write-a-good-title –

+1

我syour問題 - 你看到一個錯誤?什麼是錯誤信息? – criticalfix

+0

此外:你說你正在填寫一個現有的PDF,你正在使用Document和PdfWriter類?很明顯,你沒有閱讀文檔,否則,你會使用PdfStamper! –

回答

2

您正在使用我書中記錄的「創建PDF文檔的5個步驟」創建文檔。

  1. 創建一個Document對象。
  2. 創建一個PdfWriter實例。
  3. 打開文檔。
  4. 將內容添加到文檔。
  5. 關閉文件。

這與您真正想要做的事情相矛盾:我想在由AcroForm字段定義的佔位符中添加圖像。

爲什麼你說你想要一件事,並做其他事情?打敗我。可能是因爲你不想閱讀文檔。

你需要的東西是這樣的:

  1. 創建PdfReader實例。
  2. 創建一個PDFStamper實例。
  3. 向印模詢問有關這些區域的信息。
  4. 使用壓模實例將內容添加到頁面。
  5. 關閉壓模。

回答您的問題:爲什麼我的圖像沒有出現在我的文檔中?

支持字段的現有文獻中的座標是左下角X = 600,Y = 600和右上角X = 700,Y = 700,那麼你就在可見區域之外添加圖像你正在創建的頁面。當您使用new Document();時,您正在創建一個文檔,左下角爲x = 0,y = 0,右上角爲x = 595,y = 842.

在這種情況下,將圖像重新添加到文檔中,但它不可見,因爲您已將其添加到定義頁面的矩形之外。

+0

非常感謝您,正如您提到的我試過tio使用下面的代碼 –

+0

什麼代碼?我認爲你的評論中缺少某些東西。 –

+0

PdfReader pdfReader = new PdfReader(pdfTemplate); PdfStamper pdfStamper = new PdfStamper(pdfReader,new FileStream(newFile,FileMode.Create)); AcroFields pdfFormFields = pdfStamper.AcroFields; iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(pathh +「/ ADE_RepBtn_Nor.png」); –