Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generate PDF with iText
package net.ekstrandom.htmlpdf;
import java.util.Optional;
import java.io.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import picocli.CommandLine;
// import com.itextpdf.kernel.io.*;
import com.itextpdf.kernel.pdf.*;
import com.itextpdf.html2pdf.*;
import com.itextpdf.styledxmlparser.css.media.*;
class PDFOptions {
@CommandLine.Option(names="-o", description="write output to file")
File outputFile;
@CommandLine.Option(names="-help", description="show this help")
boolean help;
@CommandLine.Option(names="-password", description="encrypt with password")
String password;
@CommandLine.Parameters(paramLabel="PATH", arity="0..1",
description="render page at PATH")
Optional<String> path;
}
public class MakePDF {
private static final Logger log = LoggerFactory.getLogger(MakePDF.class);
public static void main(String[] args) throws Exception {
PDFOptions opts = new PDFOptions();
CommandLine cli = new CommandLine(opts);
cli.parseArgs(args);
if (opts.help) {
cli.usage(System.err);
System.exit(0);
}
if (!opts.path.isPresent()) {
log.error("no path provided");
System.exit(1);
}
log.info("input base URL: {}", opts.path);
InputStream source = new FileInputStream(opts.path.get());
OutputStream dest;
if (opts.outputFile != null) {
log.info("writing to {}", opts.outputFile);
dest = new FileOutputStream(opts.outputFile);
} else {
log.info("writing to standard output");
dest = System.out;
}
PdfWriter out;
if (opts.password == null) {
out = new PdfWriter(dest);
} else {
WriterProperties props = new WriterProperties();
props = props.setStandardEncryption(
opts.password.getBytes(), opts.password.getBytes(),
EncryptionConstants.ALLOW_PRINTING,
EncryptionConstants.ENCRYPTION_AES_128 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA);
out = new PdfWriter(dest, props);
}
ConverterProperties cvt = new ConverterProperties();
cvt.setBaseUri(opts.path.get());
cvt.setMediaDeviceDescription(new MediaDeviceDescription(MediaType.PRINT));
HtmlConverter.convertToPdf(source, out, cvt);
log.info("Finished!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment