TXT文本轉PDF示例代碼
Free Spire.PDF for Java 提供的TXT文本文件轉為PDF文件的方法實際上是先通過?readTextFromFile?方法讀取txt文件中的文本,然后再將讀取的文件使用?PdfTextWidget.draw()?方法繪制到 PDF 頁面上的指定位置。
該免費Java庫還提供了接口,允許設置繪制文本的字體、字體顏色、對齊樣式等。下面是一個簡單的示例,展示了如何將一個TXT文件轉換為一個PDF文件:
import com.spire.pdf.FileFormat;import com.spire.pdf.PdfDocument;import com.spire.pdf.PdfPageBase;importcom.spire.pdf.graphics.*;
importjava.awt.*;import java.awt.geom.Rectangle2D;import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;
publicclass ConvertTextToPdf {
? ? publicstaticvoidmain(String[] args)throws Exception {
? ? ? ? //從TXT文件讀取文本String text = readTextFromFile("C:\\Users\\Administrator\\Desktop\\文本.txt");
? ? ? ? //創建PdfDocument類的對象PdfDocument pdf =new PdfDocument();
? ? ? ? //添加一個頁面PdfPageBase page = pdf.getPages().add();
? ? ? ? //創建PdfFont類的對象Font font =newFont("宋體", Font.PLAIN, 11);
? ? ? ? PdfTrueTypeFont font1 =new PdfTrueTypeFont(font);
? ? ? ? //創建PdfTextLayout類的對象PdfTextLayout textLayout =new PdfTextLayout();
? ? ? ? textLayout.setBreak(PdfLayoutBreakType.Fit_Page);
? ? ? ? textLayout.setLayout(PdfLayoutType.Paginate);
? ? ? ? //創建PdfStringFormat類的對象PdfStringFormat format =new PdfStringFormat();
? ? ? ? format.setLineSpacing(20f);
? ? ? ? //用讀取的文本創建PdfTextWidget類的對象PdfTextWidget textWidget =new PdfTextWidget(text, font1, PdfBrushes.getBlack());
? ? ? ? //設置字符格式? ? ? ? textWidget.setStringFormat(format);
? ? ? ? //將文本添加到PDF頁面的指定位置Rectangle2D.Float bounds =new Rectangle2D.Float();
? ? ? ? bounds.setRect(0,25,page.getCanvas().getClientSize().getWidth(),page.getCanvas().getClientSize().getHeight());
? ? ? ? textWidget.draw(page, bounds, textLayout);
? ? ? ? //保存結果文件pdf.saveToFile("TXT轉PDF.pdf", FileFormat.PDF);
? ? }
? ? publicstaticString readTextFromFile(String fileName)throws IOException {
? ? ? ? StringBuffer sb =new StringBuffer();
? ? ? ? BufferedReader br =newBufferedReader(new FileReader(fileName));
? ? ? ? String content =null;
? ? ? ? while((content = br.readLine()) !=null) {
? ? ? ? ? ? sb.append(content);
? ? ? ? ? ? sb.append("\n");
? ? ? ? }
? ? ? ? return sb.toString();
? ? }
}
散熱風扇https://www.uv-semi.com/
深圳網站建設www.sz886.com