導航:首頁 > 文檔加密 > java生成pdf並列印

java生成pdf並列印

發布時間:2024-09-17 06:13:19

pdf列印 彈出提示框 java開發

這個大概應該是在jFrame裡面,點擊列印pdf按鈕,然後打開這個對話框的Jframe,在這個界面,可以返回兩個參數給那個按鈕的界面,如果返回 是,則繼續執行列印pdf的java代碼。

❷ 如何運用Java組件itext生成pdf

實現流程:
一、iText介紹
iText是著名的開放源碼的站點sourceforge一個項目,是用於生成PDF文檔的一個java類庫。通過iText不僅可以生成PDF或rtf的文檔,而且可以將XML、Html文件轉化為PDF文件。
二、建立第一個PDF文檔
用iText生成PDF文檔需要5個步驟:
①建立com.lowagie.text.Document對象的實例。
Document document = new Document();
②建立一個書寫器(Writer)與document對象關聯,通過書寫器(Writer)可以將文檔寫入到磁碟中。
PDFWriter.getInstance(document, new FileOutputStream("Helloworld.PDF"));
③打開文檔。
document.open();
④向文檔中添加內容。
document.add(new Paragraph("Hello World"));
⑤關閉文檔。
document.close();
通過上面的5個步驟,就能產生一個Helloworld.PDF的文件,文件內容為"Hello World"。
建立com.lowagie.text.Document對象的實例
com.lowagie.text.Document對象的構建函數有三個,分別是:
public Document();
public Document(Rectangle pageSize);
public Document(Rectangle pageSize,
int marginLeft,
int marginRight,
int marginTop,
int marginBottom);
構建函數的參數pageSize是文檔頁面的大小,對於第一個構建函數,頁面的大小為A4,同Document(PageSize.A4)的效果一樣;
對於第三個構建函數,參數marginLeft、marginRight、marginTop、marginBottom分別為左、右、上、下的頁邊距。
通過參數pageSize可以設定頁面大小、面背景色、以及頁面橫向/縱向等屬性。iText定義了A0-A10、AL、LETTER、
HALFLETTER、_11x17、LEDGER、NOTE、B0-B5、ARCH_A-ARCH_E、FLSA
和FLSE等紙張類型,也可以通過Rectangle pageSize = new Rectangle(144,
720);自定義紙張。通過Rectangle方法rotate()可以將頁面設置成橫向。
書寫器(Writer)對象
一旦文檔(document)對象建立好之後,需要建立一個或多個書寫器(Writer)對象與之關聯。通過書寫器(Writer)對象可以將具體文檔
存檔成需要的格式,如com.lowagie.text.PDF.PDFWriter可以將文檔存成PDF文件,
com.lowagie.text.html.HtmlWriter可以將文檔存成html文件。
設定文檔屬性
在文檔打開之前,可以設定文檔的標題、主題、作者、關鍵字、裝訂方式、創建者、生產者、創建日期等屬性,調用的方法分別是:
public boolean addTitle(String title)
public boolean addSubject(String subject)
public boolean addKeywords(String keywords)
public boolean addAuthor(String author)
public boolean addCreator(String creator)
public boolean addProcer()
public boolean addCreationDate()
public boolean addHeader(String name, String content)
其中方法addHeader對於PDF文檔無效,addHeader僅對html文檔有效,用於添加文檔的頭信息。
當新的頁面產生之前,可以設定頁面的大小、書簽、腳注(HeaderFooter)等信息,調用的方法是:
public boolean setPageSize(Rectangle pageSize)
public boolean add(Watermark watermark)
public void removeWatermark()
public void setHeader(HeaderFooter header)
public void resetHeader()
public void setFooter(HeaderFooter footer)
public void resetFooter()
public void resetPageCount()
public void setPageCount(int pageN)
如果要設定第一頁的頁面屬性,這些方法必須在文檔打開之前調用。
對於PDF文檔,iText還提供了文檔的顯示屬性,通過調用書寫器的setViewerPreferences方法可以控制文檔打開時Acrobat Reader的顯示屬性,如是否單頁顯示、是否全屏顯示、是否隱藏狀態條等屬性。
另外,iText也提供了對PDF文件的安全保護,通過書寫器(Writer)的setEncryption方法,可以設定文檔的用戶口令、只讀、可列印等屬性。
添加文檔內容
所有向文檔添加的內容都是以對象為單位的,如Phrase、Paragraph、Table、Graphic對象等。比較常用的是段落(Paragraph)對象,用於向文檔中添加一段文字。
三、文本處理
iText中用文本塊(Chunk)、短語(Phrase)和段落(paragraph)處理文本。
文本塊(Chunk)是處理文本的最小單位,有一串帶格式(包括字體、顏色、大小)的字元串組成。如以下代碼就是產生一個字體為HELVETICA、大小為10、帶下劃線的字元串:
Chunk chunk1 = new Chunk("This text is underlined", FontFactory.getFont(FontFactory.HELVETICA, 12, Font.UNDERLINE));
短語(Phrase)由一個或多個文本塊(Chunk)組成,短語(Phrase)也可以設定字體,但對於其中以設定過字體的文本塊
(Chunk)無效。通過短語(Phrase)成員函數add可以將一個文本塊(Chunk)加到短語(Phrase)中,
如:phrase6.add(chunk);
段落(paragraph)由一個或多個文本塊(Chunk)或短語(Phrase)組
成,相當於WORD文檔中的段落概念,同樣可以設定段落的字體大小、顏色等屬性。另外也可以設定段落的首行縮進、對齊方式(左對齊、右對齊、居中對齊)。
通過函數setAlignment可以設定段落的對齊方式, setAlignment的參數1為居中對齊、2為右對齊、3為左對齊,默認為左對齊。
四、表格處理
iText中處理表格的類為:com.lowagie.text.Table和com.lowagie.text.PDF.PDFPTable,對於比
較簡單的表格處理可以用com.lowagie.text.Table,但是如果要處理復雜的表格,這就需要
com.lowagie.text.PDF.PDFPTable進行處理。這里就類com.lowagie.text.Table進行說明。
類com.lowagie.text.Table的構造函數有三個:
①Table (int columns)
②Table(int columns, int rows)
③Table(Properties attributes)
參數columns、rows、attributes分別為表格的列數、行數、表格屬性。創建表格時必須指定表格的列數,而對於行數可以不用指定。
建立表格之後,可以設定表格的屬性,如:邊框寬度、邊框顏色、襯距(padding space 即單元格之間的間距)大小等屬性。下面通過一個簡單的例子說明如何使用表格,代碼如下:
1:Table table = new Table(3);
2:table.setBorderWidth(1);
3:table.setBorderColor(new Color(0, 0, 255));
4:table.setPadding(5);
5:table.setSpacing(5);
6:Cell cell = new Cell("header");
7:cell.setHeader(true);
8:cell.setColspan(3);
9:table.addCell(cell);
10:table.endHeaders();
11:cell = new Cell("example cell with colspan 1 and rowspan 2");
12:cell.setRowspan(2);
13:cell.setBorderColor(new Color(255, 0, 0));
14:table.addCell(cell);
15:table.addCell("1.1");
16:table.addCell("2.1");
17:table.addCell("1.2");
18:table.addCell("2.2");
19:table.addCell("cell test1");
20:cell = new Cell("big cell");
21:cell.setRowspan(2);
22:cell.setColspan(2);
23:table.addCell(cell);
24:table.addCell("cell test2");
運行結果如下:
header
example cell with colspan 1 and rowspan 2 1.1 2.1
1.2 2.2
cell test1 big cell
cell test2
代碼1-5行用於新建一個表格,如代碼所示,建立了一個列數為3的表格,並將邊框寬度設為1,顏色為藍色,襯距為5。
代碼6-10行用於設定表格的表頭,第7行cell.setHeader(true);是將該單元格作為表頭信息顯示;第8行
cell.setColspan(3);指定了該單元格佔3列;為表格添加表頭信息時,要注意的是一旦表頭信息添加完了之後,必須調用
endHeaders()方法,如第10行,否則當表格跨頁後,表頭信息不會再顯示。
代碼11-14行是向表格中添加一個寬度佔一列,長度佔二行的單元格。
往表格中添加單元格(cell)時,按自左向右、從上而下的次序添加。如執行完11行代碼後,表格的右下方出現2行2列的空白,這是再往表格添加單元格時,先填滿這個空白,然後再另起一行,15-24行代碼說明了這種添加順序。
五、圖像處理
iText中處理表格的類為com.lowagie.text.Image,目前iText支持的圖像格式有:GIF, Jpeg, PNG,
wmf等格式,對於不同的圖像格式,iText用同樣的構造函數自動識別圖像格式。通過下面的代碼分別獲得gif、jpg、png圖像的實例。
Image gif = Image.getInstance("vonnegut.gif");
Image jpeg = Image.getInstance("myKids.jpg");
Image png = Image.getInstance("hitchcock.png");
圖像的位置
圖像的位置主要是指圖像在文檔中的對齊方式、圖像和文本的位置關系。IText中通過函數public void setAlignment(int
alignment)進行處理,參數alignment為Image.RIGHT、Image.MIDDLE、Image.LEFT分別指右對齊、居中、
左對齊;當參數alignment為Image.TEXTWRAP、Image.UNDERLYING分別指文字繞圖形顯示、圖形作為文字的背景顯示。這
兩種參數可以結合以達到預期的效果,如setAlignment(Image.RIGHT|Image.TEXTWRAP)顯示的效果為圖像右對齊,文字
圍繞圖像顯示。
圖像的尺寸和旋轉
如果圖像在文檔中不按原尺寸顯示,可以通過下面的函數進行設定:
public void scaleAbsolute(int newWidth, int newHeight)
public void scalePercent(int percent)
public void scalePercent(int percentX, int percentY)
函數public void scaleAbsolute(int newWidth, int
newHeight)直接設定顯示尺寸;函數public void scalePercent(int
percent)設定顯示比例,如scalePercent(50)表示顯示的大小為原尺寸的50%;而函數scalePercent(int
percentX, int percentY)則圖像高寬的顯示比例。
如果圖像需要旋轉一定角度之後在文檔中顯示,可以通過函數public void setRotation(double r)設定,參數r為弧度,如果旋轉角度為30度,則參數r= Math.PI / 6。
六、中文處理
默認的iText字體設置不支持中文字體,需要下載遠東字體包iTextAsian.jar,否則不能往PDF文檔中輸出中文字體。通過下面的代碼就可以在文檔中使用中文了:
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
com.lowagie.text.Font FontChinese = new com.lowagie.text.Font(bfChinese, 12, com.lowagie.text.Font.NORMAL);
Paragraph pragraph=new Paragraph("你好", FontChinese);

❸ java實現生成導出pdf文件需要哪些jar包

可以下載Spire.Pdf.jar這個,適用於創建、編輯、轉換PDF文檔,下載後,只需要在java程序裡面導入這一個jar文件就可以進行PDF文檔操作了,具體可查看官方教程庫,有很多教程文章可以參考使用,寫的比較詳細了

❹ Spring Boot——Thymeleaf生成PDF實戰教程

Thymeleaf是一個現代的伺服器端 Java 模板引擎,適用於 Web 和獨立環境。它為開發工作流程帶來優雅的自然模板——HTML可以在瀏覽器中正確顯示,也可以用作靜態原型,從而在開發團隊中實現更強大的協作。藉助 Spring Framework 的模塊、與您最喜歡的工具的大量集成以及插入您自己的功能的能力,Thymeleaf 是現代 HTML5 JVM Web 開發的理想選擇——盡管它可以做的更多。通過下面的步驟,您可以了解如何使用 Thymeleaf 模板引擎實現 PDF 列印。

首先,確保已引入必要的 Thymeleaf 依賴。版本應根據實際情況選擇相應的版本。接下來,配置 application.yml 文件以指定 Thymeleaf 模板路徑。配置示例包括設置路徑以存儲生成的 PDF 文件。

為了生成 PDF,需要配置 PDF 相關設置。這包括添加列印所需的字體,如 SIMSUN.TTC。此外,確保所有配置信息正確無誤,然後編寫 API 介面。在介面請求過程中,可能會遇到錯誤信息,這些通常與列印模板路徑配置錯誤有關。解決這類問題的方法是檢查和修正 application.yml 文件中的相關配置。

完成所有配置後,可以測試 PDF 文件的生成效果。點擊「Save to a file」保存生成的文件,並查看響應結果。結果數據僅供參考,實際應用中,您將獲得所需的 PDF 文件。

❺ 如何運用Java組件itext生成pdf

Controller層(param為數據)

byte[]bytes=PdfUtils.createPdf(param);
ByteArrayInputStreaminStream=newByteArrayInputStream(bytes);
//設置輸出的格式
response.setContentType("bin");
response.setHeader("content-disposition","attachment;filename="+URLEncoder.encode(itemName+"(評審意見).pdf","UTF-8"));
//循環取出流中的數據
byte[]b=newbyte[2048];
intlen;
while((len=inStream.read(b))>0)
response.getOutputStream().write(b,0,len);

inStream.close();

Service層(param為數據)

public static byte[] createPdf(Map<String,Object> param) {

byte[] result= null;

ByteArrayOutputStream baos = null;

//支流程評審信息匯總

List<CmplncBranchRvwInfoDTO> branchRvwInfos = (List<CmplncBranchRvwInfoDTO>) param.get("branchRvwInfos");

//主流程評審信息匯總

List<CmplncMainRvwInfoDTO> mainRvwInfos = (List<CmplncMainRvwInfoDTO>) param.get("mainRvwInfos");

//主評審信息

CmplncRvwFormDTO rvwFormDTO = (CmplncRvwFormDTO) param.get("rvwFormDTO");

//附件列表

List<FileInfoDTO> fileList = (List<FileInfoDTO>) param.get("fileList");

//專業公司

String legalEntityDeptDesc = (String) param.get("legalEntityDeptDesc");

String legalEntitySonDeptDesc = (String) param.get("legalEntitySonDeptDesc");

//設置頁邊距

Document doc = new Document(PageSize.A4, 20, 20, 60, 20);

try {

baos = new ByteArrayOutputStream();//構建位元組輸出流

PdfWriter writer = PdfWriter.getInstance(doc,baos);

//頁眉頁腳字體

BaseFont bf = null;

BaseFont bFont = null;

try {

bFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);

bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);

} catch (Exception e) {

e.printStackTrace();

}

Font footerFont = new Font(bFont, 10, Font.NORMAL);

Font title = new Font(bf,15,Font.BOLD);

Font content = new Font(bf,9,Font.NORMAL);

Font chinese = new Font(bf, 10, Font.BOLD);

/**

* HeaderFooter的第2個參數為非false時代表列印頁碼

* 頁眉頁腳中也可以加入圖片,並非只能是文字

*/

HeaderFooter header=new HeaderFooter(new Phrase("法律合規評審系統",title),false);

//設置是否有邊框等

header.setBorder(Rectangle.NO_BORDER);

header.setAlignment(1);

doc.setHeader(header);

HeaderFooter footer=new HeaderFooter(new Phrase("-",footerFont),new Phrase("-",footerFont));

/**

* 0左 1中 2右

*/

footer.setAlignment(1);

footer.setBorder(Rectangle.NO_BORDER);

doc.setFooter(footer);

doc.open();

//doc.add(new Paragraph("評審意見:",chinese));

//7列

PdfPTable table = new PdfPTable(7);

PdfPCell cell;

table.addCell(new Paragraph("評審項目編號",chinese));

table.addCell(new Paragraph(rvwFormDTO.getRvwItemCode(),content));

cell = new PdfPCell(new Paragraph("評審項目類型",chinese));

cell.setColspan(2);

table.addCell(cell);

String rvwItemParentType = (String) param.get("rvwItemParentType");

String rvwItemType = (String) param.get("rvwItemType");

String rvwItemTwoType = (String) param.get("rvwItemTwoType");

cell = new PdfPCell(new Paragraph(rvwItemParentType+"/"+rvwItemType+"/"+rvwItemTwoType,content));

cell.setColspan(3);

table.addCell(cell);

table.addCell(new Paragraph("申請人姓名",chinese));

table.addCell(new Paragraph(rvwFormDTO.getApplicantName(),content));

cell = new PdfPCell(new Paragraph("申請人所在部門",chinese));

cell.setColspan(2);

table.addCell(cell);

cell = new PdfPCell(new Paragraph(rvwFormDTO.getAplcntDeptName(),content));

cell.setColspan(3);

table.addCell(cell);

table.addCell(new Paragraph("錄入人姓名",chinese));

table.addCell(new Paragraph(rvwFormDTO.getRecordName(),content));

cell = new PdfPCell(new Paragraph("項目涉及金額",chinese));

cell.setColspan(2);

table.addCell(cell);

table.addCell(new Paragraph(String.valueOf(rvwFormDTO.getInvolveAmount()==null?0:rvwFormDTO.getInvolveAmount()),content));

table.addCell(new Paragraph("幣種",chinese));

String involveAmountType = (String) param.get("involveAmountType");

table.addCell(new Paragraph(involveAmountType,content));

table.addCell(new Paragraph("專業公司",chinese));

cell = new PdfPCell(new Paragraph(legalEntityDeptDesc+"->"+legalEntitySonDeptDesc,content));

cell.setColspan(6);

table.addCell(cell);

table.addCell(new Paragraph("項目名稱",chinese));

cell = new PdfPCell(new Paragraph(rvwFormDTO.getItemName(),content));

cell.setColspan(6);

table.addCell(cell);

table.addCell(new Paragraph("項目概述",chinese));

cell = new PdfPCell(new Paragraph(rvwFormDTO.getItemOverview(),content));

cell.setColspan(6);

table.addCell(cell);

table.addCell(new Paragraph("評審需求",chinese));

cell = new PdfPCell(new Paragraph(rvwFormDTO.getRvwDemand(),content));

cell.setColspan(6);

table.addCell(cell);

table.addCell(new Paragraph("申請人自我評估",chinese));

cell = new PdfPCell(new Paragraph(rvwFormDTO.getApplicantSelfAssmnt(),content));

cell.setColspan(6);

table.addCell(cell);

/* table.addCell(new Paragraph("同步抄送",chinese));

cell = new PdfPCell(new Paragraph(rvwFormDTO.getSyncsenderNames(),content));

cell.setColspan(6);

table.addCell(cell);*/

int infoNum = 0;

if(fileList.size() > 0){

//附件信息

cell = new PdfPCell(new Paragraph("附件信息",chinese));

cell.setUseAscender(true);

cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中

cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中

cell.setRowspan(fileList.size()+1);

table.addCell(cell);

//序號

cell = new PdfPCell(new Paragraph("序號",chinese));

cell.setUseAscender(true);

cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中

cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中

table.addCell(cell);

//附件名稱

cell = new PdfPCell(new Paragraph("附件名稱",chinese));

cell.setUseAscender(true);

cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中

cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中

table.addCell(cell);

//上傳時間

cell = new PdfPCell(new Paragraph("上傳時間",chinese));

cell.setUseAscender(true);

cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中

cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中

table.addCell(cell);

//上傳人

cell = new PdfPCell(new Paragraph("上傳人",chinese));

cell.setUseAscender(true);

cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中

cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中

table.addCell(cell);

//附件類型

cell = new PdfPCell(new Paragraph("附件類型",chinese));

cell.setUseAscender(true);

cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中

cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中

table.addCell(cell);

//法律合規評審

cell = new PdfPCell(new Paragraph("法律合規評審",chinese));

cell.setUseAscender(true);

cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中

cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中

table.addCell(cell);

for (FileInfoDTO file : fileList) {

infoNum++;

//序號

cell = new PdfPCell(new Paragraph(infoNum+"",content));

cell.setUseAscender(true);

cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中

cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中

table.addCell(cell);

//附件名稱

cell = new PdfPCell(new Paragraph(file.getFileName(),content));

cell.setUseAscender(true);

cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中

cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中

table.addCell(cell);

//上傳時間

cell = new PdfPCell(new Paragraph(file.getUploadTimeFormat(),content));

cell.setUseAscender(true);

cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中

cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中

table.addCell(cell);

//上傳人

cell = new PdfPCell(new Paragraph(file.getUploadName(),content));

cell.setUseAscender(true);

cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中

cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中

table.addCell(cell);

//附件類型

String fileType;

if("1".equals(file.getFileType())){

fileType = "合同文件";

}else if("99".equals(file.getFileType())){

fileType = "支持文檔";

}else{

fileType = "";

}

cell = new PdfPCell(new Paragraph(fileType,content));

cell.setUseAscender(true);

cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中

cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中

table.addCell(cell);

//法律合規評審

String typeRvwStatus;

if("1".equals(file.getTypeRvwStatus())){

typeRvwStatus = "經審查附件無重大法律合規問題";

}else if("2".equals(file.getTypeRvwStatus())){

typeRvwStatus = "退回修改";

}else{

typeRvwStatus = "";

}

cell = new PdfPCell(new Paragraph(typeRvwStatus,content));

cell.setUseAscender(true);

cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中

cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中

table.addCell(cell);

}

}else{

//附件信息

cell = new PdfPCell(new Paragraph("附件信息",chinese));

table.addCell(cell);

cell = new PdfPCell(new Paragraph("沒有附件",content));

cell.setColspan(6);

table.addCell(cell);

}

cell = new PdfPCell(new Paragraph("評審意見",chinese));

cell.setRowspan(mainRvwInfos.size()+branchRvwInfos.size());

//居中

cell.setUseAscender(true);

cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中

cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中

table.addCell(cell);

if(mainRvwInfos.size()>0){

cell = new PdfPCell(new Paragraph("主評審意見",chinese));

cell.setRowspan(mainRvwInfos.size());

//居中

cell.setUseAscender(true);

cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中

cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中

table.addCell(cell);

infoNum = 0;

for (CmplncMainRvwInfoDTO dto : mainRvwInfos) {

infoNum++;

//序號

cell = new PdfPCell(new Paragraph(infoNum+"",content));

cell.setUseAscender(true);

cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中

cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中

table.addCell(cell);

//評審意見

PdfPTable branchRvwInfosTable = new PdfPTable(1);

cell = new PdfPCell(new Paragraph(delHTMLTag(dto.getRvwOpinion()),content));

cell.disableBorderSide(2);

branchRvwInfosTable.addCell(cell);

//評審人和評審時間

cell = new PdfPCell(new Paragraph(dto.getRvwUmName()+"/"+getStringDate(dto.getRvwTime()),content));

cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

cell.disableBorderSide(1);

cell.setPaddingTop(5);

branchRvwInfosTable.addCell(cell);

PdfPCell branchRvwInfosCell = new PdfPCell(branchRvwInfosTable);

branchRvwInfosCell.setColspan(4);

table.addCell(branchRvwInfosCell);

}

doc.add(table);

}

if(branchRvwInfos.size()>0){

cell = new PdfPCell(new Paragraph("支評審意見",chinese));

cell.setRowspan(branchRvwInfos.size());

//居中

cell.setUseAscender(true);

cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中

cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中

table.addCell(cell);

infoNum = 0;

for (CmplncBranchRvwInfoDTO dto : branchRvwInfos) {

infoNum++;

//序號

cell = new PdfPCell(new Paragraph(infoNum+"",content));

cell.setUseAscender(true);

cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中

cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中

table.addCell(cell);

//評審意見

PdfPTable branchRvwInfosTable = new PdfPTable(1);

cell = new PdfPCell(new Paragraph(delHTMLTag(dto.getRvwOpinion()),content));

cell.disableBorderSide(2);

branchRvwInfosTable.addCell(cell);

//評審人和評審時間

cell = new PdfPCell(new Paragraph(dto.getRvwUmName()+"/"+getStringDate(dto.getRvwTime()),content));

cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

cell.disableBorderSide(1);//隱藏上邊框

cell.setPaddingTop(5);

branchRvwInfosTable.addCell(cell);

PdfPCell branchRvwInfosCell = new PdfPCell(branchRvwInfosTable);

branchRvwInfosCell.setColspan(4);

table.addCell(branchRvwInfosCell);

}

doc.add(table);

}

if(doc != null){

doc.close();

}

result =baos.toByteArray();

} catch (DocumentException e) {

e.printStackTrace();

}finally{

if(baos != null){

try {

baos.close();

} catch (IOException e) {

log.error("PDF異常", e);

}

}

}

return result;

}

工具

/**

* 去掉HTML標簽

* @param htmlStr

* @return

*/

public static String delHTMLTag(String htmlStr){

if (htmlStr!=null){

String regEx_script="<script[^>]*?>[\s\S]*?<\/script>"; //定義script的正則表達式

String regEx_style="<style[^>]*?>[\s\S]*?<\/style>"; //定義style的正則表達式

String regEx_html="<[^>]+>"; //定義HTML標簽的正則表達式

Pattern p_script=Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE);

Matcher m_script=p_script.matcher(htmlStr);

htmlStr=m_script.replaceAll(""); //過濾script標簽

Pattern p_style=Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE);

Matcher m_style=p_style.matcher(htmlStr);

htmlStr=m_style.replaceAll(""); //過濾style標簽

Pattern p_html=Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE);

Matcher m_html=p_html.matcher(htmlStr);

htmlStr=m_html.replaceAll(""); //過濾html標簽

Pattern p_enter = Pattern.compile("\s*| | | ");

Matcher m_enter = p_enter.matcher(htmlStr);

htmlStr = m_enter.replaceAll("");

}

return htmlStr.trim().replaceAll("&nbsp;", ""); //返迴文本字元串

}

/**

* @return返回字元串格式 yyyy-MM-dd HH:mm:ss

*/

public static String getStringDate(Date date) {

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String dateString = formatter.format(date);

return dateString;

}

❻ java怎麼把HTML界面做成pdf格式列印

public boolean convertHtmlToPdf(String inputFile, String outputFile)
throws Exception {

OutputStream os = new FileOutputStream(outputFile);
ITextRenderer renderer = new ITextRenderer();
String url = new File(inputFile).toURI().toURL().toString();

renderer.setDocument(url);

// 解決中文支持問題
ITextFontResolver fontResolver = renderer.getFontResolver();
fontResolver.addFont("C:/Windows/Fonts/SIMSUN.TTC", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//解決圖片的相對路徑問題
renderer.getSharedContext().setBaseURL("file:/D:/");
renderer.layout();
renderer.createPDF(os);

os.flush();
os.close();
return true;
}

上面這段代碼是這樣的,輸入一個HTML地址URL = inputFile,輸入一個要輸出的地址,就可以在輸出的PDF地址中生成這個PDF。

❼ java怎麼輸出pdf格式的文件

java導出pdf需要用到iText庫,iText是著名的開放源碼的站點sourceforge一個項目,是用於生成PDF文檔的一個java類庫。通過iText不僅可以生成PDF或rtf
的文檔,而且可以將XML、Html文件轉化為PDF文件。
iText的安裝非常方便,下載iText.jar文件後,只需要在系統的CLASSPATH中加入iText.jar的路徑,在程序中就可以使用
iText類庫了。
代碼如下:

public class createPdf {
//自己做的一個簡單例子,中間有圖片之類的
//先建立Document對象:相對應的 這個版本的jar引入的是com.lowagie.text.Document
Document document = new Document(PageSize.A4, 36.0F, 36.0F, 36.0F, 36.0F);
public void getPDFdemo() throws DocumentException, IOException{
//這個導出用的是 iTextAsian.jar 和iText-2.1.3.jar 屬於比較老的方法。 具體下在地址見:
//首先
//字體的定義:這里用的是自帶的jar裡面的字體
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
// 當然你也可以用你電腦裡面帶的字體庫
//BaseFont bfChinese = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1",BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
//定義字體 注意在最新的包裡面 顏色是封裝的
Font fontChinese8 = new Font(bfChinese, 10.0F, 0, new Color(59, 54, 54));
//生成pdf的第一個步驟:
//保存本地指定路徑
saveLocal();
document.open();
ByteArrayOutputStream ba = new ByteArrayOutputStream();
// PdfWriter writer = PdfWriter.getInstance(document, ba);
document.open();
//獲取此編譯的文件路徑
String path = this.getClass().getClassLoader().getResource("").getPath();
//獲取根路徑
String filePath = path.substring(1, path.length()-15);
//獲取圖片路徑 找到你需要往pdf上生成的圖片
//這里根據自己的獲取的路徑寫 只要找到圖片位置就可以
String picPath = filePath +"\\WebContent" +"\\images\\";
//往PDF中添加段落
Paragraph pHeader = new Paragraph();
pHeader.add(new Paragraph(" 你要生成文字寫這里", new Font(bfChinese, 8.0F, 1)));
//pHeader.add(new Paragraph("文字", 字體 可以自己寫 也可以用fontChinese8 之前定義好的 );
document.add(pHeader);//在文檔中加入你寫的內容
//獲取圖片
Image img2 = Image.getInstance(picPath +"ccf-stamp-new.png");
//定義圖片在文檔中顯示的絕對位置
img2.scaleAbsolute(137.0F, 140.0F);
img2.setAbsolutePosition(330.0F, 37.0F);
//將圖片添加到文檔中
document.add(img2);
//關閉文檔
document.close();
/*//設置文檔保存的文件名
response.setHeader("Content-
disposition", "attachment;filename=\""+ new String(("CCF會員資格確認
函.pdf").getBytes("GBK"),"ISO-8859-1") + "\"");
//設置類型
response.setContentType("application/pdf");
response.setContentLength(ba.size());
ServletOutputStream out = response.getOutputStream();
ba.writeTo(out);
out.flush();*/
}
public static void main(String[]args) throws DocumentException, IOException{
createPdf pdf= new createPdf();
pdf.getPDFdemo();
}

//指定一個文件進行保存 這里吧文件保存到D盤的text.pdf
public void saveLocal() throws IOException, DocumentException{
//直接生成PDF 制定生成到D盤test.pdf
File file = new File("D:\\text2.pdf");
file.createNewFile();
PdfWriter.getInstance(document, new FileOutputStream(file));

}
}

閱讀全文

與java生成pdf並列印相關的資料

熱點內容
linux命令行解析度 瀏覽:345
程序員不晉升能幹到多少歲 瀏覽:376
谷歌推廣用什麼伺服器 瀏覽:626
和平精英安卓怎麼登蘋果系統 瀏覽:144
除法的心演算法 瀏覽:301
音樂源碼下載 瀏覽:716
編程拖放 瀏覽:41
linux卸載tomcat 瀏覽:875
手機時間如何校正到伺服器 瀏覽:81
創造與魔法瞬移源碼百度 瀏覽:883
反射優化java 瀏覽:876
硬體加密播放盒子 瀏覽:923
xp點擊文件夾選項沒反應 瀏覽:537
蘋果不顯示桌面的app怎麼刪除 瀏覽:864
安卓手機怎麼換國際服 瀏覽:415
神獸領域安卓怎麼下載 瀏覽:250
單片機交通燈ad原理圖 瀏覽:413
多功能解壓磁鐵筆 瀏覽:80
少兒編程火箭升空 瀏覽:401
蘭斯10游戲解壓碼 瀏覽:42