简体   繁体   中英

How to read in a text file (line-by-line) and use the output as nameS to create .pdf Files in java?

I'm writing a program that would allow me to create several PDF Files with a set of given names (from a text file, each name represented by a line in the file). These PDF Files will have a watermark on each page.

Here's the code I'm using:

    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();}
        }
    }

I was able to produce a .pdf file but the name I got was "New_null.pdf". Plus, I can only generate one .pdf files. I'd like to know how to generate as many .pdf files as the number of names in the given text file.

Any idea would be greatly appreciated.

Thanks a lot in advance.

Zestos.

Create the pdf inside the while loop which gets the lines. Right now, line is null because you reached End of File . Move everything in the loop!.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM