我正在使用iText库来创建和添加数据。
我想要添加一些textLines和一张图片超过一次,直到我关闭该文件。
numOfSamples = timeIHitTheButton();
.
.
.
*a loop tha call it the number of times choosen by numOfSamples*
DSM.saveData();DataStore (DSM是一个DataStore实例)类正确地创建了文档doc.pdf,并且DSM.addText()和DSM.addPicture()在文件上正确地打印了三个文本行和一个图像,但前提是我只按了一次按钮!!
我想在每次按下按钮时写入相同的字符串和图像(如果我按下它一次,我就有一个样本,如果真的,我有两个样本,等等)。如果我只按它一次并终止,我会得到包含字符串和图片的PDF,但如果我多次按它,我会得到一个无法阅读和损坏的PDF文件。我也不知道原因。我如何继续写图片和字符串,直到完成样本的数量?
我在这里发布了一些有用的代码("newPic1.jpg“"newPic2.jpg”等是要与文本一起添加到PDF文件中的存储图片):
public class DataStore{ ....
.
.
.
public DataStore(String Str1, String Str2, String Str3, int numOfSemples)
throws Exception{
document = new Document();
String1 = str1;
String2 = str2;
String3 = str3;
Samples = numOfSemples;
document.open();
}
privatevoid saveData(){
if(!created){
this.createFile();
created=true;
}
this.addText();
this.addPicture();
}
private void createFile(){
try {
OutputStream file = new FileOutputStream(
new File("Doc.pdf"));
PdfWriter.getInstance(document, file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
private void addText(){
try {
if(Samples > 0)
document.open();
document.add(new Paragraph(Double.toString(String1)));
document.add(new Paragraph(Double.toString(String2)));
document.add(new Paragraph(Double.toString(String3)));
} catch (DocumentException e) {
e.printStackTrace();
}
}
private void addPicture(){
try {
Image img = Image.getInstance("NewPic" + Samples + ".jpg");
document.add(img);
} catch (BadElementException bee) {
bee.printStackTrace();
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (DocumentException dee) {
dee.printStackTrace();
}
if(Samples == 0)
document.close();
else Samples--;
}
}发布于 2013-05-28 16:20:32
您以错误的顺序使用iText命令:
DataStore构造函数创建一个新的Document并调用它的open方法(这还为时过早,因为没有编写器。稍后,在第一个saveData调用中,您调用createFile创建所有saveData调用<Samples > 0,每次< times).createFile时进行在对Samples == 0的saveData调用中,关闭文档。因此,从本质上讲,您可以这样做:
document = new Document();
document.open();
[...]
PdfWriter.getInstance(document, file);
[...]
[for `Samples` times]
document.open();
[add some paragraphs]
[add an image]
[end for]
document.close();将这一点与应该如何做进行比较:
// step 1
Document document = new Document();
// step 2
PdfWriter.getInstance(document, new FileOutputStream(filename));
// step 3
document.open();
// step 4
[add content to the PDF]
// step 5
document.close();(从的示例复制)
只有对于Samples == 1你才是正确的(构造函数中多余的document.open()被忽略,因为还没有编写器);但是对于更大的Samples,值,你可以多次打开文档,有一个编写器在场,这可能会一遍又一遍地向输出流追加一个PDF开头。
您很可能可以通过删除所有当前的document.open()调用(包括addText()中的if(Samples > 0) )并在PdfWriter.getInstance(document, file).之后的createFile()中添加一个来修复该问题
https://stackoverflow.com/questions/16776799
复制相似问题