Java 導出PDF 1、內容可以插入自定義表格 2、內容插入圖片

Java PDF導出工具:自定義表格與圖片插入

下面我將實現一個Java PDF導出工具,支持插入自定義表格和圖片的功能。這個解決方案使用iText 7庫,提供了一個直觀的用戶界面,可以預覽生成的PDF內容。

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.UnitValue;public class PDFExporter extends JFrame {private JTable table;private DefaultTableModel tableModel;private JTextArea previewArea;private List<String> imagePaths = new ArrayList<>();private PdfFont font;private PdfFont titleFont;public PDFExporter() {super("PDF導出工具 - 支持自定義表格與圖片插入");setSize(900, 700);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setLocationRelativeTo(null);initFonts();initUI();}private void initFonts() {try {// 創建字體(實際應用中應使用支持中文的字體文件)font = PdfFontFactory.createFont();titleFont = PdfFontFactory.createFont(PdfFontFactory.HELVETICA_BOLD);} catch (Exception e) {e.printStackTrace();font = PdfFontFactory.createFont(PdfFontFactory.COURIER);titleFont = PdfFontFactory.createFont(PdfFontFactory.COURIER_BOLD);}}private void initUI() {// 創建主面板JPanel mainPanel = new JPanel(new BorderLayout(10, 10));mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));// 創建頂部面板JPanel topPanel = new JPanel(new BorderLayout(10, 10));// 表格模型String[] columns = {"書名", "作者", "價格 (¥)", "出版年份", "評分"};tableModel = new DefaultTableModel(columns, 0);table = new JTable(tableModel);table.setRowHeight(30);table.setFont(new Font("微軟雅黑", Font.PLAIN, 14));// 添加示例數據addSampleData();JScrollPane tableScroll = new JScrollPane(table);tableScroll.setBorder(BorderFactory.createTitledBorder("自定義表格數據"));topPanel.add(tableScroll, BorderLayout.CENTER);// 表格操作按鈕JPanel tableButtonPanel = new JPanel(new GridLayout(5, 1, 5, 5));JButton addRowBtn = new JButton("添加行");JButton deleteRowBtn = new JButton("刪除行");JButton addImageBtn = new JButton("添加圖片");JButton previewBtn = new JButton("預覽PDF");JButton exportBtn = new JButton("導出PDF");addRowBtn.addActionListener(e -> tableModel.addRow(new Object[]{"", "", "", "", ""}));deleteRowBtn.addActionListener(e -> {int row = table.getSelectedRow();if (row != -1) {tableModel.removeRow(row);}});addImageBtn.addActionListener(e -> addImage());previewBtn.addActionListener(e -> previewPDF());exportBtn.addActionListener(e -> exportPDF());tableButtonPanel.add(addRowBtn);tableButtonPanel.add(deleteRowBtn);tableButtonPanel.add(addImageBtn);tableButtonPanel.add(previewBtn);tableButtonPanel.add(exportBtn);topPanel.add(tableButtonPanel, BorderLayout.EAST);// 預覽區域previewArea = new JTextArea();previewArea.setFont(new Font("等線", Font.PLAIN, 14));previewArea.setEditable(false);previewArea.setBackground(new Color(240, 240, 240));previewArea.setBorder(BorderFactory.createTitledBorder("PDF預覽內容"));JScrollPane previewScroll = new JScrollPane(previewArea);previewScroll.setPreferredSize(new Dimension(0, 200));// 添加組件到主面板mainPanel.add(topPanel, BorderLayout.CENTER);mainPanel.add(previewScroll, BorderLayout.SOUTH);add(mainPanel);// 狀態欄JLabel statusBar = new JLabel("就緒 | 添加表格數據并插入圖片,然后導出PDF");statusBar.setBorder(BorderFactory.createEtchedBorder());add(statusBar, BorderLayout.SOUTH);updatePreview();}private void addSampleData() {Object[][] data = {{"Java核心技術", "Cay S. Horstmann", "128.50", "2022", "4.8"},{"Effective Java", "Joshua Bloch", "99.80", "2018", "4.9"},{"深入理解Java虛擬機", "周志明", "119.00", "2019", "4.7"},{"Spring實戰", "Craig Walls", "89.90", "2020", "4.6"},{"Python編程:從入門到實踐", "Eric Matthes", "75.00", "2021", "4.7"}};for (Object[] row : data) {tableModel.addRow(row);}}private void addImage() {JFileChooser fileChooser = new JFileChooser();fileChooser.setDialogTitle("選擇要插入的圖片");fileChooser.setMultiSelectionEnabled(true);int result = fileChooser.showOpenDialog(this);if (result == JFileChooser.APPROVE_OPTION) {for (File file : fileChooser.getSelectedFiles()) {imagePaths.add(file.getAbsolutePath());}updatePreview();JOptionPane.showMessageDialog(this, "已添加 " + fileChooser.getSelectedFiles().length + " 張圖片", "添加圖片", JOptionPane.INFORMATION_MESSAGE);}}private void updatePreview() {StringBuilder sb = new StringBuilder();sb.append("PDF 內容預覽:\n");sb.append("----------------------------------------\n");sb.append("標題: 圖書清單報告\n\n");sb.append("表格數據 (").append(tableModel.getRowCount()).append(" 行):\n");for (int col = 0; col < tableModel.getColumnCount(); col++) {sb.append(String.format("%-20s", tableModel.getColumnName(col)));}sb.append("\n");for (int row = 0; row < tableModel.getRowCount(); row++) {for (int col = 0; col < tableModel.getColumnCount(); col++) {Object value = tableModel.getValueAt(row, col);sb.append(String.format("%-20s", value != null ? value.toString() : ""));}sb.append("\n");}sb.append("\n圖片列表 (").append(imagePaths.size()).append(" 張):\n");for (String path : imagePaths) {sb.append("? ").append(new File(path).getName()).append("\n");}previewArea.setText(sb.toString());}private void previewPDF() {try {File tempFile = File.createTempFile("pdf_preview", ".pdf");createPDF(tempFile.getAbsolutePath());if (Desktop.isDesktopSupported()) {Desktop.getDesktop().open(tempFile);} else {JOptionPane.showMessageDialog(this, "PDF預覽已生成: " + tempFile.getAbsolutePath(), "預覽生成成功", JOptionPane.INFORMATION_MESSAGE);}} catch (Exception ex) {ex.printStackTrace();JOptionPane.showMessageDialog(this, "生成預覽時出錯: " + ex.getMessage(), "錯誤", JOptionPane.ERROR_MESSAGE);}}private void exportPDF() {JFileChooser fileChooser = new JFileChooser();fileChooser.setDialogTitle("保存PDF文件");fileChooser.setSelectedFile(new File("圖書清單報告.pdf"));int result = fileChooser.showSaveDialog(this);if (result == JFileChooser.APPROVE_OPTION) {File file = fileChooser.getSelectedFile();String filePath = file.getAbsolutePath();if (!filePath.toLowerCase().endsWith(".pdf")) {filePath += ".pdf";}try {createPDF(filePath);JOptionPane.showMessageDialog(this, "PDF導出成功: " + filePath, "導出成功", JOptionPane.INFORMATION_MESSAGE);if (Desktop.isDesktopSupported()) {Desktop.getDesktop().open(new File(filePath));}} catch (Exception ex) {ex.printStackTrace();JOptionPane.showMessageDialog(this, "導出PDF時出錯: " + ex.getMessage(), "錯誤", JOptionPane.ERROR_MESSAGE);}}}private void createPDF(String filePath) throws Exception {try (PdfWriter writer = new PdfWriter(filePath);PdfDocument pdf = new PdfDocument(writer);Document document = new Document(pdf)) {// 設置文檔屬性document.setMargins(50, 50, 50, 50);// 添加標題Paragraph title = new Paragraph("圖書清單報告").setFont(titleFont).setFontSize(24).setTextAlignment(TextAlignment.CENTER).setFontColor(ColorConstants.DARK_GRAY).setMarginBottom(20);document.add(title);// 添加副標題Paragraph subtitle = new Paragraph("自定義表格與圖片展示").setFont(font).setFontSize(16).setTextAlignment(TextAlignment.CENTER).setFontColor(ColorConstants.GRAY).setMarginBottom(30);document.add(subtitle);// 添加表格addTableToDocument(document);// 添加圖片addImagesToDocument(document);// 添加頁腳Paragraph footer = new Paragraph("生成時間: " + new java.util.Date()).setFont(font).setFontSize(10).setTextAlignment(TextAlignment.CENTER).setFontColor(ColorConstants.LIGHT_GRAY).setMarginTop(30);document.add(footer);}}private void addTableToDocument(Document document) {// 創建表格float[] columnWidths = {3, 2, 1, 1, 1};Table pdfTable = new Table(UnitValue.createPercentArray(columnWidths));pdfTable.setWidth(UnitValue.createPercentValue(100));pdfTable.setMarginBottom(30);// 添加表頭for (int col = 0; col < tableModel.getColumnCount(); col++) {Cell headerCell = new Cell().add(new Paragraph(tableModel.getColumnName(col)).setFont(titleFont).setFontSize(12).setBackgroundColor(new com.itextpdf.kernel.color.Color(230, 230, 230)).setTextAlignment(TextAlignment.CENTER);pdfTable.addHeaderCell(headerCell);}// 添加表格數據for (int row = 0; row < tableModel.getRowCount(); row++) {for (int col = 0; col < tableModel.getColumnCount(); col++) {Object value = tableModel.getValueAt(row, col);String text = value != null ? value.toString() : "";Cell dataCell = new Cell().add(new Paragraph(text)).setFont(font).setFontSize(11);// 設置特殊列的樣式if (col == 2) { // 價格列dataCell.setTextAlignment(TextAlignment.RIGHT);} else if (col == 4) { // 評分列try {double rating = Double.parseDouble(text);if (rating >= 4.5) {dataCell.setFontColor(ColorConstants.GREEN);} else if (rating >= 4.0) {dataCell.setFontColor(ColorConstants.BLUE);} else {dataCell.setFontColor(ColorConstants.ORANGE);}} catch (NumberFormatException e) {// 忽略格式錯誤}dataCell.setTextAlignment(TextAlignment.CENTER);} else {dataCell.setTextAlignment(TextAlignment.LEFT);}pdfTable.addCell(dataCell);}}document.add(pdfTable);}private void addImagesToDocument(Document document) throws Exception {if (imagePaths.isEmpty()) return;// 添加圖片標題Paragraph imageTitle = new Paragraph("圖書封面").setFont(titleFont).setFontSize(16).setMarginBottom(15);document.add(imageTitle);// 添加圖片for (String path : imagePaths) {if (!Files.exists(Paths.get(path))) continue;try {ImageData imageData = ImageDataFactory.create(path);Image pdfImage = new Image(imageData);// 調整圖片大小(最大寬度400px,保持寬高比)float width = pdfImage.getImageWidth();float height = pdfImage.getImageHeight();float maxWidth = 400;if (width > maxWidth) {float ratio = maxWidth / width;pdfImage.scale(ratio, ratio);}// 居中顯示pdfImage.setHorizontalAlignment(com.itextpdf.layout.property.HorizontalAlignment.CENTER);pdfImage.setMarginBottom(20);document.add(pdfImage);} catch (Exception e) {System.err.println("無法加載圖片: " + path);e.printStackTrace();}}}public static void main(String[] args) {SwingUtilities.invokeLater(() -> {try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());} catch (Exception e) {e.printStackTrace();}PDFExporter exporter = new PDFExporter();exporter.setVisible(true);});}
}

使用說明

要運行此程序,您需要以下依賴項:

  1. iText 7 Core庫 (用于PDF生成)
  2. Java Swing (用于GUI)

Maven依賴配置

<dependencies><!-- iText 7 Core --><dependency><groupId>com.itextpdf</groupId><artifactId>itext7-core</artifactId><version>7.2.5</version><type>pom</type></dependency><!-- 其他必要的依賴項 -->
</dependencies>

程序功能

  1. 表格自定義

    • 添加/刪除表格行
    • 編輯表格內容
    • 支持多列數據
  2. 圖片插入

    • 添加多張圖片
    • 自動調整圖片大小
    • 保持圖片寬高比
  3. PDF操作

    • 預覽生成的PDF
    • 導出PDF文件
    • 自動打開生成的PDF
  4. 用戶界面

    • 表格數據編輯區
    • PDF內容預覽區
    • 操作按鈕面板

使用步驟

  1. 在表格中編輯或添加圖書數據
  2. 點擊"添加圖片"按鈕插入圖書封面
  3. 使用"預覽PDF"查看效果
  4. 滿意后點擊"導出PDF"保存文件

程序會自動為表格添加樣式,并根據評分值顯示不同顏色,使生成的PDF更具可讀性。

注意:實際使用中,您可能需要添加中文字體支持以正確顯示中文內容。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/89453.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/89453.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/89453.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

sklearn機器學習概述及API詳細使用指南

一、機器學習與sklearn簡介 機器學習是人工智能的一個分支&#xff0c;它通過算法讓計算機從數據中學習規律&#xff0c;并基于這些規律做出預測或決策。scikit-learn&#xff08;簡稱sklearn&#xff09;是Python中最流行的機器學習庫之一&#xff0c;它提供了各種監督學習和…

「日拱一碼」015 機器學習常用庫——scikit-learn

目錄 數據預處理 數據標準化&#xff08;StandardScaler&#xff09; 數據歸一化&#xff08;MinMaxScaler&#xff09; 數據離散化&#xff08;KBinsDiscretizer&#xff09; 缺失值處理&#xff08;SimpleImputer&#xff09; 特征選擇 基于單變量特征選擇&#xff08…

網絡編程學習路線

C網絡編程從零基礎到精通的學習路線&#xff0c;每一步都和你的項目實際需求緊密結合&#xff0c;幫助你真正做到“學以致用”。 C網絡編程學習路線&#xff08;結合FileHub項目&#xff09; 第一階段&#xff1a;網絡編程基礎入門 1. 計算機網絡基礎 理解OSI七層模型、TCP/I…

NLP:文本張量表示方法

本文目錄&#xff1a; 一、one-hot編碼二、word2vec模型&#xff08;一&#xff09;概念1.CBOW(Continuous bag of words)模式2.skipgram模式:3.詞向量的檢索獲取 &#xff08;二&#xff09;word2vec的訓練和使用1. 獲取訓練數據2.查看原始數據3.原始數據處理&#xff0c;并查…

高階數據結構------并查集

并查集 在一些應用問題中&#xff0c;需要將n個不同的元素劃分成一些不相交的集合。開始時&#xff0c;每個元素自成一個集合&#xff0c;然后按照一定的規律將歸于同一組的元素集合合并。在此過程中要反復用到查詢某一個元素歸屬于哪一個集合的運算。適合于描述這類問題的抽象…

OWASP Top 10 是什么?

OWASP&#xff08;Open Web Application Security Project&#xff0c;開放Web應用安全項目&#xff09;是一個致力于提高軟件安全性的國際非營利組織。其發布的 ?OWASP Top 10? 是最具影響力的Web應用安全風險清單&#xff0c;每3-4年更新一次&#xff0c;幫助開發人員、安全…

如何在IIS上部署net系統(安裝iis參考上一篇)

1.對后端項目打包&#xff0c;我使用的時rider 2.打包前端 npm run build 3.在iis上部署 網站-添加網站 4.選擇之前打包的后端文件&#xff0c;設置端口 5.安裝對應net環境插件&#xff1a;主要是runtime和sdk插件以及dotnet-hosting-2.2.0-win&#xff0c;具體版本看自己項…

Docker可視化管理工具Portainer安裝部署

1、安裝Portainer 編寫docker compose文件&#xff0c;使用docker compose文件完成Portainer的安裝&#xff0c;首先需要在服務器上編寫的名為portainer.yaml的文件&#xff0c;內容如下&#xff1a; [rootserver ~]# cat portainer.yaml services: portainer: image:…

ai之RAG本地知識庫--基于OCR和文本解析器的新一代RAG引擎:RAGFlow 認識和源碼剖析

目錄標題 RAG本地知識庫問答——基于OCR和文本解析器的新一代RAG引擎&#xff1a;RAGFlow 認識和源碼剖析RAGflow 主要功能&#xff1a; 一、RAGflow 簡介1.1 允許用戶上傳并管理自己的文檔(文檔類型可以是任意類型)1.2 RAGFlow的4個特色1.2.1 AI 模型的智能文檔處理系統1.2.2 …

[面試] 手寫題-new

function mynew(Func, ...args) {// 1.創建一個空對象const obj {}// 2.新對象隱式原型指向構造函數的顯式原型obj.__proto__ Func.prototype// 3.將構建函數的this指向新對象let result Func.apply(obj, args)// 4.返回objreturn result instanceof Object ? result : obj…

設計模式精講 Day 20:狀態模式(State Pattern)

【設計模式精講 Day 20】狀態模式&#xff08;State Pattern&#xff09; 文章標簽 設計模式, 狀態模式, Java開發, 面向對象設計, 軟件架構, 設計模式實戰, Java應用開發 文章簡述 狀態模式是行為型設計模式中的重要一員&#xff0c;用于管理對象在不同狀態下的行為變化。在…

橋島隧大型工程 3D 可視化監測平臺

深中通道作為“橋、島、隧、水下互通”一體化跨海集群工程&#xff0c;其復雜結構帶來高強度監測難題。借助圖撲軟件 HT 實現深中通道的建設與運營的數字化升級&#xff0c;為交通基建行業邁向高效、智能的未來提供了有力支撐。 圖撲自主研發的 HT for Web 產品搭建深中通道-橋…

基于SpringBoot和Leaflet的區域沖突可視化系統(2025企業級實戰方案)

摘要 在全球地緣沖突與應急事件頻發的2025年&#xff0c;區域態勢可視化系統成為政府及企業的決策剛需。本文提出基于??SpringBoot 3.2??后端與??Leaflet 1.9.5??前端的沖突可視化解決方案&#xff0c;融合多源異構數據&#xff08;衛星影像、輿情熱力、設施狀態&…

[密碼學實戰]國密TLCP協議報文解析代碼實現(三十)

[密碼學實戰]國密TLCP協議報文解析代碼實現(三十) 本文將深入解析國密TLCP協議報文結構,提供完整的Java實現代碼,幫助開發者理解TLCP協議在國密環境下的通信機制和安全性設計。 一、國密TLCP協議概述 TLCP(Transport Layer Cryptographic Protocol)是基于國密算法(SM2/…

[Python] -基礎篇5-玩轉Python內置數據結構:列表、元組、字典與集合

Python 是一門以簡潔優雅著稱的編程語言,其中內置的數據結構為日常編程提供了強大支持。本文將系統介紹 Python 中四大核心數據結構:列表(list)、元組(tuple)、字典(dict)與集合(set),并配以實用示例,幫助讀者全面掌握其用法及適用場景。 一、列表(List):可變序…

技術突破與落地應用:端到端 2.0 時代輔助駕駛TOP10 論文深度拆解系列【第八篇(排名不分先后)】

HiP-AD: Hierarchical and Multi-Granularity Planning with Deformable Attention for Autonomous Driving in a Single Decoder GitHub地址&#xff1a;?https://github.com/nullmax-vision/HiP-AD? 在自動駕駛技術飛速發展的今天&#xff0c;端到端自動駕駛&#xff08;E…

transformer位置編碼研究相關的綜述、論文

一、權威綜述 《利用位置編碼實現長度外推》 &#xff08;騰訊云開發者社區, 2024&#xff09; 系統分析絕對/相對位置編碼&#xff08;APE/RPE&#xff09;在長序列外推中的技術演進&#xff0c;涵蓋RoPE、Alibi、Xpos等優化方案&#xff0c;討論位置插值、NTK-aware縮放等擴展…

垂直領域AI智能體開發指南:用Bright Data MCP接入智能體攻克數據難關

垂直領域AI智能體開發指南&#xff1a;用Bright Data MCP接入智能體攻克數據難關 一、智能體時代的數據困局1.1 AI智能體的爆發式增長1.2 開發者遭遇的"數據瓶頸" 二、Bright Data MCP&#xff1a;智能體的數據引擎2.1 重新定義數據獲取方式2.2 支持的核心場景2.3 四…

Stable Diffusion 項目實戰落地:從0到1 掌握ControlNet 第三篇: 打造光影字形的創意秘技-文字與自然共舞

上一篇,我們一起玩轉了 野外光影字,是不是被那種自然和光影交織的效果驚艷到啦? 如果你錯過了那篇文章,別擔心,趕緊點這里補課:Stable Diffusion 項目實戰落地:從0到1 掌握ControlNet:打造光影文字 第二篇 - 野外光影字。 今天,我們將一起做一個 生成的嵌入式文字【…

CppCon 2018 學習:Feather: A Modern C++ Web Development Framework

你這段內容羅列的是 Web 開發中的幾個基礎概念和組成模塊&#xff0c;下面我逐一用中文進行解釋&#xff0c;并理清它們之間的關系&#xff1a; 基礎概念說明 1. HTTP Server&#xff08;HTTP服務器&#xff09; 是一個監聽 HTTP 請求并返回響應的程序。主要功能&#xff1a…