1. Build the required environment
- Download wkhtmltoimage
First, you need to go from wkhtmltopdf's official website (
/
) Download the Windows version of wkhtmltoimage. Make sure to select a version that matches your system architecture (32-bit or 64-bit). - Unzip the downloaded file
After the download is complete, unzip the downloaded file to a directory you like, such as C:\wkhtmltoimage. - ConfigurationEnvironment variables
In order for the system to recognize the path to wkhtmltoimage, you need to add it to the system's environment variables. The specific operations are as follows:
Right-click "This Computer" or "My Computer" and select "Properties".
Click "Advanced System Settings".
In the System Properties window, click the Environment Variables button.
In the System Variables area, find the variable named Path and select it, and then click Edit.
In the window that opens, click "New", and then add the installation path of wkhtmltoimage, such as D:\safeware\wkhtmltopdf\bin.
Click OK to save the changes.
- Verify installation
Open a command prompt (cmd) and enter the following command to verify that wkhtmltoimage is installed correctly and can run normally:
wkhtmltoimage --version
2. Write tools
The following has been verified in the window environment
package ;
import ;
import ;
import ;
public class HtmlToPdfConverter {
private static String wkhtmltopdfPath = "D:\\safeware\\wkhtmltopdf\\bin\\"; // Windows
// or
// String wkhtmltopdfPath = "/usr/local/bin/wkhtmltopdf"; // Linux/Mac
public static void main(String[] args) {
String htmlFilePath = "E:\\Desktop\\"; // Enter the HTML file path
String outputPdfPath = "E:\\Desktop\\"; // Output PDF path
try {
// Build command
ProcessBuilder processBuilder = new ProcessBuilder(
wkhtmltopdfPath,
htmlFilePath,
outputPdfPath
);
// Start the process
Process process = ();
//Catch error streams (wkhtmltopdf usually outputs logs to error streams)
BufferedReader errorReader = new BufferedReader(
new InputStreamReader(())
);
String line;
while ((line = ()) != null) {
(line); // Print error message
}
// Wait for the command execution to complete
int exitCode = ();
if (exitCode == 0) {
("PDF generated successfully!");
} else {
("PDF generation failed, error code: " + exitCode);
}
} catch (IOException | InterruptedException e) {
();
}
}
}