Convert text into PDF

前端 未结 4 1528
轮回少年
轮回少年 2021-01-26 05:08

I have a huge string of text that is apparently raw data for a PDF file, and I need to make it back into a PDF.

Currently I\'m reading the string into a StringBuffer but

4条回答
  •  情书的邮戳
    2021-01-26 05:38

    The iText approach is the right one. You can do something like this :

    import java.io.*;
    
    import com.lowagie.text.*;
    import com.lowagie.text.pdf.*;
    
    public class TextFileToPDF {
    
      /*
         ex. java TextFileToPDF  c:\temp\text.txt  c:\temp\text.pdf
      */
      public static void main (String [] args){
        BufferedReader input = null;
        Document output = null;
        System.out.println("Convert text file to pdf");
        System.out.println("input  : " + args[0]);
        System.out.println("output : " + args[1]);
        try {
          // text file to convert to pdf as args[0]
          input = 
            new BufferedReader (new FileReader(args[0]));
          // letter 8.5x11
          //    see com.lowagie.text.PageSize for a complete list of page-size constants.
          output = new Document(PageSize.LETTER, 40, 40, 40, 40);
          // pdf file as args[1]
          PdfWriter.getInstance(output, new FileOutputStream (args[1]));
    
          output.open();
          output.addAuthor("RealHowTo");
          output.addSubject(args[0]);
          output.addTitle(args[0]);
    
          String line = "";
          while(null != (line = input.readLine())) {
            System.out.println(line);
            Paragraph p = new Paragraph(line);
            p.setAlignment(Element.ALIGN_JUSTIFIED);
            output.add(p);
          }
          System.out.println("Done.");
          output.close();
          input.close();
          System.exit(0);
        }
        catch (Exception e) {
          e.printStackTrace();
          System.exit(1);
        }
      }
    }
    

提交回复
热议问题