我正在使用飞碟将xhtml转换为pdf。如果xhtml文件中包含特殊字符,则生成pdf失败。我所说的特殊字符是指ASCII字符集之外的字符。下面是在生成pdf时失败的示例xhtml (input.xhtml - ANSI编码)。下面是我用来将xhtml转换为pdf的代码。
String inputFile = "samples/input.xhtml";
String url = new File(inputFile).toURI().toURL().toString();
String outputFile = "output.pdf";
OutputStream os = new FileOutputStream(outputFile);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(url);
renderer.layout();
renderer.createPDF(os);
os.close();
如何确保pdf生成在任何情况下都不会失败?
下面写的是另一个xhtml (input2.xhtml - UTF-8编码)。它成功地转换为pdf。但是生成的pdf没有显示特殊字符Ɠ。为什么生成的pdf中没有这个字符?如何确保pdf中出现这些类型的字符?当输入xhtml中存在NUL字符(U+0000)时,pdf生成也失败了?这是因为xml中不允许使用NUL吗?如果在xhtml中存在NUL,那么使用飞碟还能生成pdf吗?
input.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My First Document</title>
<style type="text/css"> b { color: green; } </style>
</head>
<body>
<p>
<b>Greetings Earthlings! ü </b>
We've come for your Java.
</p>
</body>
</html>
input2.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My First Document</title>
<style type="text/css"> b { color: green; } </style>
</head>
<body>
<p>
<b>Greetings Earthlings! ü Ɠ </b>
We've come for your Java.
</p>
</body>
</html>
关于问题的第一部分,字符Ɠ
没有出现的原因是默认字体没有表示它。
如果你想打印它,你必须嵌入一个包含这个字符的字体,例如Arial Unicode ms
可以这样做:
ITextRenderer renderer = new ITextRenderer();
renderer.getFontResolver().addFont("ARIALUNI.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);