我嘗試在Jasper Reports中格式化Date,它適用於Windows,但不適用於Linux。在Linux中,結果文本被截斷。爲什麼使用Linux在PDF中截斷文本?
代碼:
JRXML:
<parameter name="timestamp" class="java.util.Date"/>
[...]
<textField>
<reportElement x="0" y="0" width="50" height="16" uuid="0007846a-26f1-457a-a198-67a2f7c8417c">
<property name="local_mesure_unitwidth" value="pixel"/>
<property name="com.jaspersoft.studio.unit.width" value="px"/>
<property name="local_mesure_unitx" value="pixel"/>
<property name="com.jaspersoft.studio.unit.x" value="px"/>
<property name="local_mesure_unity" value="pixel"/>
<property name="com.jaspersoft.studio.unit.y" value="px"/>
<property name="local_mesure_unitheight" value="pixel"/>
<property name="com.jaspersoft.studio.unit.height" value="px"/>
</reportElement>
<box padding="2"/>
<textElement textAlignment="Left" verticalAlignment="Top">
<font size="8" pdfFontName="Helvetica" pdfEncoding="Cp1250" isPdfEmbedded="true"/>
</textElement>
<textFieldExpression><![CDATA[DATEFORMAT($P{timestamp},"dd.MM HH:mm")]]></textFieldExpression>
</textField>
Maven依賴:
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>5.6.0</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports-functions</artifactId>
<version>5.6.0</version>
</dependency>
的Java:
private byte[] createPdf() {
try {
InputStream is = getClass().getResourceAsStream("MyReport.jasper");
JasperReport jasperReport = (JasperReport) JRLoader.loadObject(is);
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("timestamp", new Date());
JRDataSource jrDataSource = new JRBeanCollectionDataSource(new Vector(), false);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, jrDataSource);
byte[] pdf = JasperExportManager.exportReportToPdf(jasperPrint);
return pdf;
} catch (JRException e) {
throw new RuntimeException("Could not create PDF.", e);
}
}
個
結果:
結果與Windows:
結果使用Linux:
PDF屬性:
兩個生成的PDF文件在Acrobat Reader軟件相同的字體屬性的Windows:
正如你所看到的,字體沒有嵌入。 (如果我添加依賴關係jasperreports-fonts
並刪除屬性pdfFontName
,pdfEncoding
和isPdfEmbedded
),第二個字體「Helvetica」消失。
研究:
我讀:
- PDF generated with jasperreport not showing well on Linux but yes on Mac, could the os be related?
- http://community.jaspersoft.com/questions/527138/pdf-text-truncated-linux-fine-windows
- http://community.jaspersoft.com/questions/803503/why-text-filed-value-will-be-truncated-if-application-running-linux
和解決方案似乎是嵌入字體,但它不工作。
我使用字體「黑體」,這是默認的字體之一,這就是原因,看Wikipedia:
這些字體,或者合適的替代字體用相同的指標,必須始終在所有PDF可讀者因此不需要嵌入到PDF
和https://stackoverflow.com/a/27345103/5277820:
如果您在iText的使用這些字體,iText的w ^虐待忽略嵌入參數,因爲假定Adobe Reader和其他查看器可以正確呈現這些字體是安全的。
問:
爲什麼有Windows和Linux相同的字體不同的寬度?或者爲什麼文本截斷和/或換行不同?
是的,你應該總是嵌入字體,以避免問題。請參閱http://stackoverflow.com/a/26632606/5292302中的4錯誤(答案來自itext創始人),不是最好的例子,但給出了編碼實踐的概念,總是提供並嵌入字體 –