3

我需要一些关于我的 PDF 转换器程序的帮助。

所以,我正在使用 JADE 框架做这个移动代理 PDF 转换器。但是,我面临的问题更多与我将文本文件转换为 PDF、将其作为二进制文件通过网络发送并恢复 PDF 文件的方式有关。

我编写的程序可以在我的 MacBook 上正常运行。但是,在 Windows 上,它将我的 PDF 文件恢复为空 PDF。

这是我用于发送 PDF 文件的代码。

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;
}

对此的任何帮助将不胜感激!:)

4

3 回答 3

1

PDF 文件是一种二进制文件格式,带有查找表和大量二进制数据块,使其成为字符串会破坏它。如果您想了解 PDF 文件的内部,我已经写了一大堆关于它的博客文章(http://www.jpedal.org/PDFblog/2010/09/understanding-the-pdf-file-format -系列/)

于 2011-08-29T12:16:24.397 回答
1

问题有点令人困惑,因为没有关于 PDF 内容的具体内容。

我假设您实际上想要发送字节,实际上发送一个字符串,并且客户端和服务器上的字符串编码不同。

这通常是麻烦发生的地方:

 content = baos.toString();

和:

 content.getBytes()
于 2011-08-29T02:06:43.133 回答
0

一个问题是您使用了错误的分隔符。Java 有一个内置函数,可以为正确的操作系统返回正确的字符。请参阅分隔符 char

你的代码看起来像这样

String dirPDF = dirBuffer + File.separatorChar + new Date().getTime() + ".pdf";

以供参考:

分隔符

系统相关的默认名称分隔符。该字段被初始化为包含系统属性 file.separator 值的第一个字符。在 UNIX 系统上,该字段的值为 '/';在 Microsoft Windows 系统上,它是 '\'。

于 2011-08-29T02:04:17.967 回答