Java:PDF转换器在Mac中工作,但在Windows中,会生成空PDF文件
我需要一些帮助在这里与我的PDF转换程序 所以,我正在使用JADE框架进行移动代理PDF转换。但是,我所面临的问题更多地与我将文本文件转换为PDF、通过网络以二进制形式发送以及恢复PDF文件的方式有关 我写的程序在我的MacBook上运行正常。 但是,在Windows上,它将我的PDF文件还原为空PDF 这是我用来发送PDF文件的代码Java:PDF转换器在Mac中工作,但在Windows中,会生成空PDF文件,java,file,pdf,byte,agents-jade,Java,File,Pdf,Byte,Agents Jade,我需要一些帮助在这里与我的PDF转换程序 所以,我正在使用JADE框架进行移动代理PDF转换。但是,我所面临的问题更多地与我将文本文件转换为PDF、通过网络以二进制形式发送以及恢复PDF文件的方式有关 我写的程序在我的MacBook上运行正常。 但是,在Windows上,它将我的PDF文件还原为空PDF 这是我用来发送PDF文件的代码 private void sendPDF(File f, String recipient) { String content = ""; if
private void sendPDF(File f, String recipient) {
String content = "";
if(f != null) {
try {
FileInputStream fis = new FileInputStream(f);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int noBytesRead = 0;
byte[] buffer = new byte[1024];
while((noBytesRead = fis.read(buffer)) != -1) {
baos.write(buffer, 0, noBytesRead);
}
content = baos.toString();
fis.close();
baos.close();
System.out.println("Successful PDF-to-byte conversion.");
} catch (Exception e) {
System.out.println("Exception while converting PDF-to-byte.");
content = "failed";
e.printStackTrace();
}
} else {
System.out.println("PDF-to-file conversion failed.");
content = "failed";
}
ACLMessage message = new ACLMessage(ACLMessage.INFORM);
message.addReceiver(new AID(recipient, AID.ISLOCALNAME));
message.setContent(content);
myAgent.send(message);
System.out.println("PDF document has been sent to requesting client.");
}
下面是我用来恢复PDF的代码
private File restorePDF(String content) {
String dirPDF = dirBuffer + "/" + new Date().getTime() + ".pdf";
File f = new File(dirPDF);
try {
if(!f.exists()) f.createNewFile();
byte[] buffer = new byte[1024];
ByteArrayInputStream bais = new ByteArrayInputStream(content.getBytes());
FileOutputStream fos = new FileOutputStream(f);
int noBytesRead = 0;
while((noBytesRead = bais.read(buffer)) != -1) {
fos.write(buffer, 0, noBytesRead);
}
fos.flush();
fos.close();
bais.close();
} catch (Exception e) {
e.printStackTrace();
f = null;
}
return f;
}
在此方面的任何帮助都将不胜感激!:) 一个问题是您使用了错误的字符分隔符。Java有一个内置函数,可以为正确的操作系统返回正确的字符。看 您的代码将如下所示
String dirPDF = dirBuffer + File.separatorChar + new Date().getTime() + ".pdf";
供参考:
分离器炭
依赖于系统的默认名称分隔符。这个领域是
初始化为包含系统值的第一个字符
属性文件.separator在UNIX系统上,此字段的值为
'/'; 在Microsoft Windows系统上,它是“\”。
这个问题有点让人困惑,因为PDF内容并没有什么特别之处 我假设您实际上想要发送字节,实际上发送字符串,并且字符串编码在客户端和服务器上是不同的 这通常是发生问题的地方:
content = baos.toString();
以及:
PDF文件是一种二进制文件格式,带有查找表和大量二进制数据块,如果将其设置为字符串,则会破坏它。如果你想知道PDF文件的内部信息,我已经写了一大堆关于它的博客文章(http://www.jpedal.org/PDFblog/2010/09/understanding-the-pdf-file-format-series/)有日志吗?例外?Trace?我想就是这样。再加上这样一个事实,读取PDF然后将其转换为字符串似乎非常危险,即使编码两端都匹配@你不能只写字节吗?如果不是,可以使用BASE64或类似的东西。
content.getBytes()