Skip to content

Instantly share code, notes, and snippets.

@JoelGeraci-Datalogics
Last active July 28, 2016 08:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoelGeraci-Datalogics/5e99502e1418e7cfd180 to your computer and use it in GitHub Desktop.
Save JoelGeraci-Datalogics/5e99502e1418e7cfd180 to your computer and use it in GitHub Desktop.
Converts a TXT file to PDF
/*
* Copyright 2015 Datalogics Inc.
*/
package pdfjt.cookbook.document;
import com.adobe.pdfjt.pdf.document.PDFDocument;
import com.adobe.pdfjt.pdf.document.PDFOpenOptions;
import com.datalogics.pdf.document.DocumentHelper;
import com.datalogics.pdf.layout.LayoutEngine;
import com.datalogics.pdf.text.Paragraph;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import pdfjt.util.SampleFileServices;
/**
* Demonstrates automatic page breaking by laying out a long string of text as a
* PDF file spanning multiple pages. Note that no special action needs to be
* taken by the code; Talkeetna will break the text into pages automatically.
*
*/
public final class WhiteFang {
static final String OUTPUT_PATH = "WhiteFang.pdf";
private static final String inputText = "http://dev.datalogics.com/cookbook/document/WhiteFang.chapter1.txt";
private static final String outputDir = "cookbook/Document/output/";
public static void main(final String... args) throws Exception {
// Create a document
final PDFDocument pdfDocument = PDFDocument.newInstance(PDFOpenOptions.newInstance());
URLConnection connection = new URL(inputText).openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
connection.connect();
InputStream inputStream = connection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
// Read in a text and add each line as separate paragraph
@SuppressWarnings("resource")
LayoutEngine layoutEngine = new LayoutEngine(pdfDocument);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
for (String line; (line = bufferedReader.readLine()) != null;) {
/*
* The input file uses blank lines to indicate the separation of
* paragraphs, so we'll filter them out.
*/
if (!line.matches("\\s*")) {
layoutEngine.add(new Paragraph(line));
}
}
// Save the document
System.out.println(pdfDocument.requirePages().getNumPages() + " Pages Created.");
SampleFileServices.createDir(outputDir);
DocumentHelper.saveFullAndClose(pdfDocument, outputDir + "WhiteFang.pdf");
System.out.println("Done!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment