Maven プロジェクトの場合: 次の依存関係をプロジェクトの pom.xml ファイルに追加します。
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.itextpdf.tool/xmlworker -->
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.8</version>
</dependency>
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.poi.util.IOUtils;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
public class HtmlToPdf {
public static void main(String[] args) throws DocumentException, IOException {
File htmlFile = new File(args[0]);
String pdfFileName = "test.pdf";
Document document = new Document();
PdfWriter writer = null;
InputStream is = null;
OutputStream out = null;
if (htmlFile.exists()) {
try {
is = new FileInputStream(htmlFile);
out = new FileOutputStream(pdfFileName);
writer = PdfWriter.getInstance(document, out);
document.open();
XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
System.out.println("PDF Created!");
} finally {
// close the document before before input stream (is) and writer closure
if(document != null && document.isOpen()) {
document.close();
}
// no harm in closing writer here
if(writer != null) {
writer.close();
}
IOUtils.closeQuietly(out);
IOUtils.closeQuietly(is);
}
}
}
}