Quantcast
Viewing all articles
Browse latest Browse all 1121

JPG to PDF conversion in Java

https://gist.github.com/gholker/9a6b68ae51b3bef8931b946958dd81f2


Create a Spring Initializer App (plain vanilla)


add this dependency: com.itextpdf:itextpdf:5.5.13

run this code



package org.pierre.jpgtopdf;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@SpringBootApplication
public class JpgtopdfApplication implements CommandLineRunner {

public static void main(String[] args) {
SpringApplication.run(JpgtopdfApplication.class, args);
}

@Override
public void run(String... args) throws Exception {
File root = new File("D:\\pierre\\tasse2019\\");
String outputFile = "output.pdf";
List<String> files = new ArrayList<String>();
String[] alljpgs = root.list((dir, name) -> name.endsWith("jpg"));
files.addAll(Arrays.asList(alljpgs));

Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(new File(root, outputFile)));
document.open();
for (String f : files) {
document.newPage();
Image image = Image.getInstance(new File(root, f).getAbsolutePath());
image.setAbsolutePosition(0, 0);
image.setBorderWidth(0);
image.scaleAbsolute(PageSize.A4);
document.add(image);
}
document.close();
}
}




It's amazingly fast!


Viewing all articles
Browse latest Browse all 1121

Trending Articles