生成PDF文档代码如下:
package poi.itextimport java.io.FileOutputStream
import java.io.IOException
import java.awt.Color
import com.lowagie.text.*
import com.lowagie.text.pdf.*
import com.lowagie.text.pdf.BaseFont
/**
* 创建Pdf文档
* @author Administrator
*
*/
public class HelloPdf
{
public static void main(String[] args)throws Exception
{
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED)
Font FontChinese = new Font(bfChinese, 12, Font.NORMAL)
// 第一步,创建document对象
Rectangle rectPageSize = new Rectangle(PageSize.A4)
//下面代码设置页面横置
//rectPageSize = rectPageSize.rotate()
//创建document对象并指定边距
Document doc = new Document(rectPageSize,50,50,50,50)
Document document = new Document()
try
{
// 第二步,将Document实例和文件输出流用PdfWriter类绑定在一起
//从而完成向Document写,即写入PDF文档
PdfWriter.getInstance(document,new FileOutputStream("src/poi/itext/HelloWorld.pdf"))
//第3步,打开文档
document.open()
//第3步,向文档添加文字. 文档由段组成
document.add(new Paragraph("Hello World"))
Paragraph par = new Paragraph("世界你好",FontChinese)
document.add(par)
PdfPTable table = new PdfPTable(3)
for(int i=0i<12i++)
{
if (i == 0)
{
PdfPCell cell = new PdfPCell()
cell.setColspan(3)
cell.setBackgroundColor(new Color(180,180,180))
cell.addElement(new Paragraph("表格头" , FontChinese))
table.addCell(cell)
}
else
{
PdfPCell cell = new PdfPCell()
cell.addElement(new Paragraph("表格内容" , FontChinese))
table.addCell(cell)
}
}
document.add(table)
}
catch (DocumentException de)
{
System.err.println(de.getMessage())
}
catch (IOException ioe)
{
System.err.println(ioe.getMessage())
}
//关闭document
document.close()
System.out.println("生成HelloPdf成功!")
}
}
希望对你有帮助。
可以使用Spire.XLS for Java实现把Excel转为PDF文档。
首先,您需要在 Java 程序中添加 Spire.Xls.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.xls</artifactId>
<version>5.3.3</version>
</dependency></dependencies>
将整个 Excel 文件转换为 PDF
以下是将整个 Excel 文档转换为 PDF 的步骤。
创建一个 Workbook 对象。
使用 Workbook.loadFromFile() 方法加载示例 Excel 文档。
通过 Workbook.getConverterSetting() 方法返回的 ConverterSetting 对象下的方法设置 Excel 到 PDF 的转换选项。
使用 Workbook.saveToFile() 方法将整个 Excel 文档转换为 PDF。
代码如下:
import com.spire.xls.FileFormatimport com.spire.xls.Workbookpublic class ConvertExcelToPdf {
public static void main(String[] args) {
//创建一个Workbook实例并加载Excel文件
Workbook workbook = new Workbook()
workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx")
//设置转换后的PDF页面高宽适应工作表的内容大小
workbook.getConverterSetting().setSheetFitToPage(true)
//将生成的文档保存到指定路径
workbook.saveToFile("output/ExcelToPdf", FileFormat.PDF)
}
}