我有一个脚本读取Excel工作表中的一行,使用该行中每个单元格的内容填充数组列表,并将其写入文本文件。我希望能够将它写入PDF文件(使用iText),以便我可以在文件中包含图像。问题是我不断收到一个错误,指出文档已关闭,并且“文档不能添加”元素。下面是相关代码:无法使用iText写入pdf
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的人,弦乐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文件和文本文件吗? PDF完全不同。请开始阅读https://leanpub.com/itext_pdfabc/(它是未完成的,但它是免费的)。 –