首页 文章

使用iTextSharp将图像插入PDF

提问于
浏览
3

我正在尝试使用iTextSharp将图像插入到新创建的PDF文档中 - 尽管我不确定我是否以正确的方式处理它 . 我创建了一个图像对象,然后尝试将其添加到页面中 - 但是没有图像显示 - 尽管我插入的文本确实出现在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 回答

  • 0

    阅读this以了解如何添加图像

    但是,我觉得你错过了 table 的东西 .

    你应该有一个表并使用table.addCell来添加单元格

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

    阅读this以了解如何使用表格

  • 2

    删除这个:

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

    并使用这个:

    myDocument.Add(logo);
    

    它的工作原理:)

相关问题