我想在 appengine 中将 pdf 转换为图像文件。理想情况下,我会将 pdf 作为 blob 上传并存储 pdf 和 pdf 的图像。转换也可以在不同的时间完成(任务队列)。
我还没有找到任何工作示例或这样做的良好文档。
官方文档在这里。这是我在上传 servlet 上的实现。
@SuppressWarnings("serial")
public class UploadBlobServlet extends HttpServlet {
private static final Logger log = Logger.getLogger(UploadBlobServlet.class.getName());
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
BlobKey blobKey = blobs.get("data");
log.log(Level.WARNING,"blobKey: "+blobKey.getKeyString());
if (blobKey != null) {
resp.getWriter().println(blobKey.getKeyString());
BlobstoreInputStream in=new BlobstoreInputStream(blobKey);
byte[] b = IOUtils.toByteArray(is);
// try{
in.read(b);
Asset asset = new Asset(
"application/pdf", b, "testfile.pdf");
Document document = new Document(asset);
Conversion conversion = new Conversion(document, "image/png");
ConversionService service =
ConversionServiceFactory.getConversionService();
ConversionResult result = service.convert(conversion);
if (result.success()) {
// Note: in most cases, we will return data all in one asset,
// except that we return multiple assets for multi-page images.
FileService fileService=FileServiceFactory.getFileService();
for (Asset ass : result.getOutputDoc().getAssets()) {
AppEngineFile file=fileService.createNewBlobFile("image/png", "testfile.png");
FileWriteChannel writeChannel=fileService.openWriteChannel(file, false);
writeChannel.write(ByteBuffer.wrap(b));
writeChannel.closeFinally();
}
} else {
log.log(Level.WARNING,"error");
}
更新:已添加 byte[]=IOUtils.toByteArray(is); 并且仍然获得NPE ...
如果有人有经验,我也很好奇转换的质量。