使用PDFBOX从两个PDF创建一页PDF

时间:2017-11-14 21:20:17

标签: pdf pdfbox

我有一个小的(四分之一英寸)单页PDF我用PDFBOX用文本(A)创建。我想将一小页PDF(A)放在现有PDF页面(B)的顶部,保留PDF页面的现有内容(B)。最后,我将有一页PDF,代表顶部的小PDF(A),现有的PDF完整地构成其余部分(B)。如何使用PDFBOX完成此操作?

2 个答案:

答案 0 :(得分:0)

要将另一个上面的两个页面连接到一个目标页面上,您可以使用PDFBox <?php // Build request $endpoint = "https://api.zamzar.com/v1/jobs"; $apiKey = "YOUR_API_KEY"; $sourceFilePath = "my.png"; $targetFormat = "pdf"; $sourceFile = curl_file_create($sourceFilePath); $postData = array( "source_file" => $sourceFile, "target_format" => $targetFormat ); // Send request $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $endpoint); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERPWD, $apiKey . ":"); $body = curl_exec($ch); curl_close($ch); // Process response (with link to converted files) $response = json_decode($body, true); print_r($response); ?> 以类似于PDFBox LayerUtility示例的方式将页面导入为XObject形式,例如使用这个辅助方法:

SuperimposePage

JoinPages方法void join(PDDocument target, PDDocument topSource, PDDocument bottomSource) throws IOException { LayerUtility layerUtility = new LayerUtility(target); PDFormXObject topForm = layerUtility.importPageAsForm(topSource, 0); PDFormXObject bottomForm = layerUtility.importPageAsForm(bottomSource, 0); float height = topForm.getBBox().getHeight() + bottomForm.getBBox().getHeight(); float width, topMargin, bottomMargin; if (topForm.getBBox().getWidth() > bottomForm.getBBox().getWidth()) { width = topForm.getBBox().getWidth(); topMargin = 0; bottomMargin = (topForm.getBBox().getWidth() - bottomForm.getBBox().getWidth()) / 2; } else { width = bottomForm.getBBox().getWidth(); topMargin = (bottomForm.getBBox().getWidth() - topForm.getBBox().getWidth()) / 2; bottomMargin = 0; } PDPage targetPage = new PDPage(new PDRectangle(width, height)); target.addPage(targetPage); PDPageContentStream contentStream = new PDPageContentStream(target, targetPage); if (bottomMargin != 0) contentStream.transform(Matrix.getTranslateInstance(bottomMargin, 0)); contentStream.drawForm(bottomForm); contentStream.transform(Matrix.getTranslateInstance(topMargin - bottomMargin, bottomForm.getBBox().getHeight())); contentStream.drawForm(topForm); contentStream.close(); }

你这样使用它:

join

JoinPages test try ( PDDocument document = new PDDocument(); PDDocument top = ...; PDDocument bottom = ...) { join(document, top, bottom); document.save("joinedPage.pdf"); }

结果如下:

screenshot

答案 1 :(得分:0)

作为@mkl答案的补充点。 如果有人希望在将PDF放在页面上使用之前缩放它们,

    contentStream.transform(Matrix.getScaleInstance(<scaling factor in x axis>, <scaling factor in y axis>));  //where 1 is the scaling factor if you want the page as the original size

这样,您可以重新缩放PDF。