java - 如何使用itext pdf在页面pdf中插入值

标签 java iterator itext

我尝试将值插入到 pdf 中,如下所示:

String nomeArquivo ="tempRelatorioPDF.pdf";
File file = new File(nomeArquivo);
file.createNewFile();

PdfWriter.getInstance(doc, new FileOutputStream(file)); 
doc.open();     
PdfWriter writer = PdfWriter.getInstance(doc, new `FileOutputStream(nomeArquivo));`
Document doc = new Document(PageSize.A4.rotate());

while(iteratorRow.hasNext()){
   Object valorCelulaRow = iteratorRow.next();

    Paragraph p3 = new Paragraph(); 
    p3.add(colunas[i].getName());
    p3.add("\n"); 
    doc.add((com.itextpdf.text.Element)p3); 

    if(valorCelulaRow != null){

       Paragraph p = new Paragraph(valorCelulaRow.toString());
       doc.add(p); 
}
doc.close();    

显示错误: PDF 文件已损坏 实际上在打开文件时出现错误,该文件似乎已损坏。

**

到达此点之前的调整

** 我为此使用以下库:

import com.itextpdf.text.Chunk;
import com.itextpdf.text.ListItem;

*>>>>> import com.itextpdf.text.Paragraph;*

...
import com.itextpdf.text.DocumentException;

*>>>>> import com.lowagie.text.Document;*

import com.lowagie.text.Element;
import com.lowagie.text.Font;
...

撤退注释库和添加itext时有一个conlito。文档添加错误。

import com.itextpdf.text.Document; 
// import com.lowagie.text.Document;

更改导入引用后出现错误

Document doc = new Document(PageSize.A4.rotate());      

//The constructor Document(Rectangle) is undefined

PdfWriter.getInstance(doc, new FileOutputStream(file)); 

PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(nomeArquivo));
//The method getInstance(Document, OutputStream) in the type PdfWriter is not applicable for the arguments (Document, FileOutputStream)

[部分解决]

添加“(com.itextpdf.text.Element)”

将“添加”更改为“添加”;

调试数据被加载到变量“p”和“P3”中。但生成的 PDF 文档为 0kb。

最佳答案

这应该可行,我不知道为什么不行。我认为你不应该类型转换任何东西。 Paragraph允许使用字符串参数直接构造。我认为您希望该段落的值为 valueCellRow.toString() 正确吗?

Document doc = new Document(PageSize.A4.rotate());
while(iteratorRow.hasNext()) {
    Object valorCelulaRow = iteratorRow.next();
    if(valorCelulaRow != null) {
        Paragraph p = new Paragraph(valueCellRow.toString());
        doc.Add (p);
    }
}
doc.close();  

如果所有其他方法都失败,则说明您的库 (com.lowagie.text.Element vs com.itextpdf.text.Element) 发生冲突。尝试使用:

doc.Add((com.itextpdf.text.Element) p);

尽管您不需要。

关于java - 如何使用itext pdf在页面pdf中插入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32335038/

相关文章:

c++ - unordered_map 中迭代器的效率 (C++)

linux - JasperReports 在 Linux 机器上失败

android - Android 中的 transform.TransformException

Java 图像 IO : Can I convert a PNG-24 file to PNG-8?

java - 当 putifabsent 时间到期时做点什么 [infinispan]

java - LockSupport.park(Object blocker)的参数有什么用?

java - 如何从二进制堆转储中提取jvm参数

java - 更换 map 中的 key ,

c++ - 如何在类中使用重载的 const_iterator?

c# - iTextSharp 索引超出范围