All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.butor.html2pdf.Html2Pdf Maven / Gradle / Ivy

/**
 * Copyright 2013-2019 Butor Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.butor.html2pdf;

import static com.google.common.base.Preconditions.checkNotNull;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;

import org.butor.json.JsonHelper;
import org.butor.utils.ApplicationException;
import org.butor.utils.CommonMessageID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.api.client.util.Lists;
import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.io.Files;

public class Html2Pdf {
	private Logger logger = LoggerFactory.getLogger(getClass());

	protected File html2pdfBase;
	protected File html2pdfCmd;
	protected File htmlPrintWrapper;
	protected File snapshotPrintWrapper;

	public Html2Pdf(String html2pdfBase) {
		checkNotNull(html2pdfBase);
		File file = new File(html2pdfBase);
		Preconditions.checkArgument(file.exists() && file.isDirectory(), file.getAbsolutePath() +" does not exists or is not a directory!");
		this.html2pdfBase = file;
		
		file = new File(html2pdfBase, "html2pdf.sh");
		Preconditions.checkArgument(file.exists(), file.getAbsolutePath() +" does not exists!");
		this.html2pdfCmd = file;
		
		file = new File(html2pdfBase, "htmlPrintWrapper.html");
		Preconditions.checkArgument(file.exists(), file.getAbsolutePath() +" does not exists!");
		this.htmlPrintWrapper = file;
		
		file = new File(html2pdfBase, "snapshotPrintWrapper.html");
		Preconditions.checkArgument(file.exists(), file.getAbsolutePath() +" does not exists!");
		this.snapshotPrintWrapper = file;
	}

	public void html2pdf(Map args, Html2PdfHandler handler) {
		if (args == null) {
			ApplicationException.exception(CommonMessageID.MISSING_ARG.getMessage("args"));
		}
		if (handler == null) {
			ApplicationException.exception(CommonMessageID.MISSING_ARG.getMessage("handler"));
		}
		String name = args.get("name");
		if (Strings.isNullOrEmpty(name)) {
			if (args.containsKey("title")) {
				args.put("name", args.get("title") +".pdf");
			} else {
				args.put("name", "html2pdf.pdf");
			}
		}
		if (!args.get("name").toLowerCase().endsWith(".pdf")) {
			args.put("name", args.get("name") +".pdf");
		}
		logger.info("name={}", args.get("name"));

		String type = args.get("type");
		if (Strings.isNullOrEmpty(type)) {
			args.put("type", "html");
		}

		String html = args.remove("html");
		if (Strings.isNullOrEmpty(html)) {
			ApplicationException.exception(CommonMessageID.MISSING_ARG.getMessage("html"));
		}

		String format = args.get("format");
		if (Strings.isNullOrEmpty(format)) {
			args.put("format", "Letter");
		}
		String orientation = args.get("orientation");
		if (Strings.isNullOrEmpty(orientation)) {
			args.put("orientation", "Portrait");
		}
		String margin = args.get("margin");
		if (Strings.isNullOrEmpty(margin)) {
			args.put("margin", "1cm");
		}

		File htmlFile = null;
		File resultFile = null;
		File argsFile = null;
		List processArgs = Lists.newArrayList();
		try {
			htmlFile = File.createTempFile("html2pdf_", ".html");
			htmlFile.deleteOnExit();
			FileOutputStream fos = new FileOutputStream(htmlFile);

			resultFile = File.createTempFile("html2pdf_", ".pdf");
			resultFile.deleteOnExit();

			File printWrapper = type.equals("snapshot") ? snapshotPrintWrapper : htmlPrintWrapper;
			if (!printWrapper.exists()) {
				ApplicationException.exception(CommonMessageID.SERVICE_FAILURE.getMessage(
					String.format("print wrapper does not exists %s", printWrapper.getAbsolutePath())));
			}

			String wrapper = null;
			try {
				wrapper = Files.toString(printWrapper, Charsets.UTF_8);
			} catch (IOException e1) {
				ApplicationException.exception(CommonMessageID.SERVICE_FAILURE.getMessage(
						String.format("Failed to read file %s", printWrapper.getAbsolutePath())));
			}

			if (wrapper != null) {
				if (args.containsKey("app")) {
					wrapper = wrapper.replace("_app_", args.get("app"));
				}
				html = wrapper.replace("", html +"");
			}
			fos.write(html.getBytes());
			fos.close();

			args.put("htmlFile", htmlFile.getAbsolutePath());
			args.put("resultFile", resultFile.getAbsolutePath());

			argsFile = File.createTempFile("html2pdf_", ".json");
			argsFile.deleteOnExit();
			String argsJson = new JsonHelper().serialize(args);
			Files.write(argsJson, argsFile, Charsets.UTF_8);
		
			processArgs.add(html2pdfCmd.getAbsolutePath());
			processArgs.add(argsFile.getAbsolutePath());

			ProcessBuilder builder = new ProcessBuilder(processArgs);
			builder.redirectErrorStream(true);
			logger.info("Runing command : {} ...", processArgs);
			if (logger.isDebugEnabled()) {
				logger.debug(String.format("Html2pdf processing %s with args %s ...", 
						html2pdfCmd.getAbsolutePath(), argsJson));
			}
			Process process = builder.start();

			BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line = "1";
			try {
				line = input.readLine();
				logger.info(String.format("Html2pdf process %s returned: %s", 
						html2pdfCmd.getAbsolutePath(), line));
				
			} catch (IOException e) {
				logger.warn("Failed to run {} with args {}", 
						html2pdfCmd.getAbsolutePath(), argsJson, e);
			}

			if (line.startsWith("0") && resultFile.exists()) {
				handler.handleFile(resultFile);
			} else {
				handler.handleFile(null);
			}
			
		} catch (IOException e) {
			logger.warn("Failed! {}", processArgs, e);
			
		} finally {
			if (htmlFile != null && htmlFile.exists()) {
				try {
					htmlFile.delete(); 
				} catch (Exception e) {
					//OK
				}
			}
			if (resultFile != null && resultFile.exists()) {
				try {
					resultFile.delete(); 
				} catch (Exception e) {
					//OK
				}
			}
			if (argsFile != null && argsFile.exists()) {
				try {
					argsFile.delete(); 
				} catch (Exception e) {
					//OK
				}
			}
		}
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy