gpt4 book ai didi

java - 无法使用 iText 写入 pdf

转载 作者:行者123 更新时间:2023-12-01 14:20:29 26 4
gpt4 key购买 nike

我有一个脚本,它读取 Excel 工作表中的一行,用该行中每个单元格的内容填充数组列表,然后将其写入文本文件。我希望能够将其写入 pdf 文件(使用 iText),以便我也可以在文件中包含图像。问题是我不断收到错误消息,指出文档已关闭并且“无法将元素添加到文档中”。相关代码如下:

    public File processFile(File excelWorkbook) throws FileNotFoundException, IOException, DocumentException{

System.out.println("Processing file...");
FileInputStream fileInputStream = new FileInputStream(excelWorkbook);
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet firstSheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = firstSheet.iterator();
System.out.println("Please choose output file name.");
String fName = this.chooseFileName();
try{
for(int cntr=1; cntr<=firstSheet.getPhysicalNumberOfRows(); cntr++){
ArrayList<String> values = new ArrayList<String>();
Row currentRow = firstSheet.getRow(cntr);

for(int cntr2 = 0; cntr2<currentRow.getLastCellNum(); cntr2++){
Cell currentCell = currentRow.getCell(cntr2, Row.RETURN_NULL_AND_BLANK);
if(currentCell==null){
//cell doesn't have anything in there
values.add("-not in excel file-");
continue;
}else{
switch(currentCell.getCellType()){
case Cell.CELL_TYPE_STRING:
values.add(currentCell.getStringCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:

double num = currentCell.getNumericCellValue();
String numString = String.valueOf(num);
values.add(numString);
break;
}
}

}
//libF = writeArrayListToFile(values, fName);
writePDF(values, fName);//the method that writes to pdf
}

}catch (NullPointerException e){
System.out.println("Cell is null.");
//e.printStackTrace();
}
fileInputStream.close();
return libF;
}

这是 writePDF(ArrayList al, String fName) 方法:

    public void writePDF(ArrayList<String> al, String filepath) throws FileNotFoundException, DocumentException{
PdfWriter.getInstance(document, new FileOutputStream(filepath));
document.open();
document.add(new Paragraph("Library"));
for(String i: al){
document.add(new Phrase(i+"\n"));
}
document.close();
}

为什么我无法连续写入该文件?如果我写入一个文本文件,我可以轻松地关闭它并再次打开它,这样我就可以将 Excel 电子表格中的所有信息获取到一个文本文件中。这似乎不适用于 pdf 文件。它无法轻松打开和关闭。有人可以告诉我应该如何修改我的代码吗?我想要的只是让脚本读取 Excel 工作表中的行,将单元格内容添加到数组列表中,然后立即将数组列表添加到 pdf 文档中。只需要对每一行执行此操作即可。这适用于文本文件,但不适用于 pdf。

最佳答案

您正在将每一写入pdf文档

您的 writePDF 函数有一个字段:

document

在文件打开时没有初始化(相反,我认为它是在构建时初始化的)打开输出文件的同时初始化文档

关于java - 无法使用 iText 写入 pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17623466/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com