package com.booway.aspose.convert;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import com.aspose.pdf.Document;
import com.aspose.pdf.HtmlSaveOptions;
import com.aspose.pdf.LettersPositioningMethods;
import com.booway.aspose.analysis.constrant.ParamConstrant;
import com.booway.aspose.convert.flow.FlowStrategy;
import com.booway.aspose.convert.flow.pdf.PdfHtmlTitleFlow;
import com.booway.common.utils.StreamUtil;
import com.booway.dop.config.DopConfig;
/**
/
public class PdfConvert extends BaseConvertImpl
{
@Override
public ConvertType getConvertType()
{
return ConvertType.PDF;
}
@Override
public List<Class<? extends FlowStrategy>> getFlowStrategy()
{
List<Class<? extends FlowStrategy>> flowStrategys = new ArrayList<Class<? extends FlowStrategy>>();
flowStrategys.add(PdfHtmlTitleFlow.class);
return flowStrategys;
}
@Override
public void doAnalysis() throws Exception
{
// 转换成pdf文档对象即可
Document doc = new Document(getParam(ParamConstrant.SOURCEPATH, String.class));
addParam(ParamConstrant.DOCUMENT, doc);
}
@Override
public void doConvert() throws Exception
{
Document doc = getParam(ParamConstrant.DOCUMENT, Document.class);
if (null != doc)
{
doc.save(getParam(ParamConstrant.TARGETPATH, String.class), getHtmlSaveOptions(getParam(ParamConstrant.TARGETPATH, String.class)));
}
}
/*
* 获取HtmlSaveOptions
* @return
*/
protected HtmlSaveOptions getHtmlSaveOptions(final String targetPath)
{
HtmlSaveOptions newOptions = new HtmlSaveOptions();
newOptions.RasterImagesSavingMode = HtmlSaveOptions.RasterImagesSavingModes.AsEmbeddedPartsOfPngPageBackground;
newOptions.FontSavingMode = HtmlSaveOptions.FontSavingModes.SaveInAllFormats;
// 这个地方是控制, 图片是否压入的地方
newOptions.PartsEmbeddingMode = DopConfig.getBoolean(ParamConstrant.COMPRESSIMAGE, false) ? HtmlSaveOptions.PartsEmbeddingModes.EmbedAllIntoHtml : HtmlSaveOptions.PartsEmbeddingModes.EmbedCssOnly;
newOptions.LettersPositioningMethod = LettersPositioningMethods.UseEmUnitsAndCompensationOfRoundingErrorsInCss;
newOptions.setSplitIntoPages(false);
newOptions.CustomHtmlSavingStrategy = new HtmlSaveOptions.HtmlPageMarkupSavingStrategy()
{
@Override
public void invoke(HtmlSaveOptions.HtmlPageMarkupSavingInfo htmlSavingInfo)
{
byte[] resultHtmlAsBytes = new byte[(int) htmlSavingInfo.ContentStream.getLength()];
htmlSavingInfo.ContentStream.read(resultHtmlAsBytes, 0, resultHtmlAsBytes.length);
FileOutputStream fos = null;
try
{
LOG.info(“开始写入Html[” + targetPath + “]文件…”);
// 考虑编码
fos = new FileOutputStream(targetPath);
fos.write(resultHtmlAsBytes);
fos.flush();
LOG.info(“Html[” + targetPath + “]文件写入完成…”);
} catch (Exception e)
{
LOG.error("", e);
} finally
{
StreamUtil.closeStream(fos);
}
}
};
return newOptions;
}
}