不使用iText将内容导出为pdf

时间:2014-07-02 04:40:20

标签: java html jsp servlets

我已经使用表id将html(表)内容导出到excel。我使用了类似

的内容类型
 response.getWriter().write(datatoexport);
 response.setHeader("Content-Type", "application/vnd.ms-excel");
 response.setHeader("Content-Disposition", "attachment; filename=test_file.xls");
 response.getWriter().flush();
 response.getWriter().close();

这里,datatoexport是表id。

与excel一起工作正常。

但是,如果我使用内容类型为pdf

 response.setHeader("Content-Type", "application/pdf");
 response.setHeader("Content-Disposition", "attachment; filename=test_file.pdf");

但是,我得到的pdf文件已损坏。有帮助吗? 不使用iText或其他罐子,我怎样才能实现它?特别是在IE 8中

1 个答案:

答案 0 :(得分:3)

在将pdf文件发送到输出之前,您需要在服务器端生成它。

要将文件转换为PDF,我建议在无头模式和JODConverter中使用OpenOffice。

要以无头模式运行OpenOffice(在Windows中)运行命令(假设您已安装在C:\Apps中的OpenOfficePortable:

"C:\Apps\OpenOfficePortable\OpenOfficePortable.exe" -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard

当OpenOffice以无头模式启动时,使用JODConverter库运行一个简单的工作原型:

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import java.io.File;
import java.net.ConnectException;

public class JODConv {  
    public static void main(String[] args) throws ConnectException {

        if (args.length!=2) {
            System.out.println("Usage:\nJODConv <file-to-convert> <pdf-file>");
            System.exit(0);
        }

        String sourceFilePath = args[0];
        String destFilePath = args[1];


        File inputFile = new File(sourceFilePath);
        File outputFile = new File(destFilePath);

        // connect to an OpenOffice.org instance running on port 8100
        OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
        connection.connect();

        // convert
        DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
        converter.convert(inputFile, outputFile);

        // close the connection
        connection.disconnect();
    }       
}
相关问题