最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java實(shí)現(xiàn)給PDF文件增加背景圖的操作指南

 更新時(shí)間:2025年11月27日 09:47:29   作者:何中應(yīng)  
本文介紹了如何在Java中生成PDF文件并為其添加背景圖,通過兩種不同的方式實(shí)現(xiàn):一種使用了iText庫,另一種使用了PdfBox庫,這兩種方法都可以實(shí)現(xiàn)將背景圖片添加到PDF文件中,并且可以根據(jù)項(xiàng)目需求選擇合適的方法,需要的朋友可以參考下

說明:本文介紹在使用代碼生成 PDF 文件的基礎(chǔ)上,如何給生成的的 PDF 文件增加背景圖。生成 PDF 文件參看下面這篇博客。

思路

思路是在生成后的 PDF 文件基礎(chǔ)上操作,不是在生成 PDF 的模板文件上實(shí)現(xiàn)。

如下,是前文中生成的 PDF 文件。

將下面這張圖作為文件背景放入到 PDF 文件中

實(shí)現(xiàn)一

如下,在原生成 PDF 文件的基礎(chǔ)上,增加設(shè)置背景的代碼

    @PostMapping("/pdf")
    public byte[] pdf() throws IOException {
        // 構(gòu)建響應(yīng)頭
        String fileName = "example.pdf";
        String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", encodedFileName);

        // 生成PDF文件
        byte[] pdf = pdfService.pdf();
        // PDF文件
        File pdfFile = FileUtil.createTempFile("demo", ".pdf", null, true);
        FileUtil.writeBytes(pdf, pdfFile);
        // 背景圖片
        ClassPathResource resource = new ClassPathResource("template/picture.jpg");
        File pictureFile = FileUtil.createTempFile("picture", ".jpg", null, true);
        FileUtil.writeBytes(resource.getInputStream().readAllBytes(), pictureFile);
        // 添加背景圖片,獲取添加背景后的PDF文件
        byte[] bytes = addBackground1(pdfFile, pictureFile);

        // 返回
        return ResponseEntity.ok()
                .headers(headers)
                .body(bytes).getBody();
    }

其中,添加背景圖片方法代碼如下:

    /**
     * 添加背景圖片
     *
     * @param pdfFile     PDF文件
     * @param pictureFile 背景圖片
     * @return 添加背景后的PDF文件
     */
    private byte[] addBackground1(File pdfFile, File pictureFile) {
        // 定義輸出流,存添加完背景的PDF文件
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // 透明度設(shè)置為0.2
        float transparency = 0.2f;

        // 加載PDF文件
        try (PDDocument document = PDDocument.load(pdfFile)) {
            // 加背景圖片
            PDImageXObject backgroundImage = PDImageXObject.createFromFileByExtension(pictureFile, document);

            // 創(chuàng)建透明度配置
            PDExtendedGraphicsState graphicsState = new PDExtendedGraphicsState();
            graphicsState.setNonStrokingAlphaConstant(transparency);

            // 遍歷每一頁
            for (PDPage page : document.getPages()) {
                // 獲取頁面尺寸(單位:點(diǎn),1點(diǎn)=1/72英寸)
                float pageWidth = page.getMediaBox().getWidth();
                float pageHeight = page.getMediaBox().getHeight();

                // 創(chuàng)建內(nèi)容流(追加模式,放在最底層)
                try (PDPageContentStream contentStream = new PDPageContentStream(
                        document, page, PDPageContentStream.AppendMode.PREPEND, true)) {
                    // 應(yīng)用透明度配置
                    contentStream.setGraphicsStateParameters(graphicsState);
                    // 繪制背景圖(鋪滿整個(gè)頁面)
                    contentStream.drawImage(backgroundImage, 0, 0, pageWidth, pageHeight);
                }
            }

            // 保存修改后的PDF
            document.save(outputStream);
            // 以字節(jié)數(shù)組的形式返回加完背景的PDF文件
            return outputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new byte[0];
    }

這種方式所需下面這個(gè)依賴

<dependency>
	<groupId>org.apache.pdfbox</groupId>
	<artifactId>pdfbox</artifactId>
	<version>2.0.27</version>
</dependency>

實(shí)現(xiàn)二

還可以用下面這段代碼

    /**
     * 添加背景圖片
     *
     * @param pdfFile     PDF文件
     * @param pictureFile 背景圖片
     * @return 添加背景后的PDF文件
     */
    private byte[] addBackground2(File pdfFile, File pictureFile) throws DocumentException, IOException {
        // 定義輸出流,存添加完背景的PDF文件
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // 透明度設(shè)置為0.2
        float transparency = 0.2f;

        PdfReader reader = null;
        PdfStamper stamper = null;
        try {
            reader = new PdfReader(FileUtil.readBytes(pdfFile));
            stamper = new PdfStamper(reader, outputStream);
            Image backgroundImage = Image.getInstance(FileUtil.readBytes(pictureFile));

            // 創(chuàng)建透明度配置對象
            PdfGState gState = new PdfGState();
            gState.setFillOpacity(transparency);

            int totalPages = reader.getNumberOfPages();
            for (int i = 1; i <= totalPages; i++) {
                // 直接通過PdfReader獲取頁面尺寸
                Rectangle pageSize = reader.getPageSize(i);
                float pageWidth = pageSize.getWidth();
                float pageHeight = pageSize.getHeight();

                backgroundImage.scaleToFit(pageWidth, pageHeight);
                backgroundImage.setAbsolutePosition(0, 0);

                PdfContentByte content = stamper.getUnderContent(i);
                // 應(yīng)用透明度設(shè)置
                content.setGState(gState);
                content.addImage(backgroundImage);
            }
            stamper.close();
            reader.close();
            
            return outputStream.toByteArray();
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        } finally {
            if (stamper != null) {
                stamper.close();
            }
            if (reader != null) {
                reader.close();
            }
        }
        return new byte[0];
    }

這段代碼所需下面這個(gè)依賴

<dependency>
	<groupId>com.itextpdf</groupId>
	<artifactId>itextpdf</artifactId>
	<version>5.5.13.3</version>
</dependency>

效果

兩種方式,實(shí)現(xiàn)的效果如下:

(實(shí)現(xiàn)一)

(實(shí)現(xiàn)二)

一個(gè)自適應(yīng)了 PDF 文件的尺寸,一個(gè)沒有,如果添加的背景圖片(版權(quán)標(biāo)識、企業(yè) logo)尺寸合適的話,這兩種實(shí)現(xiàn)方式?jīng)]有大的區(qū)別。

作為開發(fā)者,可以根據(jù)當(dāng)前項(xiàng)目中是否已引入上面哪個(gè)依賴,來選擇使用哪種實(shí)現(xiàn)方式。

到此這篇關(guān)于Java實(shí)現(xiàn)給PDF文件增加背景圖的操作指南的文章就介紹到這了,更多相關(guān)Java PDF文件增加背景圖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

高州市| 浦东新区| 肇庆市| 固镇县| 临沧市| 吴旗县| 石渠县| 日照市| 榆社县| 汉源县| 宁陵县| 岱山县| 碌曲县| 大石桥市| 红桥区| 夏邑县| 绥宁县| 观塘区| 土默特右旗| 四会市| 长宁县| 延吉市| 仁怀市| 耿马| 资溪县| 宕昌县| 东乌珠穆沁旗| 平度市| 论坛| 启东市| 临朐县| 婺源县| 铁岭市| 醴陵市| 襄樊市| 宁南县| 木里| 珲春市| 榆中县| 宁陕县| 越西县|