Tuesday, 01 June 2021 07:45

Java convert image to PDF

We have demonstrated how to use Spire.PDF for java to convert PDF to image. This article will show you how to convert image to PDF in Java applications.

import com.spire.pdf.*;
import com.spire.pdf.graphics.PdfImage;

public class imageToPDF {
    public static void main(String[] args) throws Exception {

        //Create a PDF document
        PdfDocument pdf = new PdfDocument();
        //Add a new page
        PdfPageBase page = pdf.getPages().add();

        //Load the image
        PdfImage image = PdfImage.fromFile("logo.jpg");

        double widthFitRate = image.getPhysicalDimension().getWidth() / page.getCanvas().getClientSize().getWidth();
        double heightFitRate = image.getPhysicalDimension().getHeight() / page.getCanvas().getClientSize().getHeight();
        double fitRate = Math.max(widthFitRate, heightFitRate);

        //get the picture width and height
        double fitWidth = image.getPhysicalDimension().getWidth() / fitRate;
        double fitHeight = image.getPhysicalDimension().getHeight() / fitRate;

        //Draw image
        page.getCanvas().drawImage(image, 0, 30, fitWidth, fitHeight);

        // Save document to file
        pdf.saveToFile("output/ToPDF.pdf");
        pdf.close();

    }
}

Output:

Java convert image to PDF

Published in Conversion
Tuesday, 15 August 2023 07:18

Java: Convert SVG to PDF

SVG files are vector-based graphics that can be scaled and resized without losing quality. While they can be very useful in certain scenarios, there may still be times when you need to convert them to PDFs for further processing, sharing, distributing, printing, or archiving. In this article, you will learn how to programmatically convert SVG images to PDF files using Spire.PDF for Java.

Install Spire.PDF for Java

First of all, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>11.10.3</version>
    </dependency>
</dependencies>

Convert SVG to PDF in Java

Spire.PDF for Java offers the PdfDocument.loadFromSvg() method to load an SVG file directly, and you can then convert it to a PDF file through the PdfDocument.saveToFile() method. The following are the detailed steps.

  • Create a PdfDocument instance.
  • Load a sample SVG file using PdfDocument.loadFromSvg() method.
  • Convert the SVG file to PDF using PdfDocument.saveToFile(String filename, FileFormat.PDF) method.
  • Java
import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;

public class SVGToPDF {
    public static void main(String[] args) {
        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();

        //Load a sample SVG file
        pdf.loadFromSvg("sample.svg");

        //Save as PDF file
        pdf.saveToFile("SVGToPDF.pdf", FileFormat.PDF);
    }
}

Java: Convert SVG to PDF

Add SVG Images to PDF in Java

In addition to converting SVG to PDF, Spire.PDF for Java also supports adding SVG images to PDF files. During the process, you are allowed to set the position and size of the SVG image. The following are the detailed steps.

  • Create a PdfDocument instance and load an SVG file using PdfDocument.loadFromSvg() method.
  • Create a template based on the content of the SVG file using PdfDocument.getPages().get().createTemplate() method.
  • Create another PdfDocument object and load a PDF file using PdfDocument.loadFromFile() method.
  • Get a specified page in the PDF file using PdfDocument.getPages().get() method.
  • Draw the template with a custom size at a specified location on the PDF page using PdfPageBase.getCanvas().drawTemplate() method.
  • Save the result PDF file using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.graphics.PdfTemplate;

import java.awt.*;
import java.awt.geom.Point2D;

public class AddSVGImagetoPDF {
    public static void main(String[] args) {
        //Create a PdfDocument instance
        PdfDocument doc1 = new PdfDocument();

        //Load an SVG file
        doc1.loadFromSvg("Image.svg");

        //Create a template based on the content of the SVG file
        PdfTemplate template = doc1.getPages().get(0).createTemplate();

        //Create another PdfDocument instance
        PdfDocument doc2 = new PdfDocument();

        //Load a PDF file
        doc2.loadFromFile("Intro.pdf");

        //Draw the template with a custom size at a specified location in the PDF file
        doc2.getPages().get(0).getCanvas().drawTemplate(template, new Point2D.Float(100,200), new Dimension(400,280) );

        //Save the result file
        doc2.saveToFile("AddSVGtoPDF.pdf", FileFormat.PDF);
        doc1.close();
        doc2.close();
    }
}

Java: Convert SVG to PDF

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Published in Conversion
Thursday, 09 June 2022 07:27

Java: Convert PDF to Excel

For security reasons, many financial documents such as invoices are usually saved in PDF format. If you want to perform data analysis and calculation on these documents, you may need to convert them to Excel. In this article, we will introduce how to convert PDF to Excel in Java using Spire.PDF for Java.

Install Spire.PDF for Java

First of all, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>11.10.3</version>
    </dependency>
</dependencies>

Convert PDF to Excel in Java

The following are the steps to convert a PDF document to Excel:

  • Initialize an instance of PdfDocument class.
  • Load the PDF document using PdfDocument.loadFromFile(String) method.
  • Save the document to Excel using PdfDocument.saveToFile(String, FileFormat) method.
  • Java
import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;

public class ConvertPdfToExcel {
    public static void main(String[] args) {
        //Initialize an instance of PdfDocument class
        PdfDocument pdf = new PdfDocument();
        //Load the PDF document
        pdf.loadFromFile("Sample.pdf");

        //Save the PDF document to XLSX
        pdf.saveToFile("PdfToExcel.xlsx", FileFormat.XLSX);
    }
}

Java: Convert PDF to Excel

This example converts multiple PDF pages to multiple Excel worksheets. If you want to convert a multi-page PDF to a single Excel sheet, please refer to this article: Java: Convert a Multi-Page PDF to One Excel Worksheet.

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Published in Conversion

Visual guide of Convert HTML to PDF in Java

Conversion from HTML to PDF in Java is a critical task for developers aiming to generate dynamic documents, reports, or invoices. Whether you're building a web application or automating data exports, this process ensures consistent formatting across platforms.

This article demonstrates how to convert HTML to PDF in Java using the powerful Spire.PDF for Java and QT WebEngine, ensuring high-fidelity PDF rendering from live webpages, raw HTML strings or HTML files.

Table of Contents:

Why Convert HTML to PDF in Java?

The benefits of using Jave for HTML to PDF conversion lie in:

  • Preserve Formatting: Maintain exact HTML/CSS styling in printable documents
  • Cross-Platform Compatibility: Ensure consistent document rendering across devices
  • Generate Professional Documents: Generate dynamic PDFs from HTML web templates
  • Archive Web Content: Create permanent snapshots of web pages
  • Automate Workflows: Integrate conversion into Java applications

Installation and Setup

Spire.PDF for Java + Qt Web Engine can act as a professional HTML to PDF converter for Java. To get started, follow the instructions below:

Install Spire.PDF for Java

To install Spire.PDF, you can use Maven or manually include the JAR file.

1. Maven Configuration

Add the following dependency to your pom.xml:

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>11.10.3</version>
    </dependency>
</dependencies>

2. Manual JAR Inclusion

Download the latest version of Spire.PDF for Java from the official website and add the JAR file to your project.

Download Qt WebEngine Plugin

Qt WebEngine is a web browser engine module that enables developers to embed web content (HTML, CSS, JavaScript) into their cross-platform applications.

This scenario uses an open-source version of Qt WebEngine (under LGPLv3/GPL) for rendering HTML content. You can download the appropriate QT plugin version for your OS:

After downloading, unzip the package to a local path to get the "plugins" folder (e.g., F:\ Plugin\plugins-windows-x64\plugins).

Qt plugin file path

Important Notes:

  • For Linux/Mac environments:

Directly copy the plugin package to system and unzip it. Ensure read permissions for the plugin folder.

  • Headless Server Requirement:

The conversion method requires GUI support. For servers without GUI, you need install the xvfb tool first, and then use the xvfb-run command to run your application.

#1. install xvfb
Centos:yum install Xvfb
Ubuntu:apt-get install Xvfb

#2. Run application
xvfb-run java -jar HTMLToPDF.jar

Convert URL to PDF in Java

The following Java code converts an HTML webpage (URL) to PDF. Perfect for live web content capture.

import com.spire.pdf.graphics.PdfMargins;
import com.spire.pdf.htmlconverter.qt.HtmlConverter;
import com.spire.pdf.htmlconverter.qt.Size;

public class ConvertUrlToPdf {

    public static void main(String[] args) {

        // Specify the url path
        String url = "https://www.google.com/";

        // Specify the output file path
        String fileName = "output/UrlToPdf.pdf";

        // Specify the plugin path
        String pluginPath = "F:\\Plugin\\plugins-windows-x64\\plugins";

        // Set the plugin path
        HtmlConverter.setPluginPath(pluginPath);

        // Convert URL to PDF
        HtmlConverter.convert(url, fileName, true, 1000000, new Size(1200f, 1000f), new PdfMargins(0));
    }
}

Critical: If plugins are missing or path is incorrect, conversion fails.

Parameters Explained

In the above code, the core conversion method is HtmlConverter.convert(). It accepts 6 parameters which are explained below:

Parameter Purpose
String url Specify the web address to convert.
String fileName Specify the output PDF file path.
boolean enableJavaScript Allows dynamic content (e.g., AJAX, animations). Set false to disable.
int timeout Max page load time. Adjust for slow sites.
Size pageSize Set the output PDF page size.
PdfMargins margins Set the output PDF margins.

Result:

Convert a URL to a PDF file

Convert HTML Strings to PDF in Java

This Java code demonstrates how to convert an HTML string into a PDF file. Ideal for generating PDFs from dynamic HTML content (e.g., user-generated).

import com.spire.pdf.graphics.PdfMargins;
import com.spire.pdf.htmlconverter.LoadHtmlType;
import com.spire.pdf.htmlconverter.qt.HtmlConverter;
import com.spire.pdf.htmlconverter.qt.Size;

import java.io.IOException;

public class ConvertHtmlStringToPdf {

    public static void main(String[] args) throws IOException {

        // Specify the Html string
        String htmlString = "<html>" +
                "<style> h1 {color: #FF5733;font-size: 24px;margin-top: 50px;} </style>" +
                "<body>" +
                "<h1>Hello, PDF!</h1>" +
                "<p>This is a simple example of converting HTML String to PDF.</p>" +
                "<ul>" +
                "<li>First Item</li>" +
                "<li>Second Item</li>" +
                "<li>Third Item</li>" +
                "</ul>" +
                "</body></html>";

        // Specify the output file path
        String outputFile = "output/HtmlStringToPdf.pdf";

        // Specify the plugin path
        String pluginPath = "F:\\Plugin\\plugins-windows-x64\\plugins";

        // Set the plugin path
        HtmlConverter.setPluginPath(pluginPath);

        // Convert the HTML string to PDF
        HtmlConverter.convert(htmlString, outputFile, true, 100000, new Size(700, 900), new PdfMargins(0), LoadHtmlType.Source_Code);
    }
}

In this code:

  • Specifies an HTML string containing inline CSS styling (e.g., red h1 text) and simple content (heading, paragraph, list).
  • Uses HtmlConverter.convert() to convert HTML string to PDF with the following parameters:
    • HTML content (string)
    • Output file path
    • true to enable JavaScript execution.
    • Timeout (100,000 milliseconds)
    • Page size (700x900)
    • Zero margins
    • LoadHtmlType.Source_Code to indicate the input is raw HTML.

Output:

Convert an HTML string to a PDF file

Convert HTML Files to PDF in Java

This example shows how to convert HTML files to PDF documents programmatically. Suitable for static document archival and design-heavy publications.

import com.spire.pdf.graphics.PdfMargins;
import com.spire.pdf.htmlconverter.LoadHtmlType;
import com.spire.pdf.htmlconverter.qt.HtmlConverter;
import com.spire.pdf.htmlconverter.qt.Size;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class ConvertHtmlToPdf {

    public static void main(String[] args) throws IOException {

        // Invoke the custom method HtmlToString() to convert HTML file to string
        String htmlString = HtmlToString("sample1.html");

        // Specify the output file path
        String outputFile = "output/HtmlFileToPdf.pdf";

        // Specify the plugin path
        String pluginPath = "F:\\Plugin\\plugins-windows-x64\\plugins";

        // Set the plugin path
        HtmlConverter.setPluginPath(pluginPath);

        // Convert the HTML string to PDF
        HtmlConverter.convert(htmlString, outputFile, true, 100000, new Size(700, 900), new PdfMargins(0), LoadHtmlType.Source_Code);
    }

    // Convert a HTML file to string
    public static String HtmlToString(String filePath) throws IOException {
        String path = filePath;
        File file = new File(path);
        FileReader fileReader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        StringBuilder stringBuilder = new StringBuilder();
        String temp = "";
        while ((temp = bufferedReader.readLine()) != null) {
            stringBuilder.append(temp + "\n");
        }
        bufferedReader.close();
        String str = stringBuilder.toString();
        return str;
    }
}

Note: Only inline CSS style and internal CSS style can be rendered correctly on PDF. If you have an external CSS style sheet, please convert it to inline or internal CSS style.

Core Workflow Explained

  • Read HTML File: Uses the custom method HtmlToString() to convert an HTML file into a string.

    • Opens the HTML file using FileReader and BufferedReader.
    • Reads line-by-line, appending content to a StringBuilder.
    • Returns the HTML content as a single string.
  • Configure Output & Plugins: Specifies output file path and sets the Qt plugin path.

  • Convert HTML to PDF: Uses the same HtmlConverter.convert() method as in above example.

Result:

Convert an HTML file to a PDF file


Frequently Asked Questions (FAQs)

Q1. Why do I need Qt plugins for HTML-to-PDF conversion?

Qt WebEngine provides a Chromium-based rendering engine required to parse modern HTML/CSS/JavaScript. Spire.PDF uses Qt under the hood for accurate web page rendering.

Q2: How can I avoid watermarks in the output PDF?

Request a 30-day trial license to remove the watermarks and get rid of the function limitations.

Q3. How do I optimize conversion speed for large documents?

  • Disable JavaScript if unnecessary
  • Reduce timeout
  • Set smaller page size

Conclusion

Using Spire.PDF for Java with the QT plugin streamlines HTML to PDF conversion in Java with minimal code. Whether sourcing from URLs, strings, or local files, this article provides detailed instructions and practical code examples to help enhance your document automation workflows.

Final Tip: Explore online documentation for advanced Java PDF processing features like digital signatures and PDF/A compliance.

Published in Conversion

Spire.PDF supports to convert PDF to HTML and save the resulted HTML file to stream by calling the method PdfDocument.saveToStream(). When converting PDF to HTML, it also supports to set the convert options with embedded SVG/Image on the resulted HTML file. This article will demonstrate how to convert the PDF pages to HTML with embedded SVG and embedded image.

import com.spire.pdf.*;
import java.io.*;

public class PDFtoHTML {
    public static void main(String[] args) throws FileNotFoundException {

        String inputFile = "Sample.pdf";
        String outputFile = "output/toHTML_out.html";

        //Load the sample document file
        PdfDocument pdf = new PdfDocument();

        pdf .loadFromFile(inputFile);

        //Set the bool useEmbeddedSvg and useEmbeddedImg as true 
        pdf .getConvertOptions().setPdfToHtmlOptions(true,true);

        //Save to stream
        File outFile = new File(outputFile);
        OutputStream outputStream = new FileOutputStream(outFile);
        pdf.saveToStream(outputStream, FileFormat.HTML);
        pdf.close();

    }
}
Published in Conversion
Friday, 08 April 2022 07:34

Java: Convert Images to PDF

Converting images to PDF is beneficial for many reasons. For one reason, it allows you to convert images into a format that is more readable and easier to share. For another reason, it dramatically reduces the size of the file while preserving the quality of images. In this article, you will learn how to convert images to PDF in Java using Spire.PDF for Java.

There is no straightforward method provided by Spire.PDF to convert images to PDF. You could, however, create a new PDF document and draw images at the specified locations. Depending on whether the page size of the generated PDF matches the image, this topic can be divided into two subtopics.

Install Spire.PDF for Java

First, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>11.10.3</version>
    </dependency>
</dependencies>

Additionally, the imgscalr library is used in the first code example to resize images. It is not necessary to install it if you do not need to adjust the image’s size.

Add an Image to PDF at a Specified Location

The following are the steps to add an image to PDF at a specified location using Spire.PDF for Java.

  • Create a PdfDocument object.
  • Set the page margins using PdfDocument.getPageSettings().setMargins() method.
  • Add a page using PdfDocument.getPages().add() method
  • Load an image using ImageIO.read() method, and get the image width and height.
  • If the image width is larger than the page (the content area) width, resize the image to make it to fit to the page width using the imgscalr library.
  • Create a PdfImage object based on the scaled image or the original image.
  • Draw the PdfImage object on the first page at (0, 0) using PdfPageBase.getCanvas().drawImage() method.
  • Save the document to a PDF file using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfImage;
import org.imgscalr.Scalr;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;

public class AddImageToPdf {

    public static void main(String[] args) throws IOException {

        //Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        //Set the margins
        doc.getPageSettings().setMargins(20);

        //Add a page
        PdfPageBase page = doc.getPages().add();

        //Load an image
        BufferedImage image = ImageIO.read(new FileInputStream("C:\\Users\\Administrator\\Desktop\\announcement.jpg"));

        //Get the image width and height
        int width = image.getWidth();
        int height = image.getHeight();

        //Declare a PdfImage variable
        PdfImage pdfImage;

        //If the image width is larger than page width
        if (width > page.getCanvas().getClientSize().getWidth())
        {
            //Resize the image to make it to fit to the page width
            int widthFitRate =  width / (int)page.getCanvas().getClientSize().getWidth();
            int targetWidth = width / widthFitRate;
            int targetHeight = height / widthFitRate;
            BufferedImage scaledImage = Scalr.resize(image,Scalr.Method.QUALITY,targetWidth,targetHeight);

            //Load the scaled image to the PdfImage object
            pdfImage = PdfImage.fromImage(scaledImage);

        } else
        {
            //Load the original image to the PdfImage object
            pdfImage = PdfImage.fromImage(image);
        }

        //Draw image at (0, 0)
        page.getCanvas().drawImage(pdfImage, 0, 0, pdfImage.getWidth(), pdfImage.getHeight());

        //Save to file
        doc.saveToFile("output/AddImage.pdf");
    }
}

Java: Convert Images to PDF

Convert an Image to PDF with the Same Width and Height

The following are the steps to convert an image to a PDF with the same page size as the image using Spire.PDF for Java.

  • Create a PdfDocument object.
  • Set the page margins to zero using PdfDocument.getPageSettings().setMargins() method.
  • Load an image using ImageIO.read() method, and get the image width and height.
  • Add a page to PDF based on the size of the image using PdfDocument.getPages().add() method.
  • Create a PdfImage object based on the image.
  • Draw the PdfImage object on the first page from the coordinate (0, 0) using PdfPageBase.getCanvas().drawImage() method.
  • Save the document to a PDF file using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfImage;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;

public class ConvertImageToPdfWithSameSize {

    public static void main(String[] args) throws IOException {

        //Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        //Set the margins to 0
        doc.getPageSettings().setMargins(0);

        //Load an image
        BufferedImage image = ImageIO.read(new FileInputStream("C:\\Users\\Administrator\\Desktop\\announcement.jpg"));

        //Get the image width and height
        int width = image.getWidth();
        int height = image.getHeight();

        //Add a page of the same size as the image
        PdfPageBase page = doc.getPages().add(new Dimension(width, height));

        //Create a PdfImage object based on the image
        PdfImage pdfImage = PdfImage.fromImage(image);

        //Draw image at (0, 0) of the page
        page.getCanvas().drawImage(pdfImage, 0, 0, pdfImage.getWidth(), pdfImage.getHeight());

        //Save to file
        doc.saveToFile("output/ConvertPdfWithSameSize.pdf");
    }
}

Java: Convert Images to PDF

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Published in Conversion

In the article of convert PDF to SVG by Spire.PDF, each page on the PDF file has been saved as a single SVG file. For example, if the PDF contains 10 pages, we will get 10 SVG files separately. From version 2.7.6, Spire.PDF for Java supports to convert a multipage PDF to one single SVG file in Java.

import com.spire.pdf.*;


public class PDFtoSVG {
    public static void main(String[] args) throws Exception {

        String inputPath = "Sample.pdf";

        PdfDocument document = new PdfDocument();
        document.loadFromFile(inputPath);

        document.getConvertOptions().setOutputToOneSvg(true);

        document.saveToFile("output.svg", FileFormat.SVG);
        document.close();
    }
}

Effective screenshot of the resulted one SVG file:

Java convert a multipage PDF to one SVG

Published in Conversion
Tuesday, 27 June 2023 08:26

Java: Convert PDF to XPS and XPS to PDF

PDF (Portable Document Format) and XPS (XML Paper Specification) are two commonly used document formats for sharing and printing documents. While PDF is widely known and supported, XPS is a Microsoft-developed format that has gained popularity due to its superior graphics rendering capabilities. In this article, we will demonstrate how to use Spire.PDF for Java to convert PDF to XPS and XPS to PDF in high quality.

Install Spire.PDF for Java

First of all, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>11.10.3</version>
    </dependency>
</dependencies>

Convert PDF to XPS in Java

Spire.PDF for Java has a powerful conversion feature, which can convert PDF to XPS in just three steps. The detailed steps are as follows:

  • Create a PdfDocument instance.
  • Load a PDF sample document using PdfDocument.loadFromFile() method.
  • Save the document as XPS using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.*;

public class PDFtoXPS {
    public static void main(String[] args) {

        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();

        //Load the PDF file
       pdf.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf.pdf");

        //Save to XPS
        pdf.saveToFile("ToXPS.xps", FileFormat.XPS);
        pdf.close();
    }
}

Java: Convert PDF to XPS and XPS to PDF

Convert XPS to PDF in Java

The PdfDocument.saveToFile() method provided by Spire.PDF for Java enables the conversion of a XPS file into a PDF document. The following are steps to convert XPS to PDF.

  • Create a PdfDocument instance.
  • Load a XPS file document using PdfDocument.loadFromFile() method.
  • Save the document as PDF using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.*;

public class XPStoPDF {
    public static void main(String[] args) {

        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();

        //Load a XPS file
        pdf.loadFromXPS("C:\\Users\\Administrator\\Desktop\\sample.xps");

        //Save to PDF
        pdf.saveToFile("toPDF.pdf", FileFormat.PDF);
        pdf.close();
    }
}

Java: Convert PDF to XPS and XPS to PDF

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Published in Conversion
Friday, 10 June 2022 07:10

Java: Convert PDF to SVG

SVG, short for scalable vector graphics, is a vector image format based on XML for two-dimensional graphics. Vector image files, like SVG and PDF files, are very similar. They can display text, images, and other elements in the same appearance and keep the definition no matter how you zoom them. And because of their similarity, PDF files can be converted to SVG files almost losslessly. This article shows an easy method to convert PDF files to SVG files using Spire.PDF for Java.

Install Spire.PDF for Java

First, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>11.10.3</version>
    </dependency>
</dependencies>

Convert Each Page of a PDF File to an SVG File

The detailed steps are as follows:

  • Create an object of PdfDocument class.
  • Load a PDF document from disk using PdfDocument.loadFromFile() method.
  • Convert the document to SVG file and save it using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.*;

public class PDFToSVG {
    public static void main(String[] args) {
        //Create an object of Document class
        PdfDocument pdf = new PdfDocument();

        //Load a PDF document from disk
        pdf.loadFromFile("D:/Samples/Sample.pdf");

        //Convert the document to SVG and Save it
        pdf.saveToFile("D:/javaOutput/PDFToSVG.svg", FileFormat.SVG);
    }
}

Java: Convert PDF to SVG

Convert All the Pages of a PDF File to a Single SVG File

The detailed steps are as follows:

  • Create an object of PdfDocument class.
  • Load a PDF document from disk using PdfDocument.loadFromFile() method.
  • Change the conversion settings to convert the PDF file to a single SVG file using PdfDocument.getConvertOptions().setOutputToOneSvg() method.
  • Convert the document to SVG file and save it using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.*;

public class PDFToSVG {
    public static void main(String[] args) {
        //Create an object of Document class
        PdfDocument pdf = new PdfDocument();

        //Load a PDF document from disk
        pdf.loadFromFile("D:/Samples/Sample.pdf");

        //Change the conversion settings to convert the PDF file to a single SVG file
        pdf.getConvertOptions().setOutputToOneSvg(true);

        //Convert the document to SVG and Save it
        pdf.saveToFile("D:/javaOutput/PDFToSVG.svg", FileFormat.SVG);
    }
}

Java: Convert PDF to SVG

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Published in Conversion
Wednesday, 17 May 2023 07:07

Java: Convert PDF to HTML

PDF file format makes the presentation of documents consistent across devices. However, when you need to put PDF documents on web pages, it's better to convert them to HTML files. In this way, all the content of your document can be displayed in the browser directly, with no need for downloading files. And the loading of large PDF documents takes a long time, while HTML files can be rendered in the browser very quickly. In addition, compared to PDF files, it is much easier for search engines to crawl HTML web pages to get information, which will give your website more exposure. This article will show how to convert PDF documents into HTML files in Java using Spire.PDF for Java.

Install Spire.PDF for Java

First of all, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>11.10.3</version>
    </dependency>
</dependencies>

Convert a PDF document to an HTML file in Java

The conversion from a PDF document to an HTML file can be directly done by loading a PDF document and saving it as an HTML file using PdfDocument.saveToFile(String filename, FileFormat.HTML) method provided by Spire.PDF for Java. The detailed steps are as follows.

  • Create an object of PdfDocument.
  • Load a PDF file using PdfDocument.loadFromFile() method.
  • Save the PDF file as an HTML file using PdfDocument.saveToFle() method.
  • Java
Java
import com.spire.pdf.*;

public class convertPDFToHTML {
    public static void main(String[] args) {

        //Create an object of PdfDocument
        PdfDocument pdf = new PdfDocument();

        //Load a PDF file
        pdf.loadFromFile("C:/Guide to a Foreign Past.pdf");

        //Save the PDF file as an HTML file
        pdf.saveToFile("PDFToHTML.html",FileFormat.HTML);
        pdf.close();
    }
}

Convert a PDF document to an HTML file with SVG Embedded

Spire.PDF for Java also provides the PdfDocument.getConvertOptions().setPdfToHtmlOptions(true) method to enable embedding SVG while converting. The detailed steps for converting a PDF file to an HTML file with SVG embedded are as follows.

  • Create an object of PdfDocument.
  • Load a PDF file using PdfDocument.loadFromFile() method.
  • Enable embedding SVG using PdfDocument.getConvertOptions().setPdfToHtmlOptions(true) method.
  • Save the PDF file as an HTML file using PdfDocument.saveToFle() method.
  • Java
import com.spire.pdf.*;

public class convertPDFToHTMLEmbeddingSVG {
    public static void main(String[] args) {

        //Create an object of PdfDocument
        PdfDocument doc = new PdfDocument();

        //Load a PDF file
        doc.loadFromFile("C:/Guide to a Foreign Past.pdf");

        //Set embedding SVG
        doc.getConvertOptions().setPdfToHtmlOptions(true);

        //Save the PDF file as an HTML file
        doc.saveToFile("PDFToHTMLEmbeddingSVG.html", FileFormat.HTML);
        doc.close();
    }
}

Convert a PDF document to HTML Stream in Java

Spire.PDF for Java also supports converting PDF documents to HTML stream. The detailed steps are as follows.

  • Create an object of PdfDocument.
  • Load a PDF file using PdfDocument.loadFromFile() method.
  • Save the PDF file as HTML stream using PdfDocument.saveToStream() method.
  • Java
import com.spire.pdf.*;

import java.io.*;


public class convertPDFToHTMLStream {
    public static void main(String[] args) throws FileNotFoundException {

        //Create an object of PdfDocument
        PdfDocument pdf = new PdfDocument();

        //Load a PDF file
        pdf.loadFromFile("C:/Guide to a Foreign Past.pdf");

        //Save the PDF file as HTML stream
        File outFile = new File("PDFToHTMLStream.html");
        OutputStream outputStream = new FileOutputStream(outFile);
        pdf.saveToStream(outputStream, FileFormat.HTML);
        pdf.close();
    }
}

Java: Convert PDF to HTML

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Published in Conversion
Page 2 of 3