当前位置: 首页 > news >正文

Java实现多张图片合并保存到pdf中

Java实现多张图片合并保存到pdf中

1、依赖–maven
        <dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>2.0.24</version></dependency>
2、上代码
package com.hxlinks.hxiot.controller;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.LosslessFactory;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.thymeleaf.expression.Lists;import javax.imageio.ImageIO;
import java.awt.geom.Point2D;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;public class PdfBoxMultipleImagesToPdf {public static void main(String[] args) {List<String> imagePaths = Arrays.asList("C:\\Users\\89131\\Desktop\\1.png", "C:\\Users\\89131\\Desktop\\2.png","C:\\Users\\89131\\Desktop\\3.png", "C:\\Users\\89131\\Desktop\\4.png");File outputPdf = new File("D:/output.pdf");try {createPdfFromImages(imagePaths, outputPdf);System.out.println("PDF with images created successfully.");} catch (IOException e) {e.printStackTrace();}}
//
//    public static void createPdfFromImages(List<String> imagePaths, File outputFile) throws IOException {
//        try (PDDocument document = new PDDocument()) {
//            for (String imagePath : imagePaths) {
//                // Load image
//                PDImageXObject image = LosslessFactory.createFromImage(document, ImageIO.read(new File(imagePath)));
//
//                // Create a new page and add it to the document
//                PDPage page = new PDPage(PDRectangle.A4);
//                document.addPage(page);
//
//                // Get the content stream for the page
//                try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
//                    // Define the position and size for the image on the page
//                    float imgWidth = image.getWidth();
//                    float imgHeight = image.getHeight();
//                    float margin = 50; // Example margin
//                    float x = (page.getMediaBox().getWidth() - imgWidth) / 2;
//                    float y = (page.getMediaBox().getHeight() - imgHeight) - margin;
//
//                    // Draw the image onto the page
//                    contentStream.drawImage(image, x, y, imgWidth, imgHeight);
//                }
//            }
//
//            // Save the final document
//            document.save(outputFile);
//        }
//    }public static void createPdfFromImages(List<String> imagePaths, File outputFile) throws IOException {try (PDDocument document = new PDDocument()) {float margin = 50f; // Define the marginfor (String imagePath : imagePaths) {// Load imagePDImageXObject image = LosslessFactory.createFromImage(document, ImageIO.read(new File(imagePath)));// Calculate scaling factor to fit image within the page minus margins, maintaining aspect ratiofloat imgWidth = image.getWidth();float imgHeight = image.getHeight();float pageWidthForImage = PDRectangle.A4.getWidth() - 2 * margin; // Subtracting total margin from widthfloat pageHeightForImage = PDRectangle.A4.getHeight() - 2 * margin; // Subtracting total margin from heightfloat scaleX = pageWidthForImage / imgWidth;float scaleY = pageHeightForImage / imgHeight;float scale = Math.min(scaleX, scaleY);// Resize the image dimensions with the scaleimgWidth *= scale;imgHeight *= scale;// Create a new page and add it to the documentPDPage page = new PDPage(PDRectangle.A4);document.addPage(page);// Get the content stream for the pagetry (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {// Calculate the centered position considering the total margin around the pagefloat x = (page.getMediaBox().getWidth() - imgWidth) / 2; // Centered without adding margin againfloat y = (page.getMediaBox().getHeight() - imgHeight) / 2; // Centered without adding margin again// Draw the scaled image onto the page at the correctly centered positioncontentStream.drawImage(image, x, y, imgWidth, imgHeight); // Apply margin here}}// Save the final documentdocument.save(outputFile);}}
}

相关文章:

Java实现多张图片合并保存到pdf中

Java实现多张图片合并保存到pdf中 1、依赖–maven <dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>2.0.24</version></dependency>2、上代码 package com.hxlinks.hxiot.contro…...

揭秘智慧校园:可视化技术引领教育新篇章

随着科技的飞速发展&#xff0c;我们的生活方式正在经历一场前所未有的变革。而在这场变革中&#xff0c;学校作为培养未来人才的重要基地&#xff0c;也在不断地探索与创新。 一、什么是校园可视化&#xff1f; 校园可视化&#xff0c;就是通过先进的信息技术&#xff0c;将学…...

基础9 探索图形化编程的奥秘:从物联网到工业自动化

办公室内&#xff0c;明媚的阳光透过窗户洒落&#xff0c;为每张办公桌披上了一层金色的光辉。同事们各自忙碌着&#xff0c;键盘敲击声、文件翻页声和低声讨论交织在一起&#xff0c;营造出一种忙碌而有序的氛围。空气中氤氲着淡淡的咖啡香气和纸张的清新味道&#xff0c;令人…...

RPC-----RCF

RPC RPC(Remote Procedure Call Protocol&#xff09;——远程过程调用协议。 RCF...

StarRocks中,这些配置项是表属性的一部分

CREATE TABLE warehouse.ads_order_all_df ( so_id varchar(200) NULL COMMENT "销售订单主表标识", so_code varchar(200) NULL COMMENT "销售订单主表表号" ) ENGINEOLAP DUPLICATE KEY(so_id) COMMENT "OLAP" DISTRIBUTED BY HASH(dt) …...

Activity->Activity生命周期

<四大组件 android:name"xxx"android:exported"true" // 该组边能够被其他组件启动android:enabled"true" // 该组件能工与用户交互 </四大组件>Activity常用生命周期 启动Activity 2024-05-29 03:53:57.401 21372-21372 yang …...

乐鑫ESP串口驱动安装,安装cp210x驱动

windows11安装cp210x驱动&#xff1a; 1&#xff1a;第一步官网下载驱动&#xff1a; 官网地址如下&#xff1a; CP210x USB to UART Bridge VCP Drivers - Silicon Labs 第二步&#xff1a;解压文件夹并安装如图所示&#xff1a; 3&#xff1a;第三步安装成功后会给你个提示…...

Django缓存

由于Django是动态网站&#xff0c;所有每次请求均会去数据进行相应的操作&#xff0c;当程序访问量大时&#xff0c;耗时必然会更加明显&#xff0c;最简单解决方式是使用&#xff1a;缓存&#xff0c;缓存将一个某个views的返回值保存至内存或者memcache中&#xff0c;若某个时…...

Python 元组

&#xff08;1&#xff09;元组中只包含一个元素时&#xff0c;需要在元素后面添加逗号&#xff1a; tup1 (50,); &#xff08;2&#xff09;元组中的元素值是不允许修改的&#xff0c;但我们可以对元组进行连接组合&#xff1a; tup1 (12, 34.56); tup2 (abc, xyz);# 以…...

JAVA面试题大全(十八)

1、说一下 jvm 的主要组成部分&#xff1f;及其作用&#xff1f; 类加载器&#xff08;ClassLoader&#xff09;运行时数据区&#xff08;Runtime Data Area&#xff09;执行引擎&#xff08;Execution Engine&#xff09;本地库接口&#xff08;Native Interface&#xff09;…...

如何利用Firebase Hosting来托管网站

文章目录 如何利用Firebase Hosting来托管网站前提条件详细步骤1. 安装 Firebase CLI2. 登录 Firebase3. 初始化 Firebase 项目4. 准备网站文件5. 部署到 Firebase6. 配置自定义域名&#xff08;可选&#xff09; 常见问题 如何利用Firebase Hosting来托管网站 以下是更详细的…...

揭秘“循环消费”模式:消费即收益,购物新体验

亲爱的朋友们&#xff0c;大家好&#xff0c;我是李华。今天&#xff0c;我要为大家介绍一种正在悄然兴起的商业模式——“循环消费”。你是否曾想过&#xff0c;在消费的同时&#xff0c;还能获得额外的收益和回馈&#xff1f;这种新型模式正在逐渐改变我们的购物体验。 近期&…...

图片怎样在线改像素大小?电脑快速修改图片大小的方法

在设计图片的时候下载的图片尺寸一般会比较大&#xff0c;在网上使用经常会因为尺寸的问题导致无法正常上传&#xff0c;那么如何快速在线改图片大小呢&#xff1f;想要修改图片尺寸可以在直接选择网上的图片改大小工具的功能来快速完成修改&#xff0c;操作简单方便使用&#…...

SELINUX=enforcing时无法启动httpd服务的解决方案(semanage命令以及setroubleshoot-server插件的妙用)

一、问题描述&#xff1a; 当/etc/selinux/conf被要求必须是SELINUXenforcing&#xff0c;不被允许使用setenforce 0宽松模式 我们启动httpd就会报错&#xff1a; Job for httpd.service failed because the control process exited with error code. See "systemctl s…...

【C++】list的使用方法和模拟实现

❤️欢迎来到我的博客❤️ 前言 list是可以在常数范围内在任意位置进行插入和删除的序列式容器&#xff0c;并且该容器可以前后双向迭代list的底层是双向链表结构&#xff0c;双向链表中每个元素存储在互不相关的独立节点中&#xff0c;在节点中通过指针指向其前一个元素和后…...

【物联网实战项目】STM32C8T6+esp8266/mqtt+dht11+onenet+uniapp

一、实物图 前端uniapp效果图&#xff08;实现与onenet同步更新数据&#xff09; 首先要确定接线图和接线顺序&#xff1a; 1、stm32c8t6开发板连接stlinkv2下载线 ST-LINK V2STM323.3V3.3VSWDIOSWIOSWCLKSWCLKGNDGND 2、ch340串口连接底座&#xff08;注意RXD和TXD的连接方式…...

Pyhton 二叉树层级遍历

class TreeNode:def __init__(self, val0, leftNone, rightNone):self.val valself.left leftself.right rightclass Solution:def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:res []# 空节点&#xff0c;直接返回if not root:return resque [roo…...

Flutter 中的 FadeTransition 小部件:全面指南

Flutter 中的 FadeTransition 小部件&#xff1a;全面指南 在 Flutter 中&#xff0c;动画是一种吸引用户注意力并提供流畅用户体验的强大工具。FadeTransition 是 Flutter 提供的一个动画小部件&#xff0c;它允许子组件在不透明度上进行渐变&#xff0c;从而实现淡入和淡出效…...

缓存存储器:性能提升的关键

目录 基本原理 主存与缓存的地址映射 主存的替换策略 缓存的写操作策略 Pentium 4 的缓存组织 使用多级缓存减少缺失损失 结论 在计算机系统中&#xff0c;缓存存储器&#xff08;Cache Memory&#xff09;发挥着至关重要的作用。它充当处理器和主存之间的高速缓冲区&am…...

『大模型笔记』工程师的LLMs简介!

💡工程师的LLMs简介 ! 文章目录 1. Embeddings Conceptually(嵌入的概念)1.1. One-hot Encodings(独热编码)1.2. Embeddings(嵌入)2. LLM Basics(LLM 基础知识)3. Autoregressive LLMs(自回归LLMs)4. Where to go from here(何去何从?)5. 参考文献https://devo…...

遍历 Map 类型集合的方法汇总

1 方法一 先用方法 keySet() 获取集合中的所有键。再通过 gey(key) 方法用对应键获取值 import java.util.HashMap; import java.util.Set;public class Test {public static void main(String[] args) {HashMap hashMap new HashMap();hashMap.put("语文",99);has…...

P3 QT项目----记事本(3.8)

3.8 记事本项目总结 项目源码 1.main.cpp #include "widget.h" #include <QApplication> int main(int argc, char *argv[]) {QApplication a(argc, argv);Widget w;w.show();return a.exec(); } 2.widget.cpp #include "widget.h" #include &q…...

【2025年】解决Burpsuite抓不到https包的问题

环境&#xff1a;windows11 burpsuite:2025.5 在抓取https网站时&#xff0c;burpsuite抓取不到https数据包&#xff0c;只显示&#xff1a; 解决该问题只需如下三个步骤&#xff1a; 1、浏览器中访问 http://burp 2、下载 CA certificate 证书 3、在设置--隐私与安全--…...

C++ Visual Studio 2017厂商给的源码没有.sln文件 易兆微芯片下载工具加开机动画下载。

1.先用Visual Studio 2017打开Yichip YC31xx loader.vcxproj&#xff0c;再用Visual Studio 2022打开。再保侟就有.sln文件了。 易兆微芯片下载工具加开机动画下载 ExtraDownloadFile1Info.\logo.bin|0|0|10D2000|0 MFC应用兼容CMD 在BOOL CYichipYC31xxloaderDlg::OnIni…...

Pinocchio 库详解及其在足式机器人上的应用

Pinocchio 库详解及其在足式机器人上的应用 Pinocchio (Pinocchio is not only a nose) 是一个开源的 C 库&#xff0c;专门用于快速计算机器人模型的正向运动学、逆向运动学、雅可比矩阵、动力学和动力学导数。它主要关注效率和准确性&#xff0c;并提供了一个通用的框架&…...

嵌入式学习笔记DAY33(网络编程——TCP)

一、网络架构 C/S &#xff08;client/server 客户端/服务器&#xff09;&#xff1a;由客户端和服务器端两个部分组成。客户端通常是用户使用的应用程序&#xff0c;负责提供用户界面和交互逻辑 &#xff0c;接收用户输入&#xff0c;向服务器发送请求&#xff0c;并展示服务…...

QT3D学习笔记——圆台、圆锥

类名作用Qt3DWindow3D渲染窗口容器QEntity场景中的实体&#xff08;对象或容器&#xff09;QCamera控制观察视角QPointLight点光源QConeMesh圆锥几何网格QTransform控制实体的位置/旋转/缩放QPhongMaterialPhong光照材质&#xff08;定义颜色、反光等&#xff09;QFirstPersonC…...

【从零学习JVM|第三篇】类的生命周期(高频面试题)

前言&#xff1a; 在Java编程中&#xff0c;类的生命周期是指类从被加载到内存中开始&#xff0c;到被卸载出内存为止的整个过程。了解类的生命周期对于理解Java程序的运行机制以及性能优化非常重要。本文会深入探寻类的生命周期&#xff0c;让读者对此有深刻印象。 目录 ​…...

【Nginx】使用 Nginx+Lua 实现基于 IP 的访问频率限制

使用 NginxLua 实现基于 IP 的访问频率限制 在高并发场景下&#xff0c;限制某个 IP 的访问频率是非常重要的&#xff0c;可以有效防止恶意攻击或错误配置导致的服务宕机。以下是一个详细的实现方案&#xff0c;使用 Nginx 和 Lua 脚本结合 Redis 来实现基于 IP 的访问频率限制…...

第7篇:中间件全链路监控与 SQL 性能分析实践

7.1 章节导读 在构建数据库中间件的过程中&#xff0c;可观测性 和 性能分析 是保障系统稳定性与可维护性的核心能力。 特别是在复杂分布式场景中&#xff0c;必须做到&#xff1a; &#x1f50d; 追踪每一条 SQL 的生命周期&#xff08;从入口到数据库执行&#xff09;&#…...