0

我正在尝试使用 ReportClientDocument、ByteArrayInputStream 和 ByteArrayOutputStream 读取 .rpt 文件并生成 pdf。生成pdf文件后,我无法打开它。它显示“它可能已损坏或使用预览无法识别的文件格式。” 下面提供了我的源代码

public static void generatePDFReport()
{
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    LocalDateTime now = LocalDateTime.now();
    System.out.println(dtf.format(now));
    try {
        ReportClientDocument rcd = new ReportClientDocument();

        String rptPath="/Users/florapc/Desktop/Report/AcStatement.rpt";
        String outputPath=String.format("/Users/florapc/Desktop/Report/%s.pdf",dtf.format(now));
        File inputFile = new File(rptPath);
        File outputFile = new File(outputPath);
        rcd.open(rptPath, 0);
        System.out.println(rptPath);
        List<IParameterField> fld = rcd.getDataDefController().getDataDefinition().getParameterFields();

        List<String> reportContent = new ArrayList<String>();
        System.out.println(fld.size());
        for (int i = 0; i < fld.size(); i++) {

            System.out.println(fld.get(i).getDescription());
            reportContent.add(fld.get(i).getDescription().replaceAll("[^a-zA-Z0-9]", " "));
        }

                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(reportContent);
        byte[] bytes = bos.toByteArray();

        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        byte[] byteArray = new byte[byteArrayInputStream.available()];
        int x = byteArrayInputStream.read(byteArray, 0, byteArrayInputStream.available());
        System.out.println(x);
        FileOutputStream fileOutputStream = new FileOutputStream(outputFile);;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();;
        byteArrayOutputStream.write(byteArray, 0, x);

        byteArrayOutputStream.writeTo(fileOutputStream);
        System.out.println(fileOutputStream);
        System.out.println("File exported succesfully");

        byteArrayInputStream.close();

        byteArrayOutputStream.close();
        fileOutputStream.close();
        rcd.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

我可以读取 .rpt 文件并在控制台中打印它。请帮助我找到正确生成 pdf 的最佳方法。

4

1 回答 1

0

我不熟悉ReportClientDocument。据我了解,它本身不是 PDF 文档,而是可以保存为 PDF 的报告。ObjectOutputStream不会实现这一点,因为它是 Java 特定格式并且与 PDF 无关。

PDF 导出似乎PrintOutputController需要 a 。因此,您的代码看起来更像这样:

FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
InputStream is = rcd.getPrintOutputController().export(ReportExportFormat.PDF);
copy(is, fileOutputStream);
fileOutputStream.close();

...

void copy(InputStream source, OutputStream target) throws IOException {
    byte[] buf = new byte[8192];
    int length;
    while ((length = source.read(buf)) > 0) {
        target.write(buf, 0, length);
    }
}

请注意,不需要字节数组流。它们是绕道而行,会减慢您的程序并增加内存消耗。

于 2021-09-22T07:52:05.443 回答