Skip to content

Instantly share code, notes, and snippets.

@mmdemirbas
Last active August 17, 2023 10:38
Show Gist options
  • Save mmdemirbas/209b4bdb66b788e785266f97204b8631 to your computer and use it in GitHub Desktop.
Save mmdemirbas/209b4bdb66b788e785266f97204b8631 to your computer and use it in GitHub Desktop.
Combine multiple images into a single PDF file using Apache PDFBox 2.0.1
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* @author Muhammed Demirbaş
* @since 2016-05-15, 16:58
*/
public class CombineIntoPDF {
public static void main(String[] args) throws IOException {
combineImagesIntoPDF("D:\\output.pdf",
"D:\\inputDir1",
"D:\\inputImage.jpg",
"D:\\inputImage.tif",
"D:\\anotherInputDir");
}
private static void combineImagesIntoPDF(String pdfPath, String... inputDirsAndFiles) throws IOException {
try (PDDocument doc = new PDDocument()) {
for (String input : inputDirsAndFiles) {
Files.find(Paths.get(input),
Integer.MAX_VALUE,
(path, basicFileAttributes) -> Files.isRegularFile(path))
.forEachOrdered(path -> addImageAsNewPage(doc, path.toString()));
}
doc.save(pdfPath);
}
}
private static void addImageAsNewPage(PDDocument doc, String imagePath) {
try {
PDImageXObject image = PDImageXObject.createFromFile(imagePath, doc);
PDRectangle pageSize = PDRectangle.A4;
int originalWidth = image.getWidth();
int originalHeight = image.getHeight();
float pageWidth = pageSize.getWidth();
float pageHeight = pageSize.getHeight();
float ratio = Math.min(pageWidth / originalWidth, pageHeight / originalHeight);
float scaledWidth = originalWidth * ratio;
float scaledHeight = originalHeight * ratio;
float x = (pageWidth - scaledWidth ) / 2;
float y = (pageHeight - scaledHeight) / 2;
PDPage page = new PDPage(pageSize);
doc.addPage(page);
try (PDPageContentStream contents = new PDPageContentStream(doc, page)) {
contents.drawImage(image, x, y, scaledWidth, scaledHeight);
}
System.out.println("Added: " + imagePath);
} catch (IOException e) {
System.err.println("Failed to process: " + imagePath);
e.printStackTrace(System.err);
}
}
}
@ramgopalcheedu
Copy link

Hi @mmdemirbas,
Thanks for the example is there any way we can fill the image into LETTER PAGE

@vinit14695
Copy link

vinit14695 commented Mar 28, 2019

Thanks a lot, also how can we convert .txt file to pdf using pdfbox?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment