2012-08-30 31 views
3

我試圖用iTextSharp將圖像插入到新創建的PDF文檔中 - 雖然我不確定我是否以正確的方式進行了操作。我創建了一個圖像對象,然後嘗試將其添加到頁面 - 但沒有圖像顯示 - 儘管我插入的文本確實出現在PDF文檔中。使用iTextSharp將圖像插入到PDF中

有沒有人有任何想法?

public bool createPDF(string batchNumber, string userName, string path) 
{ 
    // step 1: creation of a document-object 
    Document myDocument = new Document(PageSize.A4.Rotate()); 

    try 
    { 
     // step 2: 
     // Now create a writer that listens to this doucment and writes the document to desired Stream. 
     PdfWriter.GetInstance(myDocument, new FileStream(path, FileMode.Create)); 

     // step 3: Open the document now using 
     myDocument.Open(); 

     // step 4: Now add some contents to the document 
     // batch Header e.g. Batch Sheet 
     myDocument.Add(new Paragraph("Number: " + batchNumber)); 
     myDocument.Add(new Paragraph("Created By: " + userName)); 

     iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance("code39-barcode.png"); 
     PdfPCell cell = new PdfPCell(logo); 
     myDocument.Add(cell); 
    } 
    catch (DocumentException de) 
    { 
     Console.Error.WriteLine(de.Message); 
    } 
    catch (IOException ioe) 
    { 
     Console.Error.WriteLine(ioe.Message); 
    } 

    // step 5: Remember to close the document 
    myDocument.Close(); 

    return true; 
} 

回答

2

this知道如何添加圖像

不過,我想你錯過桌上的東西。

你應該有一個表,並使用table.addCell增加該小區

PdfPTable table = new PdfPTable(3); 

PdfPCell cell = new PdfPCell(new Phrase("Header spanning 3 columns")); 

this知道如何使用表

+0

大家好,由@maxisam提供的資源已經足夠好了,但是,從我的理解以及我最好的程序員那裏,正在從磁盤驅動器讀取圖片圖像。如果圖片是從數據庫表格中讀取的,它以byte []的形式存儲,該怎麼辦?需要對資源中的代碼進行哪些更改:https://www.mikesdotnetting.com/Article/87/iTextSharp-Working-with-images(如果需要任何源代碼示例,請告訴我) –

0

刪除此:

PdfPCell cell = new PdfPCell(logo); 
myDocument.Add(cell); 

,並使用此:

myDocument.Add(logo); 

它的工作原理:)