導航:首頁 > 文檔加密 > java寫入pdf

java寫入pdf

發布時間:2022-09-21 17:47:34

java中怎麼將word轉pdf

能安裝第三方軟體的話,可以考慮以使用Spire.Doc for Java:

你可以在Java程序中添加 Spire.Doc.jar 文件作為依賴項。可以從這個鏈接下載 JAR 文件;如果使用Maven,則可以通過在 pom.xml 文件中添加以下代碼導入 JAR 文件。

repositories>
<repository>
<id>com.e-iceblue</id>
<url>https://repo.e-iceblue.cn/repository/maven-public/</url>
</repository></repositories><dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>5.2.3</version>
</dependency></dependencies>

將Word轉換成PDF:

Spire.Doc for Java擁有強大的文件轉換功能,其提供了 Document. saveToFile(String fileName, FileFormat fileFormat) 方法可將 Word 文檔轉為多種格式的目標文件,下面是轉為 PDF 的方法步驟:

Java代碼如下:

import com.spire.doc.*;public class WordToPDF{
public static void main(String[] args) {
//實例化Document類的對象
Document doc = new Document();

//載入Word
doc.loadFromFile("測試.docx");

//保存為PDF格式
doc.saveToFile("WordToPDF.pdf",FileFormat.PDF);
}

}

希望對您有幫助。

❷ java中如何實現向已有的PDF文件插入附件

可以用Spire.Pdf for Java類庫給PDF文檔添加附件,下面的代碼是插入Excel和Word附件給你參考:

import com.spire.pdf.annotations.*;

import com.spire.pdf.attachments.PdfAttachment;

import com.spire.pdf.graphics.*;

import java.awt.*;

import java.awt.geom.Dimension2D;

import java.awt.geom.Rectangle2D;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

public class AttachFiles {
public static void main(String[] args) throws IOException {


//創建PdfDocument對象


PdfDocument doc = new PdfDocument();


//載入PDF文檔


doc.loadFromFile("C:\Users\Administrator\Desktop\sample.pdf");


//添加附件到PDF


PdfAttachment attachment = new PdfAttachment("C:\Users\Administrator\Desktop\使用說明書.docx");


doc.getAttachments().add(attachment);


//繪制標簽

String label = "財務報表.xlsx";


PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial Unicode MS",Font.PLAIN,12),true);


double x = 35;


double y = doc.getPages().get(0).getActualSize().getHeight() - 200;


doc.getPages().get(0).getCanvas().drawString(label, font, PdfBrushes.getOrange(), x, y);

//添加註釋附件到PDF


String filePath = "C:\Users\Administrator\Desktop\財務報表.xlsx";


byte[] data = toByteArray(filePath);


Dimension2D size = font.measureString(label);


Rectangle2D bound = new Rectangle2D.Float((float) (x + size.getWidth() + 2), (float) y, 10, 15);


PdfAttachmentAnnotation annotation = new PdfAttachmentAnnotation(bound, filePath, data);


annotation.setColor(new PdfRGBColor(new Color(0, 128, 128)));


annotation.setFlags(PdfAnnotationFlags.Default);


annotation.setIcon(PdfAttachmentIcon.Graph);


annotation.setText("點擊打開財務報表.xlsx");


doc.getPages().get(0).getAnnotationsWidget().add(annotation);

//保存文檔


doc.saveToFile("Attachments.pdf");
}

//讀取文件到byte數組


public static byte[] toByteArray(String filePath) throws IOException {

File file = new File(filePath);


long fileSize = file.length();


if (fileSize > Integer.MAX_VALUE) {


System.out.println("file too big...");


return null;


}


FileInputStream fi = new FileInputStream(file);


byte[] buffer = new byte[(int) fileSize];


int offset = 0;


int numRead = 0;


while (offset < buffer.length && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {


offset += numRead;


}

if (offset != buffer.length) {


throw new IOException("Could not completely read file "
+ file.getName());


}


fi.close();


return buffer;


}


}

效果:

❸ 如何用java把好多office文件寫入1個pdf文件

你用JAVA想幹嘛?如果你是想把這數個文件放在一起,成一個PDF檔,那麼樓上講的那個軟體就可以做到了,下載安裝後,點擊製作PDF,將想製成PDF檔的文件也可按你想要的順序一個一個拖過去即可。

❹ java將html文件轉成pdf

核心代碼如下
package com.hmkcode;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.html2pdf.HtmlConverter;

public class App {
public static final String HTML = "<h1>Hello</h1>"
+ "<p>This was created using iText</p>"
+ "<a href='hmkcode.com'>hmkcode.com</a>";

public static void main( String[] args ) throws FileNotFoundException, IOException
{
HtmlConverter.convertToPdf(HTML, new FileOutputStream("string-to-pdf.pdf"));

System.out.println( "PDF Created!" );
}
}

❺ java將pdf文件寫入bytes[]

public static void main(String[] args) throws IOException {

//現在我有一個Byte[]
byte[] bs = new byte[]{1,2,3,4,5};

//確定寫出文件的位置
File file = new File("Test.txt");

//建立輸出位元組流
FileOutputStream fos = new FileOutputStream(file);

//用FileOutputStream 的write方法寫入位元組數組
fos.write(bs);
System.out.println("寫入成功");

//為了節省IO流的開銷,需要關閉
fos.close();

}
}

總結:因為你寫入的是位元組,所以會顯示亂碼。位元組流就是這樣的,用於讀取文件和復制任何東西。

❻ java導出的pdf文件是空白是因為什麼

導出的PDF大小是否是0kb?如果是0,那就是沒有把內容寫入到pdf,看下如下導出方法:

importjava.awt.*;

importjava.awt.geom.Point2D;

importjava.awt.geom.Rectangle2D;

importjava.io.*;

importcom.spire.pdf.PdfPageBase;

importcom.spire.pdf.graphics.*;

{

publicstaticvoidmain(String[]args)throwsFileNotFoundException,IOException{

//創建PdfDocument對象

PdfDocumentdoc=newPdfDocument();

//添加一頁

PdfPageBasepage=doc.getPages().add();

//標題文字

Stringtitle="Java基礎語法";

//創建單色畫刷對象

PdfSolidBrushbrush1=newPdfSolidBrush(newPdfRGBColor(Color.BLUE));

PdfSolidBrushbrush2=newPdfSolidBrush(newPdfRGBColor(Color.BLACK));

//創建TrueType字體對象

PdfTrueTypeFontfont1=newPdfTrueTypeFont(newFont("ArialUnicodeMS",Font.PLAIN,14),true);

PdfTrueTypeFontfont2=newPdfTrueTypeFont(newFont("ArialUnicodeMS",Font.PLAIN,10),true);

//創建PdfStringFormat對象

PdfStringFormatformat1=newPdfStringFormat();

format1.setAlignment(PdfTextAlignment.Center);//設置文字居中

//使用drawString方法繪制標題文字

page.getCanvas().drawString(title,font1,brush1,newPoint2D.Float(page.getActualBounds(true).width/2,0),format1);

//從txt文件讀取內容到字元串

Stringbody=readFileToString("C:\Users\Administrator\Desktop\bodyText.txt");

//創建PdfStringFormat對象

PdfStringFormatformat2=newPdfStringFormat();

format2.setParagraphIndent(20);//設置段首縮進

//創建Rectangle2D對象

Rectangle2D.Floatrect=newRectangle2D.Float(0,30,page.getActualBounds(true).width,page.getActualBounds(true).height);

//使用drawString方法在矩形區域繪制主體文字

page.getCanvas().drawString(body,font2,brush2,rect,format2);

//保存到PDF文檔

doc.saveToFile("ouput.pdf");

}

//自定義方法讀取txt文件內容到字元串

(Stringfilepath)throwsFileNotFoundException,IOException{

StringBuildersb=newStringBuilder();

Strings="";

BufferedReaderbr=newBufferedReader(newFileReader(filepath));

while((s=br.readLine())!=null){

sb.append(s+" ");

}

br.close();

Stringstr=sb.toString();

returnstr;

}

}

PDF到處效果如下圖:

❼ Java如何使用Java向PDF頁面中添加文本

試試這個教程,需要依賴免費版的Spire.Pdf.jar包

importjava.awt.*;
importjava.awt.geom.Point2D;
importjava.awt.geom.Rectangle2D;
importjava.io.*;
importcom.spire.pdf.PdfPageBase;
importcom.spire.pdf.graphics.*;

{

publicstaticvoidmain(String[]args)throwsFileNotFoundException,IOException{

//創建PdfDocument對象
PdfDocumentdoc=newPdfDocument();

//添加一頁
PdfPageBasepage=doc.getPages().add();

//標題文字
Stringtitle="標題";

//創建單色畫刷對象
PdfSolidBrushbrush1=newPdfSolidBrush(newPdfRGBColor(Color.BLUE));
PdfSolidBrushbrush2=newPdfSolidBrush(newPdfRGBColor(Color.BLACK));

//創建TrueType字體對象
PdfTrueTypeFontfont1=newPdfTrueTypeFont(newFont("ArialUnicodeMS",Font.PLAIN,14),true);
PdfTrueTypeFontfont2=newPdfTrueTypeFont(newFont("ArialUnicodeMS",Font.PLAIN,10),true);

//創建PdfStringFormat對象
PdfStringFormatformat1=newPdfStringFormat();
format1.setAlignment(PdfTextAlignment.Center);//設置文字居中

//使用drawString方法繪制標題文字
page.getCanvas().drawString(title,font1,brush1,newPoint2D.Float(page.getActualBounds(true).width/2,0),format1);

//從txt文件讀取內容到字元串
Stringbody=readFileToString("C:\Users\Administrator\Desktop\bodyText.txt");

//創建PdfStringFormat對象
PdfStringFormatformat2=newPdfStringFormat();
format2.setParagraphIndent(20);//設置段首縮進

//創建Rectangle2D對象
Rectangle2D.Floatrect=newRectangle2D.Float(0,30,page.getActualBounds(true).width,page.getActualBounds(true).height);

//使用drawString方法在矩形區域繪制主體文字
page.getCanvas().drawString(body,font2,brush2,rect,format2);

//保存到PDF文檔
doc.saveToFile("ouput.pdf");
}

//自定義方法讀取txt文件內容到字元串
(Stringfilepath)throwsFileNotFoundException,IOException{

StringBuildersb=newStringBuilder();
Strings="";
BufferedReaderbr=newBufferedReader(newFileReader(filepath));

while((s=br.readLine())!=null){
sb.append(s+" ");
}
br.close();
Stringstr=sb.toString();
returnstr;
}

}

❽ 怎麼用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文件寫入不進去

通常需要用到用於讀、寫、編輯PDF文件的庫,你可以參考下面採用spire.pdf.jar來創建PDF的步驟及方法:

  1. 首先需要引入jar包。具體的引入方法可以自行網路搜索。

  2. 創建PdfDocument類的對象,並通過PdfDocument.getPages().add()方法添加頁碼。

  3. 定義標題文字。

  4. 創建PdfSolidBrush畫刷、PdfTrueTypeFont字體、PdfStringFormat字元串、Rectangle2D等對象,用於指定字元串繪制效果、字體、格式、繪制區域等。

  5. 通過PdfPageBase.getCanvas().drawString(body, font2, brush2, rect, format2)方法將內容繪制到PDF頁面。

下面附上詳細的代碼demo示例:

import com.spire.pdf.*;

import com.spire.pdf.graphics.*;

import java.awt.*;

import java.awt.geom.*;

import java.io.*;

public class CreatePdfDocumentInJava {

public static void main(String[] args) throws FileNotFoundException, IOException {

//創建PdfDocument對象
PdfDocument doc = new PdfDocument();

//添加一頁
PdfPageBase page = doc.getPages().add();

//標題文字
String title = "Java基礎語法";

//創建單色畫刷對象
PdfSolidBrush brush1 = new PdfSolidBrush(new PdfRGBColor(Color.BLUE));
PdfSolidBrush brush2 = new PdfSolidBrush(new PdfRGBColor(Color.BLACK));

//創建TrueType字體對象
PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("宋體", Font.PLAIN, 14), true);
PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("宋體", Font.PLAIN, 10), true);

//創建PdfStringFormat對象
PdfStringFormat format1 = new PdfStringFormat();
format1.setAlignment(PdfTextAlignment.Center);//設置文字居中

//使用drawString方法繪制標題文字
page.getCanvas().drawString(title, font1, brush1, new Point2D.Float((float) page.getActualBounds(true).getWidth() / 2, 0), format1);

//從txt文件讀取內容到字元串
String body = readFileToString("C:\Users\Administrator\Desktop\bodyText.txt");

//創建PdfStringFormat對象
PdfStringFormat format2 = new PdfStringFormat();
format2.setParagraphIndent(20);//設置段首縮進

//創建Rectangle2D對象
Rectangle2D.Float rect = new Rectangle2D.Float(0, 30, (float) page.getActualBounds(true).getWidth(), (float) page.getActualBounds(true).getHeight());

//使用drawString方法在矩形區域繪制主體文字
page.getCanvas().drawString(body, font2, brush2, rect, format2);

//保存到PDF文檔
doc.saveToFile("ouput.pdf");
}

//自定義方法讀取txt文件內容到字元串
private static String readFileToString(String filepath) throws FileNotFoundException, IOException {

StringBuilder sb = new StringBuilder();
String s = "";
BufferedReader br = new BufferedReader(new FileReader(filepath));

while ((s = br.readLine()) != null) {
sb.append(s + " ");
}
br.close();
String str = sb.toString();
return str;
}

}

❿ java如何創建pdf文件,並將資料庫數據寫入pdf

寫入PDF? 可以,不過需要下載操作 PDF 的JAR包!操作起來不是太麻煩,不過就是生成的時間比較長。。。

flex 是 flash的一種延伸,flash 對於網站載入來說本來就比較慢,比較的消耗資源,生成PDF 可想而知!

其次 flex 發布到jobss tomcat 等伺服器中時,你的 flex 是編譯成flash,還是直接將xml放入容器中讓其自動生成flash呢? 如果是的話,那反應就更慢了。。。

再後者,flex 雖然說是 flash 只要客戶端支持flash就能看見 你的網站,但flex 需要在jobss tomcat 等容器中配置的,有免費的有收費的,它們的配置方法都不一樣的。。。

好了就說到這里,雖然有點廢話,並且與主題無關,但希望對LZ有幫助!

閱讀全文

與java寫入pdf相關的資料

熱點內容
android平滑滾動效果 瀏覽:841
什麼是編譯器指令 瀏覽:219
微控制器邏輯命令使用什麼匯流排 瀏覽:885
程序員在學校里是學什麼的 瀏覽:601
oraclejava數據類型 瀏覽:890
程序員考注冊會計師 瀏覽:957
怎麼使用access的命令按鈕 瀏覽:899
有點錢app在哪裡下載 瀏覽:832
博途v15解壓後無法安裝 瀏覽:205
什麼是根伺服器主機 瀏覽:438
安卓手游怎麼申請退款 瀏覽:555
安卓系統如何分享網頁 瀏覽:278
ad如何編譯pcb工程 瀏覽:414
除了滴滴app哪裡還能用滴滴 瀏覽:399
截圖怎麼保存文件夾然後壓縮 瀏覽:8
幻影伺服器怎麼樣 瀏覽:28
具體哪些廣東公司招程序員 瀏覽:870
嵌入式編譯器教程 瀏覽:307
ssl數據加密傳輸 瀏覽:87
51單片機定時器方式2 瀏覽:332