Converting EPUB to PDF with Java

I would like to convert an EPUB document to PDF using Java. I found many questions about converting PDF to EPUB, but didn't change anything.

Is there a Java library or command line tool that I could call through Java to do the magic?

thanks in advance!

-Gesh

+3


source to share


2 answers


If you're not afraid to use an online service, then the EPUB to PDF Rest API can be used.

The actual JAVA code would look like



public class Main {
    public static void main(String[] args) throws IOException {
        TreeMap params = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);

        params.put("File", "C:\path\to\test-epub.epub");
        params.put("Secret", "<secret>");

        CloseableHttpResponse response = ConvertApi.convert("epub", "pdf", params);
        System.out.println(EntityUtils.toString(response.getEntity(), "UTF-8"));
    }
}

class ConvertApi {
    public static CloseableHttpResponse convert(String srcFormat, String dstFormat, TreeMap params) throws IOException {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        params.forEach((k, v) -> {
            if(Files.exists(Paths.get(v))) {
                builder.addBinaryBody(k, new File(v));
            } else {
                builder.addTextBody(k, v, ContentType.TEXT_PLAIN);
            }
        });

        String authParam = params.get("secret") == null ? String.format("Token=%s", params.get("token")) : String.format("Secret=%s", params.get("secret"));
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(String.format("https://v2.convertapi.com/%s/to/%s?%s", srcFormat, dstFormat, authParam));
        httpPost.setEntity(builder.build());
        return httpClient.execute(httpPost);
    }
}

      

+1


source


You can invoke a Caliber program called ebook-convert from the command line. See the Calibration Guide for details .

I find the conversion works great for simple requirements. I tried to use it to convert e-books (ePUB to PDF), but was unable to control some of the document parameters (page number indents, etc.). The result contained all the text from the original ePUB, it was useful, but I was not happy with the quality of the formatting.



Finally, I finished parsing ePUB and used PrinceXML transform to convert HTML to PDF. The good thing is that I can remove the ePUB table of contents (hyperlinks without page numbers) with a completely different ToC (hyperlinks with page numbers), I can add blank pages where needed, etc. PrinceXML is a binary that you can run from the command line or execute through the Java wrapper , it works very well and has wide HTML / CSS support.

Karelian

0


source







All Articles