Last active
August 17, 2023 10:38
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks a lot, also how can we convert .txt file to pdf using pdfbox?