java生成pdf

直入正题:


java生成pdf

所需ar包

具体代码:

package com.medmeeting.core;

import com.itextpdf.text.*;

import com.itextpdf.text.pdf.BaseFont;

import com.itextpdf.text.pdf.PdfPCell;

import com.itextpdf.text.pdf.PdfPTable;

import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileOutputStream;

import java.util.List;

/**

* @Date: 2019/11/26 16:33

*/

public class MakePdf {

private static Font headfont;

private static Font keyfont;

private static Font textfont;

static {

BaseFont bfChinese;

try {

bfChinese = BaseFont.createFont("simsun.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

headfont = new Font(bfChinese, 25, Font.BOLD);

textfont = new Font(bfChinese, 17, Font.BOLD);

keyfont = new Font(bfChinese, 14, Font.NORMAL);

} catch (Exception e) {

e.printStackTrace();

}

}

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

test1();

}

public static PdfPTable createTable(int num, List<String> list) throws Exception {

PdfPTable table = new PdfPTable(num);

table.setTotalWidth(2);

table.setPaddingTop(2);

for (int i = 0; i < list.size(); i++) {

table.addCell(new Paragraph(list.get(i), textfont));

}

return table;

}

public static void test1() throws Exception {

FileOutputStream out = new FileOutputStream("C:\\game\\kangk.pdf");

Rectangle rectangle = new Rectangle(PageSize.A4);

Document doc = new Document(rectangle);

doc = new Document(rectangle.rotate());

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

writer.setPdfVersion(PdfWriter.PDF_VERSION_1_2);

// doc.addTitle("Title");//标题

// doc.addAuthor("kangk");// 作者

// doc.addSubject("Subject");//主题

// doc.addKeywords("keywords1");//关键字

// doc.addCreator("Creator");

// Phrase、Paragraph、Table、Graphic

Paragraph tParagraph = new Paragraph("测试", headfont);

tParagraph.setAlignment(1);//setAlignment的参数1为居中对齐、2为右对齐、3为左对齐,默认为左对齐。

Chunk chunk = new Chunk("This text is underlined", FontFactory.getFont(FontFactory.HELVETICA,15,Font.UNDEFINED));

//建立了一个列数为3的表格,并将边框宽度设为1,颜色为蓝色,衬距为5。

PdfPTable table = new PdfPTable(3);

PdfPCell cell = new PdfPCell(new Paragraph("text cell", textfont));

cell.setColspan(3);//指定了该单元格占3列

table.addCell(cell);

//往表格中添加单元格(cell)时,按自左向右、从上而下的次序添加

table.addCell("1.1");

table.addCell("2.1");

table.addCell("1.2");

table.addCell("2.2");

table.addCell("1.3");

table.addCell(new Paragraph("233", keyfont));

doc.open();

doc.add(tParagraph);

doc.add(chunk);

doc.add(table);

doc.add(new Paragraph("\n"));

Paragraph paragraph = new Paragraph("您的学术任务" + "\n", textfont);

doc.add(paragraph);

doc.add(new Paragraph("内容1", headfont));

doc.add(new Paragraph("内容2 内容2 内容2 内容2", textfont));

doc.add(new Paragraph("内容3 内容3 内容3 内容3 内容3 内容3 内容3 内容3", keyfont));

doc.close();

}

}

您可能还会对下面的文章感兴趣: