java文檔生成
❶ java生成word文檔的問題
Jacob解決Word文檔的讀寫問題收藏
Jacob 是Java-COM Bridge的縮寫,它在Java與微軟的COM組件之間構建一座橋梁。使用Jacob自帶的DLL動態鏈接庫,並通過JNI的方式實現了在Java平台上對COM程序的調用。Jacob下載的地址為:
http://sourceforge.net/project/showfiles.php?group_id=109543&package_id=118368
配置:
(1)將解壓包中的jacob.dll(x86常用,x64)拷到jdk安裝目錄下的jre\bin文件夾或windows安裝路徑下的WINDOWS\system32文件夾下
(2)將jacob.jar文件拷到classpath下即可
常見問題解決:
對於」java.lang.UnsatisfiedLinkError: C:\WINDOWS\system32\jacob-1.14.3-x86.dll: 由於應用程序配置不正確,應用程序未能啟動。重新安裝應用程序可能會糾正」這個問題,可以通過
重新下載Jacob的jar及dll文件(最好版本比現在的低,如1.11)解決
實例製作(主要功能:標題製作,表格製作,合並表格,替換文本,頁眉頁腳,書簽處理):
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class WordOperate {
public static void main(String args[]) {
ActiveXComponent wordApp = new ActiveXComponent("Word.Application"); // 啟動word
// Set the visible property as required.
Dispatch.put(wordApp, "Visible", new Variant(true));// //設置word可見
Dispatch docs = wordApp.getProperty("Documents").toDispatch();
// String inFile = "d:\\test.doc";
// Dispatch doc = Dispatch.invoke(docs, "Open", Dispatch.Method,
// new Object[] { inFile, new Variant(false), new Variant(false)},//參數3,false:可寫,true:只讀
// new int[1]).toDispatch();//打開文檔
Dispatch document = Dispatch.call(docs, "Add").toDispatch();// create new document
String userName = wordApp.getPropertyAsString("Username");// 顯示用戶信息
System.out.println("用戶名:" + userName);
// 文檔對齊,字體設置////////////////////////
Dispatch selection = Dispatch.get(wordApp, "Selection").toDispatch();
Dispatch align = Dispatch.get(selection, "ParagraphFormat")
.toDispatch(); // 行列格式化需要的對象
Dispatch font = Dispatch.get(selection, "Font").toDispatch(); // 字型格式化需要的對象
// 標題處理////////////////////////
Dispatch.put(align, "Alignment", "1"); // 1:置中 2:靠右 3:靠左
Dispatch.put(font, "Bold", "1"); // 字型租體
Dispatch.put(font, "Color", "1,0,0,0"); // 字型顏色紅色
Dispatch.call(selection, "TypeText", "Word文檔處理"); // 寫入標題內容
Dispatch.call(selection, "TypeParagraph"); // 空一行段落
Dispatch.put(align, "Alignment", "3"); // 1:置中 2:靠右 3:靠左
Dispatch.put(selection, "Text", " ");
Dispatch.call(selection, "MoveDown"); // 游標標往下一行
//表格處理////////////////////////
Dispatch tables = Dispatch.get(document, "Tables").toDispatch();
Dispatch range = Dispatch.get(selection, "Range").toDispatch();
Dispatch table1 = Dispatch.call(tables, "Add", range, new Variant(3),
new Variant(2), new Variant(1)).toDispatch(); // 設置行數,列數,表格外框寬度
// 所有表格
Variant tableAmount = Dispatch.get(tables, "count");
System.out.println(tableAmount);
// 要填充的表格
Dispatch t1 = Dispatch.call(tables, "Item", new Variant(1))
.toDispatch();
Dispatch t1_row = Dispatch.get(t1, "rows").toDispatch();// 所有行
int t1_rowNum = Dispatch.get(t1_row, "count").getInt();
Dispatch.call(Dispatch.get(t1, "columns").toDispatch(), "AutoFit");// 自動調整
int t1_colNum = Dispatch.get(Dispatch.get(t1, "columns").toDispatch(),
"count").getInt();
System.out.println(t1_rowNum + " " + t1_colNum);
for (int i = 1; i <= t1_rowNum; i++) {
for (int j = 1; j <= t1_colNum; j++) {
Dispatch cell = Dispatch.call(t1, "Cell", new Variant(i),
new Variant(j)).toDispatch();// 行,列
Dispatch.call(cell, "Select");
Dispatch.put(selection, "Text", "cell" + i + j); // 寫入word的內容
Dispatch.put(font, "Bold", "0"); // 字型租體(1:租體 0:取消租體)
Dispatch.put(font, "Color", "1,1,1,0"); // 字型顏色
Dispatch.put(font, "Italic", "1"); // 斜體 1:斜體 0:取消斜體
Dispatch.put(font, "Underline", "1"); // 下劃線
Dispatch Range = Dispatch.get(cell, "Range").toDispatch();
String cellContent = Dispatch.get(Range, "Text").toString();
System.out.println((cellContent.substring(0, cellContent
.length() - 1)).trim());
}
Dispatch.call(selection, "MoveDown"); // 游標往下一行(才不會輸入蓋過上一輸入位置)
}
//合並單元格////////////////////////
Dispatch.put(selection, "Text", " ");
Dispatch.call(selection, "MoveDown"); // 游標標往下一行
Dispatch range2 = Dispatch.get(selection, "Range").toDispatch();
Dispatch table2 = Dispatch.call(tables, "Add", range2, new Variant(8),
new Variant(4), new Variant(1)).toDispatch(); // 設置行數,列數,表格外框寬度
Dispatch t2 = Dispatch.call(tables, "Item", new Variant(2))
.toDispatch();
Dispatch beginCell = Dispatch.call(t2, "Cell", new Variant(1),
new Variant(1)).toDispatch();
Dispatch endCell = Dispatch.call(t2, "Cell", new Variant(4),
new Variant(4)).toDispatch();
Dispatch.call(beginCell, "Merge", endCell);
for (int row = 1; row <= Dispatch.get(
Dispatch.get(t2, "rows").toDispatch(), "count").getInt(); row++) {
for (int col = 1; col <= Dispatch.get(
Dispatch.get(t2, "columns").toDispatch(), "count").getInt(); col++) {
if (row == 1) {
Dispatch cell = Dispatch.call(t2, "Cell", new Variant(1),
new Variant(1)).toDispatch();// 行,列
Dispatch.call(cell, "Select");
Dispatch.put(font, "Color", "1,1,1,0"); // 字型顏色
Dispatch.put(selection, "Text", "merge Cell!");
} else {
Dispatch cell = Dispatch.call(t2, "Cell", new Variant(row),
new Variant(col)).toDispatch();// 行,列
Dispatch.call(cell, "Select");
Dispatch.put(font, "Color", "1,1,1,0"); // 字型顏色
Dispatch.put(selection, "Text", "cell" + row + col);
}
}
Dispatch.call(selection, "MoveDown");
}
//Dispatch.call(selection, "MoveRight", new Variant(1), new Variant(1));// 取消選擇
// Object content = Dispatch.get(doc,"Content").toDispatch();
// Word文檔內容查找及替換////////////////////////
Dispatch.call(selection, "TypeParagraph"); // 空一行段落
Dispatch.put(align, "Alignment", "3"); // 1:置中 2:靠右 3:靠左
Dispatch.put(font, "Color", 0);
Dispatch.put(selection, "Text", "歡迎,Hello,world!");
Dispatch.call(selection, "HomeKey", new Variant(6));// 移到開頭
Dispatch find = Dispatch.call(selection, "Find").toDispatch();// 獲得Find組件
Dispatch.put(find, "Text", "hello"); // 查找字元串"hello"
Dispatch.put(find, "Forward", "True");// 向前查找
// Dispatch.put(find, "Format", "True");// 設置格式
Dispatch.put(find, "MatchCase", "false");// 大小寫匹配
Dispatch.put(find, "MatchWholeWord", "True"); // 全字匹配
Dispatch.call(find, "Execute"); // 執行查詢
Dispatch.put(selection, "Text", "你好");// 替換為"你好"
//使用方法傳入的參數parameter調用word文檔中的MyWordMacro宏//
//Dispatch.call(document,macroName,parameter);
//Dispatch.invoke(document,macroName,Dispatch.Method,parameter,new int[1]);
//頁眉,頁腳處理////////////////////////
Dispatch ActiveWindow = wordApp.getProperty("ActiveWindow")
.toDispatch();
Dispatch ActivePane = Dispatch.get(ActiveWindow, "ActivePane")
.toDispatch();
Dispatch View = Dispatch.get(ActivePane, "View").toDispatch();
Dispatch.put(View, "SeekView", "9"); //9是設置頁眉
Dispatch.put(align, "Alignment", "1"); // 置中
Dispatch.put(selection, "Text", "這里是頁眉"); // 初始化時間
Dispatch.put(View, "SeekView", "10"); // 10是設置頁腳
Dispatch.put(align, "Alignment", "2"); // 靠右
Dispatch.put(selection, "Text", "這里是頁腳"); // 初始化從1開始
//書簽處理(打開文檔時處理)////////////////////////
//Dispatch activeDocument = wordApp.getProperty("ActiveDocument").toDispatch();
Dispatch bookMarks = Dispatch.call(document, "Bookmarks").toDispatch();
boolean isExist = Dispatch.call(bookMarks, "Exists", "bookMark1")
.getBoolean();
if (isExist == true) {
Dispatch rangeItem1 = Dispatch.call(bookMarks, "Item", "bookMark1")
.toDispatch();
Dispatch range1 = Dispatch.call(rangeItem1, "Range").toDispatch();
Dispatch.put(range1, "Text", new Variant("當前是書簽1的文本信息!"));
String bookMark1Value = Dispatch.get(range1, "Text").toString();
System.out.println(bookMark1Value);
} else {
System.out.println("當前書簽不存在,重新建立!");
Dispatch.call(bookMarks, "Add", "bookMark1", selection);
Dispatch rangeItem1 = Dispatch.call(bookMarks, "Item", "bookMark1")
.toDispatch();
Dispatch range1 = Dispatch.call(rangeItem1, "Range").toDispatch();
Dispatch.put(range1, "Text", new Variant("當前是書簽1的文本信息!"));
String bookMark1Value = Dispatch.get(range1, "Text").toString();
System.out.println(bookMark1Value);
}
//保存操作////////////////////////
Dispatch.call(document, "SaveAs", "D:/wordOperate.doc");
//Dispatch.invoke((Dispatch) doc, "SaveAs", Dispatch.Method, new Object[]{htmlPath, new Variant(8)}, new int[1]); //生成html文件
// 0 = wdDoNotSaveChanges
// -1 = wdSaveChanges
// -2 = wdPromptToSaveChanges
//Dispatch.call(document, "Close", new Variant(0));
// // worddoc.olefunction("protect",2,true,"");
// // Dispatch bookMarks = wordApp.call(docs,"Bookmarks").toDispatch();
// // System.out.println("bookmarks"+bookMarks.getProgramId());
// //Dispatch.call(doc, "Save"); //保存
// // Dispatch.call(doc, "Close", new Variant(true));
// //wordApp.invoke("Quit",new Variant[]{});
// wordApp.safeRelease();//Finalizers call this method
}
}
❷ 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如何根據word模板生成word文檔
首先是action的createDoc方法:
[java]
/**
* 通過HttpCient調用報告伺服器的方法生成報告 DOC
*/
public String createDoc() throws Exception {
//定義放回成功與否的判斷碼
String prMsg="";
// 獲取當前登錄的用戶
UserVo userVo = CommonUtils.getUserMessage();
//獲取模版類型
docType = Struts2Utils.getParameter("docType");
//重新創建文檔
String creatOrnot = Struts2Utils.getParameter("creatOrnot");
//獲取組組編號參數
workgroupId = Struts2Utils.getParameter("workgroupId");
//獲取評估用例實例ID參數
evtcaseInstId = Struts2Utils.getParameter("evtcaseInstId");
if(CommonUtils.isNotNull(docType)){
//獲取項目Id
projectId = Struts2Utils.getParameter("projectId");
if(!CommonUtils.isNotNull(projectId)){
if(CommonUtils.isNotNull(this.getIdFromSession("PM_PROJECTID"))){
projectId = this.getIdFromSession("PM_PROJECTID").toString();
}else{
Struts2Utils.getRequest().setAttribute("msg", "請先選擇項目!");
}
}
if(CommonUtils.isNotNull(projectId)){
prMsg = infoSystemDescService.downloadFileByUrl(projectId, userVo.getUserId(), workgroupId, evtcaseInstId, docType, creatOrnot);
}
}
return "docList";
}
註:在我貼出來的代碼中,能看懂就行了,有些不用管他(可能是其他業務方面的判斷),關於最後返回的prMsg---代表各種狀態 主要表示成功與否或者是出錯的信息。
接著我貼出service層的方法downloadFileByUrl
[java]
</pre><p></p><p></p><pre name="code" class="java"><pre name="code" class="java">/**
* 功能:
* 1.(生成報告文檔)
* 2.保存指定URL的源文件到指定路徑下
* @param projectId
* @param userId
* @param workgroupId
* @param evtcaseInstId
* @param docType
* @param creatOrnot
* @return
* @throws Exception
*/
@SuppressWarnings("deprecation")
public synchronized String downloadFileByUrl(String projectId,String userId,String workgroupId,String evtcaseInstId,String docType,String creatOrnot) throws Exception {
String msg = "1";//"1":默認為創建成功的提示信息 "2":標識創建失敗
String srcUrl = ""; //報告伺服器的執行路徑
HttpResponse response = null;
FileOutputStream out = null;
HttpClient httpclient = null;
HttpGet httpget = null;
long time1 = System.currentTimeMillis();
//獲取保存後的路徑
TProjDoc projDoc = projectDocDao.findFileByType(userId, Integer.parseInt(docType), Long.parseLong(projectId), workgroupId,evtcaseInstId);
if(projDoc == null || (projDoc != null && CommonUtils.isNotNull(creatOrnot) && creatOrnot.equals("1"))){ //FT_任務編號_[FID]
try {
//獲取報告伺服器的執行路徑
srcUrl = xmlPathDef.getActionUrl(docType, projectId,userId,workgroupId,evtcaseInstId);
HttpParams httpParams = new BasicHttpParams();
// 設置最大連接數
ConnManagerParams.setMaxTotalConnections(httpParams, 1);
// 設置獲取連接的最大等待時間
//ConnManagerParams.setTimeout(httpParams, 6000);
// 設置每個路由最大連接數
ConnPerRouteBean connPerRoute = new ConnPerRouteBean(1);
ConnManagerParams.setMaxConnectionsPerRoute(httpParams,connPerRoute);
// 設置連接超時時間
HttpConnectionParams.setConnectionTimeout(httpParams, 6000);
// 設置讀取超時時間
if(docType.toString().equals(XmlPathDef.SPOTTEST_DOC) && docType.toString().equals(XmlPathDef.FTEST_DOC)){
HttpConnectionParams.setSoTimeout(httpParams, 2400000);
}else{
HttpConnectionParams.setSoTimeout(httpParams, 600000);
}
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(httpParams, registry);
httpclient = new DefaultHttpClient(connectionManager, httpParams);
httpget = new HttpGet(srcUrl);
//執行返回
response = httpclient.execute(httpget);
//如果是本機既當伺服器,又當報表伺服器,那麼就只生成一遍
String ipvalues = xmlPathDef.getRepUrl();
if(CommonUtils.isNotNull(ipvalues)){
if(ipvalues.indexOf(":") != -1){
ipvalues = ipvalues.substring(0,ipvalues.lastIndexOf(":"));
}
}
HttpEntity entity = response.getEntity();
//獲取保存後的路徑
projDoc = projectDocDao.findFileByType(userId,Integer.parseInt(docType), Long.parseLong(projectId), workgroupId,evtcaseInstId);
String filePath = "";
if(projDoc != null)
filePath = projDoc.getPath();
if(CommonUtils.isNotNull(filePath)){
String basepath = XmlPathDef.getBasePath();
String outFilePath = (basepath + filePath).replaceAll("\\\\", "\\/");
XmlPathDef.isExists(outFilePath);
File wdFile = new File(outFilePath);
out = new FileOutputStream(wdFile);
int l;
byte[] tmp = new byte[2048];
while ((l = instream.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.flush();
out.close();
System.out.println("****************************** ");
System.out.println("");
System.out.println("*************** 恭喜! 報告創建成功 結束 ***************");
System.out.println("");
}else{
msg = "8";//說明word創建成功,但是數據沒有保存成功
response = null;
}
}else{
msg = "2";
}
} catch (ClientProtocolException e) {
msg = "7";
e.printStackTrace();
} catch (IOException e) {
msg = "7";
logger.error("資料庫報告伺服器地址配置錯誤或網路不通!!2.連接是否超時" + e.getMessage());
e.printStackTrace();
}finally{
if(out!=null){
try {
out.close();
} catch (IOException e) {
msg = "7";
logger.error("資料庫報告伺服器地址配置錯誤或網路不通!!2.連接是否超時" + e.getMessage());
e.printStackTrace();
}
}
}
}
long time2 = System.currentTimeMillis();
long numTime = time2 - time1;
if(docType.toString().equals(XmlPathDef.SPOTTEST_DOC) && docType.toString().equals(XmlPathDef.FTEST_DOC)){
if(numTime >= 2401000){
msg = "9";
}
}else{
if(numTime >= 601000){
msg = "9";
}
}
System.out.println("");
String loggerinfo = "********* 報告類型為 :" + docType + " 執行時間為: " + (time2 - time1) /1000 + " 秒!***************";
System.out.println(loggerinfo);
System.out.println("");
System.out.println("*****************************");
logger.info(loggerinfo);
return msg;
}
❹ 如何用java生成一個xml文件
一個XML文檔,可以先構造一個DOM,然後將DOM轉化為xml序列,輸出或者生成文件。package test;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Test {
public static void generate(){
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
document.setXmlVersion("1.0");
document.setXmlStandalone(true);
Element root = document.createElement_x("MobileNet"); //創建根節點
document.appendChild(root); //將根節點添加到Document對象中
Element pageElement = document.createElement_x("page"); //設置第一個page元素到
pageElement.setAttribute("name", "list.jsp"); //設置page節點的name屬性
Element methodElement = document.createElement_x("method"); //設置method節點
methodElement.setTextContent("get"); //給method設置值
pageElement.appendChild(methodElement); //添加method節點到page節點內
Element displayElement = document.createElement_x("display"); //設置method節點
displayElement.setTextContent("list撒旦發放"); //給display設置值
pageElement.appendChild(displayElement); //添加display節點到page節點內
Element request_paramElement = document.createElement_x("request_param");
request_paramElement.setTextContent("request_param1|request_param2");
pageElement.appendChild(request_paramElement);
root.appendChild(pageElement);
pageElement = document.createElement_x("page"); //設置第二個page元素到
pageElement.setAttribute("name", "content.jsp"); //設置page節點的name屬性
methodElement = document.createElement_x("method");
methodElement.setTextContent("post");
pageElement.appendChild(methodElement);
displayElement = document.createElement_x("display");
displayElement.setTextContent("content");
pageElement.appendChild(displayElement);
Element url_titleElement = document.createElement_x("url_title"); //設置url_title節點
url_titleElement.setTextContent("title,publisher,published_calendar"); //給url_title設置值
pageElement.appendChild(url_titleElement); //添加url_title節點到page節點內
root.appendChild(pageElement); //將page段加人根節點內
TransformerFactory transFactory = TransformerFactory.newInstance(); //開始把Document映射到文件
Transformer transFormer = transFactory.newTransformer();
DOMSource domSource = new DOMSource(document); //設置輸出結果
File file = new File("MobileNetRule.xml"); //生成xml文件
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream out = new FileOutputStream(file); //文件輸出流
StreamResult xmlResult = new StreamResult(out); //設置輸入源
transFormer.transform(domSource, xmlResult); //輸出xml文件
System.out.println(file.getAbsolutePath()); //測試文件輸出的路徑
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
t.setOutputProperty("{/encoding/}","GB2312/");
ByteArrayOutputStream boc = new ByteArrayOutputStream();
t.transform(new DOMSource(document), new StreamResult(boc));
String xmlstring = boc.toString();
System.out.println(xmlstring);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args){
Test.generate();
}
}
❺ 如何用java生成word
jacob,相關資料你可以去查找看看
❻ eclipse怎樣生成javadoc
使用eclipse生成文檔(javadoc)主要有三種方法:
1,在項目列表中按右鍵,選擇Export(導出),然後在Export(導出)對話框中選擇java下的javadoc,提交到下一步。
在Javadoc Generation對話框中有兩個地方要注意的:
javadoc command:應該選擇jdk的bin/javadoc.exe
destination:為生成文檔的保存路徑,可自由選擇。
按finish(完成)提交即可開始生成文檔。
2,用菜單選擇:File->Export(文件->導出),
剩下的步驟和第一種方法是一樣的。
3,選中要生成文檔的項目,然後用菜單選擇,
Project->Generate Javadoc直接進入Javadoc Generation對話框,剩餘的步驟就和第一種方法在Javadoc Generation對話框開始是一樣的。
❼ java中如何生成word文檔的目錄頁
1.創建帶有格式的word文檔,將該需要動態展示的數據使用變數符替換。 2. 將剛剛創建的word文檔另存為xml格式。3.編輯這個XMl文檔去掉多餘的xml標記,如圖中藍色部分 4.從Freemarker官網【下載】最新的開發包,將freemarker.jar拷貝到自己的開發項目中。 5.新建DocUtil類,實現根據Doc模板生成word文件的方法6.用戶根據自己的需要,調用使用getDataMap獲取需要傳遞的變數,然後調用createDoc方法生成所需要的文檔。
❽ 怎麼用java代碼生成pdf文檔
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.IOException;
importcom.itextpdf.text.*;
importcom.itextpdf.text.pdf.PdfWriter;
publicclassPdfTest
{
publicstaticvoidmain(String[]args)throwsException
{
DocumentpdfDoc=newDocument();
//將要生成的pdf文件的路徑輸出流
FileOutputStreampdfFile=
newFileOutputStream(newFile("F:/study/test/firstPdf.pdf"));
//pdf文件中的一個文欄位落
Paragraphparagraph=newParagraph("MyfirstPDFfilewithanimage...");
Imageimage=Image.getInstance("F:/study/test/洛克李.jpg");
//用Document對象、File對象獲得PdfWriter輸出流對象
PdfWriter.getInstance(pdfDoc,pdfFile);
pdfDoc.open();//打開Document文檔
//添加一個文欄位落、一張圖片
pdfDoc.add(paragraph);
pdfDoc.add(image);
pdfDoc.close();
}
}