All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.adobe.pdfservices.operation.pdfops.ExportPDFOperation Maven / Gradle / Ivy

Go to download

Adobe PDF Services SDK allows you to access RESTful APIs to create, convert, and manipulate PDFs within your applications.

There is a newer version: 4.1.0
Show newest version
/*
 * Copyright 2019 Adobe
 * All Rights Reserved.
 *
 * NOTICE: Adobe permits you to use, modify, and distribute this file in
 * accordance with the terms of the Adobe license agreement accompanying
 * it. If you have received this file from a source other than Adobe,
 * then your use, modification, or distribution of it requires the prior
 * written permission of Adobe.
 */

package com.adobe.pdfservices.operation.pdfops;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

import com.adobe.pdfservices.operation.exception.ServiceApiException;
import com.adobe.pdfservices.operation.exception.ServiceUsageException;
import com.adobe.pdfservices.operation.internal.ExtensionMediaTypeMapping;
import com.adobe.pdfservices.operation.internal.FileRefImpl;
import com.adobe.pdfservices.operation.internal.InternalExecutionContext;
import com.adobe.pdfservices.operation.internal.MediaType;
import com.adobe.pdfservices.operation.internal.api.FileDownloadApi;
import com.adobe.pdfservices.operation.internal.cpf.dto.response.platform.CPFContentAnalyzerResponse;
import com.adobe.pdfservices.operation.internal.exception.OperationException;
import com.adobe.pdfservices.operation.internal.service.ExportPDFService;
import com.adobe.pdfservices.operation.internal.util.FileUtil;
import com.adobe.pdfservices.operation.internal.util.PathUtil;
import com.adobe.pdfservices.operation.internal.util.StringUtil;
import com.adobe.pdfservices.operation.internal.util.ValidationUtil;
import com.adobe.pdfservices.operation.ExecutionContext;
import com.adobe.pdfservices.operation.Operation;
import com.adobe.pdfservices.operation.io.FileRef;
import com.adobe.pdfservices.operation.pdfops.options.exportpdf.ExportPDFTargetFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * An operation which exports a source PDF file to a supported format specified by
 * {@link ExportPDFTargetFormat}.
 * 

* For the image target formats (JPEG and PNG), the resulting file is a ZIP archive containing one image per page of * the source PDF file. Each image file name ends with "_<unpadded_page_index>". For example, a PDF file with 15 * pages will generate 15 image files. The first file's name ends with "_1" and the last file's name ends with "_15". * *

* Sample Usage: *

{@code   ExportPDFOperation exportPdfOperation = ExportPDFOperation.createNew(ExportPDFTargetFormat.DOCX);
 *   exportPdfOperation.setInput(FileRef.createFromLocalFile("~/Documents/exportPdfInput.pdf",
 *                                                            ExportPDFOperation.SupportedSourceFormat.PDF.getMediaType()));
 *   Credentials credentials = Credentials.serviceAccountCredentialsBuilder().fromFile("pdfservices-api-credentials.json").build();
 *   FileRef result = exportPdfOperation.execute(ExecutionContext.create(credentials));
 *   result.saveAs("output/ExportPDFOutput.docx");
 * }
*/ public class ExportPDFOperation implements Operation { private static final Logger LOGGER = LoggerFactory.getLogger(ExportPDFOperation.class); /** * Supported media types for this operation */ private static final Set SUPPORTED_SOURCE_MEDIA_TYPE = new HashSet<>(Arrays.asList(ExtensionMediaTypeMapping.PDF.getMediaType())); /** * Field representing the extension of the operation result, depends on the format specified by the client */ private final ExportPDFTargetFormat targetFormat; /** * Field to check if the operation instance was invoked more than once */ private boolean isInvoked = false; private FileRefImpl sourceFileRef; private ExportPDFOperation(ExportPDFTargetFormat exportPDFTargetFormat) { this.targetFormat = exportPDFTargetFormat; } /** * Constructs a {@code ExportPDFOperation} instance. * * @param exportPDFTargetFormat target format * @return a new {@code ExportPDFOperation} instance */ public static ExportPDFOperation createNew(ExportPDFTargetFormat exportPDFTargetFormat) { Objects.requireNonNull(exportPDFTargetFormat, "Export target format must not be null"); return new ExportPDFOperation(exportPDFTargetFormat); } /** * Sets an input PDF file (media type "application/pdf"). * * @param sourceFileRef an input PDF file */ public void setInput(FileRef sourceFileRef) { Objects.requireNonNull(sourceFileRef, "No input was set for operation"); this.sourceFileRef = (FileRefImpl) sourceFileRef; } /** * Executes this operation synchronously using the supplied context and returns a new FileRef instance for the resulting file. *

* The resulting file may be stored in the system temporary directory (per java.io.tmpdir System property). * See {@link FileRef} for how temporary resources are cleaned up. * * @param context the context in which to execute the operation * @return the resulting file; see class-level docs for format-specific considerations * @throws ServiceApiException if an API call results in an error response * @throws IOException if there is an error in reading either the input source or the resulting file * @throws ServiceUsageException if service usage limits have been reached or credentials quota has been exhausted. */ public FileRef execute(ExecutionContext context) throws ServiceApiException, IOException, ServiceUsageException { validateInvocationCount(); InternalExecutionContext internalExecutionContext = (InternalExecutionContext) context; this.validate(internalExecutionContext); try { LOGGER.info("All validations successfully done. Beginning Export Operation execution"); long startTimeMs = System.currentTimeMillis(); String location = ExportPDFService.exportPDF(internalExecutionContext, sourceFileRef, targetFormat, this.getClass().getSimpleName()); String targetFormatExtension = getTargetFormat(); String targetFileName = FileUtil.getRandomFileName(targetFormatExtension); String temporaryDestinationPath = PathUtil.getTemporaryDestinationPath(targetFileName, targetFormatExtension); FileDownloadApi.downloadAndSave(internalExecutionContext, location, temporaryDestinationPath, CPFContentAnalyzerResponse.class); LOGGER.info("Operation successfully completed. Stored exported PDF at {}", temporaryDestinationPath); LOGGER.debug("Operation Success Info - Request ID: {}, Latency(ms): {}", StringUtil.getRequestIdFromLocation(location), System.currentTimeMillis() - startTimeMs); isInvoked = true; return FileRef.createFromLocalFile(temporaryDestinationPath); } catch (OperationException oe) { throw new ServiceApiException(oe.getErrorMessage(), oe.getRequestTrackingId(), oe.getStatusCode(), oe.getReportErrorCode()); } } private String getTargetFormat() { switch (targetFormat) { case PNG: case JPEG: return ExtensionMediaTypeMapping.ZIP.getExtension(); default: return targetFormat.getFileExt(); } } private void validateInvocationCount() { if (isInvoked) { LOGGER.error("Operation instance must only be invoked once"); throw new IllegalStateException("Operation instance must not be reused, can only be invoked once"); } } private void validate(InternalExecutionContext context) { if (sourceFileRef == null) { throw new IllegalArgumentException("No input was set for operation"); } ValidationUtil.validateExecutionContext(context); ValidationUtil.validateMediaType(SUPPORTED_SOURCE_MEDIA_TYPE, this.sourceFileRef.getMediaType()); } /** * Supported source file formats for {@link ExportPDFOperation}. */ public enum SupportedSourceFormat implements MediaType { /** * Represents "application/pdf" media type */ PDF; /** * Returns the corresponding media type for this format, intended to be used for {@code mediaType} parameter in * {@link FileRef} methods. * * @return the corresponding media type */ public String getMediaType() { return ExtensionMediaTypeMapping.valueOf(name()).getMediaType().toLowerCase(); } } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy