Create Documents with Document Writers - Java

This tutorial shows how to create a Java application that creates a new PDF document and adds the first pages from each PDF in a directory to the newly created PDF.

Overview  
Summary This tutorial covers how to create a new PDF document and add pages to it using SVG in a Java Console application.
Completion Time 30 minutes
Eclipse Project Download tutorial project (3 KB)
Platform Java Application
IDE Eclipse
Development License Download LEADTOOLS
Try it in another language

Required Knowledge

Get familiar with the basic steps of creating a project by reviewing the Add References and Set a License tutorial, before working on the Create Documents with Document Writers - Java tutorial.

Create the Project and Add the LEADTOOLS References

Start with a copy of the project created in the Add References and Set a License tutorial. If that project is unavailable, follow the steps in that tutorial to create the project.

The references needed depend upon the purpose of the project. References can be added by local .jar files located at <INSTALL_DIR>\LEADTOOLS23\Bin\Java.

For this project, the following references are needed:

This tutorial uses LEADTOOLS Document library support. For a complete list of which JAR files are required for your application, refer to Files to be Included with your Java Application

Set the License File

The License unlocks the features needed for the project. It must be set before any toolkit function is called. For details, including tutorials for different platforms, refer to Setting a Runtime License.

There are two types of runtime licenses:

Note: Adding LEADTOOLS references and setting a license are covered in more detail in the Add References and Set a License tutorial.

Create a New PDF Document and Add Pages Code

With the project created, the references added, and the license set, coding can begin.

In the Project Explorer, open _Main.java class. Add the following statements to the import block at the top.

Java
import java.io.*; 
import java.nio.file.*; 
import java.util.*; 
 
import leadtools.*; 
import leadtools.codecs.*; 
import leadtools.document.writer.*; 

In the run() method make sure to include the following code.

Java
public static void main(String[] args) throws IOException 
{ 
	new _Main().run(args); 
} 
private void run(String[] args) { 
	try { 
		Platform.setLibPath("C:\\LEADTOOLS23\\Bin\\CDLL\\x64"); 
	    Platform.loadLibrary(LTLibrary.LEADTOOLS); 
	    Platform.loadLibrary(LTLibrary.CODECS); 
	    Platform.loadLibrary(LTLibrary.DOCUMENT_WRITER); 
 
	    SetLicense(); 
 
	    CreatePdfDocument(); 
	}  
	catch(Exception ex) { 
		System.err.println(ex.getMessage()); 
		ex.printStackTrace(); 
	} 
} 

Add a new method called CreatePdfDocument() and call it inside the run() method after the SetLicense(); call, as shown above. Add the below code to create a new PDF file and add the first page of each PDF in a given directory to the new PDF.

Java
void CreatePdfDocument() 
{ 
    RasterCodecs codecs = new RasterCodecs(); 
    String dir = "C:\\LEADTOOLS23\\Resources\\Images"; 
    int pageNumber = 1; 
    String[] pdfFiles = GetFiles(dir, "*.pdf"); 
 
    DocumentFormat format = DocumentFormat.PDF; 
    String outFile = PathCombine(dir, "DocumentWriters." + DocumentWriter.getFormatFileExtension(format)); 
 
    codecs.getOptions().getRasterizeDocument().getLoad().setResolution(300); 
 
    DocumentWriter docWriter = new DocumentWriter(); 
 
    PdfDocumentOptions pdfOptions = (PdfDocumentOptions) docWriter.getOptions(format); 
    pdfOptions.setDocumentType(PdfDocumentType.PDFA); 
    pdfOptions.setImageOverText(true); 
    docWriter.setOptions(format, pdfOptions); 
 
    // Begin a new PDF document 
    docWriter.beginDocument(outFile,format); 
 
    // Add the pages 
    for (String file : pdfFiles) 
    { 
        DocumentWriterSvgPage page = new DocumentWriterSvgPage(); 
        page.setSvgDocument(codecs.loadSvg(file, pageNumber, null)); 
        if (pdfOptions.getImageOverText()) 
        { 
            // If we are using image/text, then load the overlay raster image 
            page.setImage(codecs.load(file, pageNumber)); 
        } 
        // Add the page to the created PDF document 
        docWriter.addPage(page);System.out.println("Added page " + pageNumber + " from " + file.substring(file.lastIndexOf("\\") + 1, file.lastIndexOf(".")) + "\n"); 
        // Dispose of resources 
        if (page.getSvgDocument() != null) 
            page.getSvgDocument().dispose(); 
        if (page.getImage() != null) 
            page.getImage().dispose(); 
    } 
    // Finalized document to disk 
    docWriter.endDocument(); 
    System.out.println("PDF document saved successfully!"); 
} 

Add the GetFiles(String path, String searchPattern) and the PathCombine(String... paths) methods, which will be called by inside the CreatePdfDocument() method as shown above.

Java
String[] GetFiles(String path, String searchPattern) 
{ 
    // Split the searchPattern incase we have directories in there 
    ArrayList<String> pattern = new ArrayList<>(Arrays.asList(searchPattern.split("/"))); 
    // Take the last element out from the array, as this will be the file pattern 
    String filePattern = pattern.remove(pattern.size() - 1); 
    // Insert the base path into the remaining list 
    pattern.add(0, path); 
    // Now lets concat the lot to create a base path 
    path = PathCombine(pattern.toArray(new String[pattern.size()])); 
    final Pattern regEx = Pattern.compile(filePattern.replace("*", ".*").replace("?", ".?")); 
    File directory = new File(path); 
    File[] matchingFiles = directory.listFiles(new FilenameFilter() { 
        @Override 
        public boolean accept(File dir, String filename) { 
            return new File(dir, filename).isFile() && regEx.matcher(filename).matches(); 
        } 
    }); 
    ArrayList<String> files = new ArrayList<>(); 
    assert matchingFiles != null; 
    for (File file : matchingFiles) { 
        files.add(file.getAbsolutePath()); 
    } 
    return files.toArray(new String[files.size()]); 
} 
 
String PathCombine(String... paths) 
{ 
    File file = new File(paths[0]); 
    for (int i = 1; i < paths.length ; i++) { 
        file = new File(file, paths[i]); 
    } 
    return file.getPath(); 
} 

Run the Project

Run the project by pressing Ctrl + F11, or by selecting Run -> Run.

If the steps were followed correctly, the application creates a new PDF file that includes the first page of each PDF file in a given directory using SVG and Document Writers.

Wrap-up

This tutorial showed how to create documents using the Document Writers. Also, it covered how to use the DocumentWriter, PdfDocumentOptions, DocumentWriterSvgPage, and RasterCodecs classes.

See Also

Help Version 23.0.2024.4.23
Products | Support | Contact Us | Intellectual Property Notices
© 1991-2024 LEAD Technologies, Inc. All Rights Reserved.


Products | Support | Contact Us | Intellectual Property Notices
© 1991-2023 LEAD Technologies, Inc. All Rights Reserved.