Spire.Doc is a class library specialized in operating Word documents. It helps developers create, edit, convert and print Microsoft Word documents easily, quickly and efficiently without installing Microsoft Word. With nearly 10 years of professional development experience, the Spire series of office document development tools focus on creating, editing, converting and printing Word/PDF/Excel and other format files. It is compact and convenient. In addition, you can also browse other products under E- iceblue Document development tools in different languages~
This article will demonstrate how to use Spire.Doc for Java in a Java application to convert HTML strings and HTML files to PDF (qun:767755948)
Convert HTML string to PDF
import com.spire.doc.*; import java.io.*; public class htmlStringToWord { public static void main(String[] args) throws Exception { String inputHtml = "InputHtml.txt"; //Create a new document Document document = new Document(); //Add a section Section sec = document.addSection(); String htmlText = readTextFromFile(inputHtml); //add a paragraph and append html string. sec.addParagraph().appendHTML(htmlText); //Save to PDF document.saveToFile("HTMLstringToPDF.pdf", FileFormat.PDF); } public static String readTextFromFile(String fileName) throws IOException{ StringBuffer sb = new StringBuffer(); BufferedReader br = new BufferedReader(new FileReader(fileName)); String content = null; while ((content = br.readLine()) != null) { sb.append(content); } return sb.toString(); } }
Convert HTML files to PDF
import com.spire.doc.*; import com.spire.doc.documents.XHTMLValidationType; public class htmlFileToWord { public static void main(String[] args) throws Exception { // Load the sample HTML file Document document = new Document(); document.loadFromFile("InputHtmlFile.html", FileFormat.Html, XHTMLValidationType.None); //Save to file document.saveToFile("Result.pdf",FileFormat.PDF); } }
The above is how to convert Word to PDF in Java. If you have other questions, you can continue to browse this series of articles and get related tutorials~