Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weโ€™ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New converter itextpdfa #117

Draft
wants to merge 10 commits into
base: main
Choose a base branch
from
2 changes: 1 addition & 1 deletion .java-version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
11
17
4 changes: 2 additions & 2 deletions helm/Chart.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ apiVersion: v2
name: pagopapdfengine
description: Microservice description
type: application
version: 0.119.0
appVersion: 2.10.9
version: 0.120.0
appVersion: 2.10.11-itextpdfa
dependencies:
- name: microservice-chart
version: 2.4.0
Expand Down
2 changes: 1 addition & 1 deletion helm/values-dev.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ microservice-chart:
fullnameOverride: ""
image:
repository: ghcr.io/pagopa/pagopa-pdf-engine
tag: "2.10.9"
tag: "2.10.11-itextpdfa"
pullPolicy: Always
# https://github.com/Azure/azure-functions-host/blob/dev/src/WebJobs.Script.WebHost/Controllers/HostController.cs
livenessProbe:
Expand Down
2 changes: 1 addition & 1 deletion helm/values-prod.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ microservice-chart:
fullnameOverride: ""
image:
repository: ghcr.io/pagopa/pagopa-pdf-engine
tag: "2.10.9"
tag: "2.10.11-itextpdfa"
pullPolicy: Always
# https://github.com/Azure/azure-functions-host/blob/dev/src/WebJobs.Script.WebHost/Controllers/HostController.cs
livenessProbe:
Expand Down
2 changes: 1 addition & 1 deletion helm/values-uat.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ microservice-chart:
fullnameOverride: ""
image:
repository: ghcr.io/pagopa/pagopa-pdf-engine
tag: "2.10.9"
tag: "2.10.11-itextpdfa"
pullPolicy: Always
# https://github.com/Azure/azure-functions-host/blob/dev/src/WebJobs.Script.WebHost/Controllers/HostController.cs
livenessProbe:
Expand Down
2 changes: 1 addition & 1 deletion openapi/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"openapi": "3.0.1",
"info": {
"title": "OpenAPI definition - PDF Engine",
"version": "2.10.9"
"version": "2.10.11-itextpdfa"
},
"servers": [
{
Expand Down
2 changes: 1 addition & 1 deletion openapi/openapi_node.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"openapi": "3.0.1",
"info": {
"title": "OpenAPI definition - PDF Engine Node",
"version": "2.10.9"
"version": "2.10.11-itextpdfa"
},
"servers": [
{
Expand Down
22 changes: 20 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

<groupId>it.gov.pagopa</groupId>
<artifactId>pdf-engine</artifactId>
<version>2.10.9</version>
<version>2.10.11-itextpdfa</version>
<packaging>jar</packaging>

<name>pagopa-pdf-engine</name>
Expand All @@ -29,6 +29,11 @@
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
<repository>
<id>maven_central</id>
<name>Maven Central</name>
<url>https://repo.maven.apache.org/maven2/</url>
</repository>
</repositories>

<dependencies>
Expand Down Expand Up @@ -188,7 +193,7 @@
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf.free</artifactId>
<version>9.12.3</version>
<version>5.1.0</version>
</dependency>

<dependency>
Expand Down Expand Up @@ -234,6 +239,19 @@
<version>2.6.1</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-pdfa</artifactId>
<version>5.5.13</version>
</dependency>


</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

package it.gov.pagopa.pdf.engine;

import com.fasterxml.jackson.databind.ObjectMapper;
Expand Down Expand Up @@ -41,14 +40,11 @@
*/
public class HttpTriggerGeneratePDFFunction {

private final Logger logger = LoggerFactory.getLogger(HttpTriggerGeneratePDFFunction.class);

private final String workingDirectoryPath = System.getenv().getOrDefault("WORKING_DIRECTORY_PATH", "");

private static final String INVALID_REQUEST_MESSAGE = "Invalid request";
private static final String ERROR_GENERATING_PDF_MESSAGE = "An error occurred when generating the PDF";
private static final String PATTERN_FORMAT = "yyyy.MM.dd.HH.mm.ss";

private final Logger logger = LoggerFactory.getLogger(HttpTriggerGeneratePDFFunction.class);
private final String workingDirectoryPath = System.getenv().getOrDefault("WORKING_DIRECTORY_PATH", "");
private final GeneratePDFService generatePDFService;
private final ParseRequestBodyService parseRequestBodyService;

Expand All @@ -63,6 +59,16 @@ public HttpTriggerGeneratePDFFunction(GeneratePDFService generatePDFService, Par
this.parseRequestBodyService = parseRequestBodyService;
}

private static HttpStatus getHttpStatus(PDFEngineException e) {
HttpStatus status;
if(e.getErrorCode().equals(AppErrorCodeEnum.PDFE_703) || e.getErrorCode().equals(AppErrorCodeEnum.PDFE_704) || e.getErrorCode().equals(AppErrorCodeEnum.PDFE_705)) {
status = INTERNAL_SERVER_ERROR;
} else {
status = BAD_REQUEST;
}
return status;
}

/**
* This function will be invoked when a Http Trigger occurs.
* This function listens at endpoint "/api/generate-pdf". To invoke it using "curl" command in bash:
Expand All @@ -80,7 +86,7 @@ public HttpResponseMessage run(
logger.debug("Generate PDF function called at {}", LocalDateTime.now());

Optional<byte[]> optionalRequestBody = request.getBody();
if (optionalRequestBody.isEmpty()) {
if(optionalRequestBody.isEmpty()) {
logger.error("Invalid request the payload is null");
return request
.createResponseBuilder(BAD_REQUEST)
Expand Down Expand Up @@ -122,23 +128,23 @@ public HttpResponseMessage run(
.build();
}

if (generatePDFInput.getTemplateZip() == null) {
if(generatePDFInput.getTemplateZip() == null) {
logger.error("Invalid request, template HTML not provided");
return request
.createResponseBuilder(BAD_REQUEST)
.body(buildResponseBody(BAD_REQUEST, AppErrorCodeEnum.PDFE_897, INVALID_REQUEST_MESSAGE))
.build();
}

if (generatePDFInput.getData() == null) {
if(generatePDFInput.getData() == null) {
logger.error("Invalid request the PDF document input data are null");
return request
.createResponseBuilder(BAD_REQUEST)
.body(buildResponseBody(BAD_REQUEST, AppErrorCodeEnum.PDFE_898, INVALID_REQUEST_MESSAGE))
.build();
}

try (BufferedInputStream inputStream = generatePDFService.generatePDF(generatePDFInput, workingDirPath, logger)){
try (BufferedInputStream inputStream = generatePDFService.generatePDF(generatePDFInput, workingDirPath, logger)) {
byte[] fileBytes = inputStream.readAllBytes();

logger.debug("Returning generated pdf at {}", LocalDateTime.now());
Expand Down Expand Up @@ -176,16 +182,6 @@ public HttpResponseMessage run(

}

private static HttpStatus getHttpStatus(PDFEngineException e) {
HttpStatus status;
if (e.getErrorCode().equals(AppErrorCodeEnum.PDFE_703) || e.getErrorCode().equals(AppErrorCodeEnum.PDFE_704) || e.getErrorCode().equals(AppErrorCodeEnum.PDFE_705)) {
status = INTERNAL_SERVER_ERROR;
} else {
status = BAD_REQUEST;
}
return status;
}

private ErrorResponse buildResponseBody(HttpStatus status, AppErrorCodeEnum appErrorCode, String message) {
return new ErrorResponse(
status,
Expand All @@ -209,12 +205,13 @@ private void clearTempDirectory(Path workingDirPath) {
private File createWorkingDirectory() throws IOException {

File workingDirectory = new File(workingDirectoryPath);
if (!workingDirectory.exists()) {
if(!workingDirectory.exists()) {
try {
Files.createDirectory(workingDirectory.toPath());
} catch (FileAlreadyExistsException e) {}
} catch (FileAlreadyExistsException e) {
}
}
return workingDirectory;
}

}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@

package it.gov.pagopa.pdf.engine.service.impl;

import com.spire.pdf.conversion.PdfStandardsConverter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;
import it.gov.pagopa.pdf.engine.client.impl.PdfEngineClientImpl;
import it.gov.pagopa.pdf.engine.exception.GeneratePDFException;
import it.gov.pagopa.pdf.engine.model.AppErrorCodeEnum;
Expand All @@ -11,7 +12,6 @@
import it.gov.pagopa.pdf.engine.service.GeneratePDFService;
import it.gov.pagopa.pdf.engine.util.ObjectMapperUtils;
import org.apache.commons.io.IOUtils;

import org.slf4j.Logger;

import java.io.*;
Expand All @@ -22,8 +22,46 @@
import java.util.zip.ZipOutputStream;

import static it.gov.pagopa.pdf.engine.model.AppErrorCodeEnum.*;

public class GeneratePDFServiceImpl implements GeneratePDFService {


public static void convert(String pdfNormal, String pdfA, Logger logger) {
Document document = new Document();
PdfReader reader;
try {
PdfAWriter writer = PdfAWriter.getInstance(document, new FileOutputStream(pdfA), PdfAConformanceLevel.PDF_A_1B);
document.addCreationDate();

writer.setTagged();
writer.createXmpMetadata();
writer.setCompressionLevel(9);

document.open();
PdfContentByte pdfContentByte = writer.getDirectContent();

reader = new PdfReader(pdfNormal);

PdfImportedPage page;

int pageCount = reader.getNumberOfPages();
for (int i = 0; i < pageCount; i++) {
final int index = i + 1;
document.setPageSize(reader.getPageSize(index));
document.newPage();

page = writer.getImportedPage(reader, index);
page.setBoundingBox(reader.getCropBox(index));

pdfContentByte.addTemplate(page, 0, 0);
}
} catch (IOException | DocumentException ex) {
logger.error(ex.getMessage(), ex);
}

document.close();
}

@Override
public BufferedInputStream generatePDF(GeneratePDFInput generatePDFInput, Path workingDirPath, Logger logger)
throws GeneratePDFException {
Expand All @@ -42,20 +80,20 @@ public BufferedInputStream generatePDF(GeneratePDFInput generatePDFInput, Path w

logger.debug("PdfEngineClient called at {}", LocalDateTime.now());
PdfEngineResponse response = pdfEngineClient.generatePDF(pdfEngineRequest);
if (response.getStatusCode() != 200 || response.getTempPdfPath() == null) {
if(response.getStatusCode() != 200 || response.getTempPdfPath() == null) {
throw new GeneratePDFException(AppErrorCodeEnum.valueOf(
response.getErrorCode()),response.getErrorMessage());
response.getErrorCode()), response.getErrorMessage());
}
logger.debug("PdfEngineClient responded at {}", LocalDateTime.now());

String fileToReturn = response.getTempPdfPath();
logger.debug("Starting pdf conversion at {}", LocalDateTime.now());
PdfStandardsConverter converter = new PdfStandardsConverter(fileToReturn);
converter.toPdfA2A(pdfTempFile.getParent() + "/ToPdfA2A.pdf");
logger.info("Starting pdf conversion at {}", LocalDateTime.now());
convert(fileToReturn, pdfTempFile.getParent() + "/ToPdfA2A.pdf", logger);

fileToReturn = pdfTempFile.getParent() + "/ToPdfA2A.pdf";
logger.debug("Completed pdf conversion at {}", LocalDateTime.now());

if (generatePDFInput.isGenerateZipped()) {
if(generatePDFInput.isGenerateZipped()) {
return zipPDFDocument(new File(fileToReturn), workingDirPath);
}
return new BufferedInputStream(new FileInputStream(fileToReturn));
Expand Down Expand Up @@ -98,4 +136,5 @@ private File createTempFile(String fileName, String fileExtension, Path workingD
throw new GeneratePDFException(error, error.getErrorMessage(), e);
}
}

}
Loading