HTML to PDF using PD4ML | Code Factory

Reference Link : Link

Donate : Link

Required Jars :

- pd4ml.jar
- ss_css2.jar

PD4ML_test.java

import java.awt.Color;
import java.awt.Insets;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;
import java.security.InvalidParameterException;
import java.util.Date;
import org.zefer.pd4ml.PD4Constants;
import org.zefer.pd4ml.PD4ML;
import org.zefer.pd4ml.PD4PageMark;
public class PD4ML_test {public static void main(String args[]) throws InvalidParameterException, IOException {
StringReader reader = new StringReader(getHtml());

ByteArrayOutputStream bos = new ByteArrayOutputStream();

PD4ML html = new PD4ML();
html.setHtmlWidth(760);
html.setPageSize(PD4Constants.A4);
html.setPageInsets(new Insets(15, 15, 15, 15));
html.enableImgSplit(false);
html.interpolateImages(false);
html.enableTableBreaks(false);


PD4PageMark header = new PD4PageMark();
header.setTitleTemplate("Header Title");
header.setTitleAlignment(PD4PageMark.LEFT_ALIGN);
header.setPageNumberTemplate(new Date().toString());
header.setPageNumberAlignment(PD4PageMark.RIGHT_ALIGN);
header.setColor(new Color(81, 81, 81));
header.setPagesToSkip(0);
header.setAreaHeight(18);
header.setFontSize(12);

PD4PageMark footer = new PD4PageMark();
footer.setTitleTemplate("Footer Title");
footer.setTitleAlignment(PD4PageMark.LEFT_ALIGN);
footer.setPageNumberTemplate("page $[page] of $[total]");
footer.setPageNumberAlignment(PD4PageMark.RIGHT_ALIGN);
footer.setColor(new Color(81, 81, 81));
footer.setInitialPageNumber(1);
footer.setPagesToSkip(0);
footer.setAreaHeight(18);
footer.setFontSize(12);

html.setPageHeader(header);
html.setPageFooter(footer);

html.render(reader, bos);

try(OutputStream stream = new FileOutputStream("E:\\test.pdf")) {
bos.writeTo(stream);
}
System.out.println("Done");
}
private static String getHtml() {
/*use inline css*/
/*return "<html>" +
"<body>" +
"<h1 style='color:blue;'>This is a heading</h1>" +
"<p style='margin-left:30px;'>This is a paragraph.</p>" +
"</body>" +
"</html>";*/

/*use external css*/
return "<html>" +
"<head>" +
"<link rel='stylesheet' href='style.css'>" +
"</head>" +
"<body>" +
"<h1>This is a heading</h1>" +
"<p>This is a paragraph.</p>" +
"</body>" +
"</html>";
}
}

style.css

p {
margin-left:30px;
font-size: 21px;
}