我正在使用我的java代码中的PDFBox创建PDF文件。在此期间,我需要在这个新的PDF之间嵌入一个RTF(Rich Text Formate)文件。谷歌我找不到任何办法做到这一点。
我确信,我无法将直接读取的RTF内容写入PDF。即使我尝试使用下面的代码,但在打开PDF时它会出错。错误表示PDF已损坏。
注意:在C#和VB中可以完成类似的事情,http://www.syncfusion.com/kb/845/how-to-insert-an-rtf-text-into-a-pdf-document。所以我乐观地认为java中也必须有类似的东西。
我正在使用PDFBox 1.8.10
示例代码:
public static void main(String arg[]) throws IOException, COSVisitorException
{
final PDFont font = PDType1Font.HELVETICA_OBLIQUE;
final int font_size = 8;
PDDocument document = new PDDocument();
PDPage page = new PDPage(PDPage.PAGE_SIZE_LETTER);
document.addPage(page);
PDPageContentStream contents = new PDPageContentStream(document, page, true, true);
float x = 10f;
float y = page.getMediaBox().getHeight();
float yOffset = 15f;
float yCurrent = y - yOffset;
contents.beginText();
contents.moveTextPositionByAmount(x, yCurrent);
contents.setFont(font, font_size);
contents.drawString("Start Text before RTF");
contents.endText();
yCurrent = yCurrent - yOffset;
FileInputStream fi = new FileInputStream("C:\\Test.rtf");
StringBuffer sb = new StringBuffer();
BufferedReader br= new BufferedReader(new InputStreamReader(fi));
int c;
try {
while((c=br.read()) != -1){
sb.append((char)c);
}
} catch (IOException e) {
throw e;
}
br.close();
String rtfContent = sb.toString();
contents.beginText();
contents.moveTextPositionByAmount(x, yCurrent);
contents.setFont(font, font_size);
contents.drawString(rtfContent);
contents.endText();
yCurrent = yCurrent - yOffset;
contents.beginText();
contents.moveTextPositionByAmount(x, yCurrent);
contents.setFont(font, font_size);
contents.drawString("End Text after RTF");
contents.endText();
contents.close();
File file = new File("C:\\pdf\\RTF\\RRFSample1.pdf");
System.out.println("Sample file saved at : " + file.getAbsolutePath());
document.save(file);
document.close();
}