導航:首頁 > 文檔加密 > java生成動態pdf

java生成動態pdf

發布時間:2023-09-21 20:18:06

java 圖片流生成pdf

你是想在java生成一個pdf文件?並通過流輸出?iText可以,找下案例,可以繼續追問。

② java中怎麼利用poi和itext生成pdf文檔

生成PDF文檔代碼如下:

packagepoi.itext;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.awt.Color;
importcom.lowagie.text.*;
importcom.lowagie.text.pdf.*;
importcom.lowagie.text.pdf.BaseFont;
/**
*創建Pdf文檔
*@authorAdministrator
*
*/
publicclassHelloPdf
{
publicstaticvoidmain(String[]args)throwsException
{
BaseFontbfChinese=BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
FontFontChinese=newFont(bfChinese,12,Font.NORMAL);
//第一步,創建document對象
RectanglerectPageSize=newRectangle(PageSize.A4);

//下面代碼設置頁面橫置
//rectPageSize=rectPageSize.rotate();

//創建document對象並指定邊距
Documentdoc=newDocument(rectPageSize,50,50,50,50);
Documentdocument=newDocument();
try
{
//第二步,將Document實例和文件輸出流用PdfWriter類綁定在一起
//從而完成向Document寫,即寫入PDF文檔
PdfWriter.getInstance(document,newFileOutputStream("src/poi/itext/HelloWorld.pdf"));
//第3步,打開文檔
document.open();
//第3步,向文檔添加文字.文檔由段組成
document.add(newParagraph("HelloWorld"));
Paragraphpar=newParagraph("世界你好",FontChinese);
document.add(par);
PdfPTabletable=newPdfPTable(3);
for(inti=0;i<12;i++)
{
if(i==0)
{
PdfPCellcell=newPdfPCell();
cell.setColspan(3);
cell.setBackgroundColor(newColor(180,180,180));
cell.addElement(newParagraph("表格頭",FontChinese));
table.addCell(cell);
}
else
{
PdfPCellcell=newPdfPCell();
cell.addElement(newParagraph("表格內容",FontChinese));
table.addCell(cell);
}
}
document.add(table);
}
catch(DocumentExceptionde)
{
System.err.println(de.getMessage());
}
catch(IOExceptionioe)
{
System.err.println(ioe.getMessage());
}
//關閉document
document.close();

System.out.println("生成HelloPdf成功!");
}


}

希望對你有幫助。

③ 如何運用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代碼生成pdf文檔

package com.qhdstar.java.pdf;
import java.awt.Color;
import java.io.FileOutputStream;

import com.lowagie.text.Chapter;
import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Section;
import com.lowagie.text.pdf.PdfWriter;

/**
* 描述:TODO 【JAVA生成PDF】
* <p>
*
* @title GeneratePDF
* @author SYJ
* @email [email protected]
* @date 2013-4-6
* @version V1.0
*/
public class GeneratePDF {

public static void main(String[] args) {

//調用第一個方法,向C盤生成一個名字為ITextTest.pdf 的文件
try {
writeSimplePdf();
}
catch (Exception e) { e.printStackTrace(); }

//調用第二個方法,向C盤名字為ITextTest.pdf的文件,添加章節。
try {
writeCharpter();
}
catch (Exception e) { e.printStackTrace(); }

}

public static void writeSimplePdf() throws Exception {

// 1.新建document對象
// 第一個參數是頁面大小。接下來的參數分別是左、右、上和下頁邊距。
Document document = new Document(PageSize.A4, 50, 50, 50, 50);

// 2.建立一個書寫器(Writer)與document對象關聯,通過書寫器(Writer)可以將文檔寫入到磁碟中。
// 創建 PdfWriter 對象 第一個參數是對文檔對象的引用,第二個參數是文件的實際名稱,在該名稱中還會給出其輸出路徑。
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\ITextTest.pdf"));

// 3.打開文檔
document.open();

// 4.向文檔中添加內容
// 通過 com.lowagie.text.Paragraph 來添加文本。可以用文本及其默認的字體、顏色、大小等等設置來創建一個默認段落
document.add(new Paragraph("First page of the document."));
document.add(new
Paragraph("Some more text on the first page with different color and
font type.", FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, new
Color(255, 150, 200))));

// 5.關閉文檔
document.close();
}

/**
* 添加含有章節的pdf文件
*
* @throws Exception
*/
public static void writeCharpter() throws Exception {

// 新建document對象 第一個參數是頁面大小。接下來的參數分別是左、右、上和下頁邊距。
Document document = new Document(PageSize.A4, 20, 20, 20, 20);

// 建立一個書寫器(Writer)與document對象關聯,通過書寫器(Writer)可以將文檔寫入到磁碟中。
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("c:\\ITextTest.pdf"));

// 打開文件
document.open();

// 標題
document.addTitle("Hello mingri example");

// 作者
document.addAuthor("wolf");

// 主題
document.addSubject("This example explains how to add metadata.");
document.addKeywords("iText, Hello mingri");
document.addCreator("My program using iText");

// document.newPage();
// 向文檔中添加內容
document.add(new Paragraph("\n"));
document.add(new Paragraph("\n"));
document.add(new Paragraph("\n"));
document.add(new Paragraph("\n"));
document.add(new Paragraph("\n"));
document.add(new Paragraph("First page of the document."));
document.add(new Paragraph("First page of the document."));
document.add(new Paragraph("First page of the document."));
document.add(new Paragraph("First page of the document."));
document.add(new
Paragraph("Some more text on the first page with different color and
font type.", FontFactory.getFont(FontFactory.defaultEncoding, 10,
Font.BOLD, new Color(0, 0, 0))));
Paragraph title1 = new
Paragraph("Chapter 1", FontFactory.getFont(FontFactory.HELVETICA, 18,
Font.BOLDITALIC, new Color(0, 0, 255)));

// 新建章節
Chapter chapter1 = new Chapter(title1, 1);
chapter1.setNumberDepth(0);
Paragraph
title11 = new Paragraph("This is Section 1 in Chapter 1",
FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD, new Color(255,
0, 0)));
Section section1 = chapter1.addSection(title11);
Paragraph someSectionText = new Paragraph("This text comes as part of section 1 of chapter 1.");
section1.add(someSectionText);
someSectionText = new Paragraph("Following is a 3 X 2 table.");
section1.add(someSectionText);
document.add(chapter1);

// 關閉文檔
document.close();
}

}

⑤ 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利用現有word文檔生成pdf的問題

1. 需要用的軟體
OpenOffice 下載地址http://www.openoffice.org/
JodConverter 下載地址http://sourceforge.net/projects/jodconverter/files/JODConverter/,也可以直接從附件裡面下載

2.啟動OpenOffice的服務

安裝完openoffice,安裝服務
cd C:\Program Files (x86)\OpenOffice 4\program
執行
soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
查看是否安裝成功,查看埠對應的pid
netstat -ano|findstr "8100"
查看pid對應的服務程序名
tasklist|findstr "pid值"

3.將JodConverter相關的jar包添加到項目中

4. 下面是實現代碼

附件裡面有現成的可以用的項目示例,直接導入eclipse就可以運行

[java] view plain
/**
* 將Office文檔轉換為PDF. 運行該函數需要用到OpenOffice, OpenOffice下載地址為
* http://www.openoffice.org/
*
* <pre>
* 方法示例:
* String sourcePath = "F:\\office\\source.doc";
* String destFile = "F:\\pdf\\dest.pdf";
* Converter.office2PDF(sourcePath, destFile);
* </pre>
*
* @param sourceFile
* 源文件, 絕對路徑. 可以是Office2003-2007全部格式的文檔, Office2010的沒測試. 包括.doc,
* .docx, .xls, .xlsx, .ppt, .pptx等. 示例: F:\\office\\source.doc
* @param destFile
* 目標文件. 絕對路徑. 示例: F:\\pdf\\dest.pdf
* @return 操作成功與否的提示信息. 如果返回 -1, 表示找不到源文件, 或url.properties配置錯誤; 如果返回 0,
* 則表示操作成功; 返回1, 則表示轉換失敗
*/
public static int office2PDF(String sourceFile, String destFile) {
try {
File inputFile = new File(sourceFile);
if (!inputFile.exists()) {
return -1;// 找不到源文件, 則返回-1
}

// 如果目標路徑不存在, 則新建該路徑
File outputFile = new File(destFile);
if (!outputFile.getParentFile().exists()) {
outputFile.getParentFile().mkdirs();
}

// connect to an OpenOffice.org instance running on port 8100
OpenOfficeConnection connection = new SocketOpenOfficeConnection(
"127.0.0.1", 8100);
connection.connect();

// convert
DocumentConverter converter = new OpenOfficeDocumentConverter(
connection);
converter.convert(inputFile, outputFile);

// close the connection
connection.disconnect();

return 0;
} catch (FileNotFoundException e) {
e.printStackTrace();
return -1;
} catch (ConnectException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return 1;
}

⑦ java 將圖片生成pdf 問題

不知道你用什麼方法生成 的,你可以去網路搜索 java IText 用那個生成PDF幾句代碼就行了

網路有現成的例子
大約是。。。他可以直接把圖片,生成PDF
Document doc = new Document(null, 0, 0, 0, 0);

Image image = Image.getInstance(imgPath);
PdfWriter.getInstance(doc, fos);

閱讀全文

與java生成動態pdf相關的資料

熱點內容
男的送快遞,女的在按摩的上班的叫什麼電影 瀏覽:751
海綿寶寶大電影免費中文版 瀏覽:275
愛國戰爭片免費觀看 瀏覽:887
三位數碼管單片機是如何工作的 瀏覽:728
免費看不下載老電影院 瀏覽:511
啄木鳥影業都有哪些作品 瀏覽:824
在電腦上怎麼把pdf保存成圖片 瀏覽:767
末段愛情廣播劇是哪個app可以聽 瀏覽:322
e片免費看 瀏覽:361
成龍教外國小孩功夫電影叫什麼 瀏覽:482
disk命令分區 瀏覽:912
丁巴度愛與激情 瀏覽:264
韓國野戰電影 瀏覽:462
法國chouchou在線觀看 瀏覽:700
linux歷史命令查看 瀏覽:964
堅果安卓11怎麼樣 瀏覽:497
imovie壓縮 瀏覽:453
古裝鬼電影大全 瀏覽:457
韓電影app 瀏覽:888
何炅參加密室逃脫視頻 瀏覽:897