用JODConverter和openoffice生成PDF文档时候的PAGESIZE设置有关问题

用JODConverter和openoffice生成PDF文档时候的PAGESIZE设置问题

生成PDF的方法有很多

其中一个方法就是JODConverter http://www.artofsolving.com/opensource/jodconverter 和openoffice 来生成。

一般的如何转换这里就不介绍了。可以看看其他文章。例如:http://nopainnogain.iteye.com/blog/819432

这里要说的是如果我们要转换的excel等的纸张大小不是默认的A4的情况下如何处理。

      一般转换的时候会有部分代码是下面这样。

  // convert 
  DocumentConverter converter = new OpenOfficeDocumentConverter(connection); 
  converter.convert(inputFile, outputFile); 
用上面的代码转换的时候,

无论输入文档的纸张定义成多大,都会被当成默认的A4来进行的转换,转换后的PDF也是A4的。

转换的具体过程,其实跟手动操作是一样的,openoffice打开要转换的文档,再点转换PDF按钮。

打开文档后,默认A4大小,我们调整纸张大小,转换后仍然是A4的PDF文件。

经过查看,其实转换PDF时候的参数设置里面并没有设置纸张大小的选择。所以只能从加载文档的地方想办法。


查看源代码OpenOfficeDocumentConverter的convert方法的源代码,可以看到其中调用到OpenOfficeDocumentConverter的下面的方法:

private void loadAndExport(String inputUrl, Map/*<String,Object>*/ loadProperties, String outputUrl, Map/*<String,Object>*/ storeProperties) 

上面的方法主要三个内容:

document = loadDocument(inputUrl, loadProperties);
refreshDocument(document);
storeDocument(document, outputUrl, storeProperties);

loadDocument是加载office文档的,通过loadProperties传递的参数。支持的参数都定义在jar包里面的document-formats.xml里面了,没有 纸张设置的参数。

我们要做的只能增加几个参数。这个参数的具体内容需要查阅openoffice的文档。

因为loadDocument方法是private的,我们只能想别的办法,好在 refreshDocument不是private

我们可以新建一个class继承OpenOfficeDocumentConverter 并override refreshDocument方法。

        public final static Size A5, A4, A3;
	public final static Size B4, B5, B6;
	public final static Size KaoqinReport;

	static {
		A5 = new Size(14800, 21000);
		A4 = new Size(21000, 29700);
		A3 = new Size(29700, 42000);

		B4 = new Size(25000, 35300);
		B5 = new Size(17600, 25000);
		B6 = new Size(12500, 17600);
		
		KaoqinReport = new Size(25400, 27940);
	}

/*
	 * XComponent:xCalcComponent
	 * 
	 * @seecom.artofsolving.jodconverter.openoffice.converter.
	 * AbstractOpenOfficeDocumentConverter
	 * #refreshDocument(com.sun.star.lang.XComponent)
	 */
	@Override
	protected void refreshDocument(XComponent document) {
		super.refreshDocument(document);

		// The default paper format and orientation is A4 and portrait. To
		// change paper orientation
		// re set page size
		XPrintable xPrintable = (XPrintable) UnoRuntime.queryInterface(XPrintable.class, document);
		PropertyValue[] printerDesc = new PropertyValue[2];

		// Paper Orientation
//		printerDesc[0] = new PropertyValue();
//		printerDesc[0].Name = "PaperOrientation";
//		printerDesc[0].Value = PaperOrientation.PORTRAIT;

		// Paper Format
		printerDesc[0] = new PropertyValue();
		printerDesc[0].Name = "PaperFormat";
		printerDesc[0].Value = PaperFormat.USER;

		// Paper Size
		printerDesc[1] = new PropertyValue();
		printerDesc[1].Name = "PaperSize";
		printerDesc[1].Value = KaoqinReport;

		try {
			xPrintable.setPrinter(printerDesc);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		}

	}


如果是excel有多个sheet,上面的部分只会影响第一个sheet,其他sheet还会以A4的大小输出。