【问题标题】:How to read in a text file (line-by-line) and use the output as nameS to create .pdf Files in java?如何读取文本文件(逐行)并使用输出作为 nameS 在 java 中创建 .pdf 文件?
【发布时间】:2014-12-09 14:55:20
【问题描述】:

我正在编写一个程序,它允许我创建多个具有一组给定名称的 PDF 文件(来自文本文件,每个名称由文件中的一行表示)。这些 PDF 文件的每一页都会有水印。

这是我正在使用的代码:

    public class watermark {    
        public static void main(String[] args) {

            try {
                BufferedReader br = new BufferedReader(new FileReader("D:\\Documents\\java\\listcos.txt"));
                String line;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }

                try {
                    String a = line;
                    PdfReader Read_PDF_To_Watermark = new PdfReader("Sample.pdf");
                    int number_of_pages = Read_PDF_To_Watermark.getNumberOfPages();
                    PdfStamper stamp = new PdfStamper(Read_PDF_To_Watermark, new FileOutputStream("New_" + line + ".pdf"));
                    int i = 0;
                    Image watermark_image = Image.getInstance("watermark.jpg");
                    watermark_image.setAbsolutePosition(20, 40);
                    PdfContentByte add_watermark;            
                    while (i < number_of_pages) {
                      i++;
                      add_watermark = stamp.getUnderContent(i);
                      add_watermark.addImage(watermark_image);
                    }
                    stamp.close();
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("Done");
            }catch (IOException e) {
                e.printStackTrace();}
        }
    }

我能够生成一个 .pdf 文件,但我得到的名称是“New_null.pdf”。另外,我只能生成一个 .pdf 文件。我想知道如何生成与给定文本文件中名称数量一样多的 .pdf 文件。

任何想法将不胜感激。

非常感谢。

Zestos。

【问题讨论】:

  • 你得到了 null,因为 line 已经到达文件的末尾并且为 null。您已经使用每一行的文件名在该 while 循环中创建了一个 pdf。不是你只创建一个pdf,名称=文件结尾为空。查看您的代码
  • @MihaiC:非常感谢您指出这一点。我意识到我只需要将while 之后的“}”移动到System.out.println("Done"); 下面的行。
  • 就是这样 :) 现在可以用了吗?
  • 是的。效果很好。并且创建多个Pdf文件的问题也得到了解决。打印出该行时,它还创建了一个带有打印名称的文件。真是太棒了!
  • 我知道问这个问题真的很傻。但是我怎样才能接受答案呢?

标签: java file pdf text line-by-line


【解决方案1】:

while loop 中创建 pdf,获取行。现在,线路是null,因为您到达了End of File。移动循环中的所有内容!。

【讨论】:

    猜你喜欢
    • 2014-11-11
    • 1970-01-01
    • 2014-06-13
    • 2015-12-14
    • 2011-08-17
    • 1970-01-01
    • 2016-11-20
    • 2020-03-10
    • 1970-01-01
    相关资源
    最近更新 更多