Commit 54f3cbef by paolo

[ADD] PDF REST ACEPTA ORIENTACION HORIZONTAL

Parametro opcional "orientation" (horizontal/landscape/true) en JSON o
form-data. Si no se envia, el PDF se genera vertical como antes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
parent a39fc151
...@@ -28,6 +28,7 @@ public class pdfRest { ...@@ -28,6 +28,7 @@ public class pdfRest {
String fileName; String fileName;
String background; String background;
boolean isBase64; boolean isBase64;
String orientation;
if (json != null && !json.isEmpty()) { if (json != null && !json.isEmpty()) {
JSONObject jsonBody = new JSONObject(json); JSONObject jsonBody = new JSONObject(json);
...@@ -35,18 +36,20 @@ public class pdfRest { ...@@ -35,18 +36,20 @@ public class pdfRest {
fileName = jsonBody.optString("file_name", "pdf.pdf"); fileName = jsonBody.optString("file_name", "pdf.pdf");
isBase64 = jsonBody.optBoolean("base64"); isBase64 = jsonBody.optBoolean("base64");
background = jsonBody.has("background") ? jsonBody.getString("background") : null; background = jsonBody.has("background") ? jsonBody.getString("background") : null;
orientation = jsonBody.has("orientation") ? String.valueOf(jsonBody.get("orientation")) : null;
} else { } else {
html = params.get("html"); html = params.get("html");
fileName = params.getOrDefault("file_name", "pdf.pdf"); fileName = params.getOrDefault("file_name", "pdf.pdf");
isBase64 = Boolean.parseBoolean(params.get("base64")); isBase64 = Boolean.parseBoolean(params.get("base64"));
background = params.get("background"); background = params.get("background");
orientation = params.get("orientation");
} }
if (background != null && !background.startsWith("http") && !background.startsWith("data:")) { if (background != null && !background.startsWith("http") && !background.startsWith("data:")) {
background = "data:image/png;base64," + background; background = "data:image/png;base64," + background;
} }
byte[] bytes = pdfService.generatePdf(html, background); byte[] bytes = pdfService.generatePdf(html, background, PDFService.isLandscape(orientation));
if (isBase64) { if (isBase64) {
String base64 = commonUtils.byteToBase64(bytes); String base64 = commonUtils.byteToBase64(bytes);
......
...@@ -24,15 +24,20 @@ import java.io.IOException; ...@@ -24,15 +24,20 @@ import java.io.IOException;
public class PDFService { public class PDFService {
public byte[] generatePdf(String htmlContent, String backgroundUrl) throws Exception { public byte[] generatePdf(String htmlContent, String backgroundUrl) throws Exception {
return generatePdf(htmlContent, backgroundUrl, false);
}
public byte[] generatePdf(String htmlContent, String backgroundUrl, boolean landscape) throws Exception {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
PdfWriter writer = new PdfWriter(baos); PdfWriter writer = new PdfWriter(baos);
PdfDocument pdf = new PdfDocument(writer); PdfDocument pdf = new PdfDocument(writer);
pdf.setDefaultPageSize(PageSize.A4); pdf.setDefaultPageSize(landscape ? PageSize.A4.rotate() : PageSize.A4);
// 1. Creamos el estilo CSS para el fondo // 1. Creamos el estilo CSS para el fondo
// Usamos @page para que se aplique a todas las páginas del PDF // Usamos @page para que se aplique a todas las páginas del PDF
String backgroundStyle = "<style>" + String backgroundStyle = "<style>" +
"@page {" + "@page {" +
(landscape ? " size: A4 landscape;" : "") + // Horizontal solo si se solicita
" margin: 0;" + // Opcional: define márgenes si los necesitas " margin: 0;" + // Opcional: define márgenes si los necesitas
" background-image: url('" + backgroundUrl + "');" + " background-image: url('" + backgroundUrl + "');" +
" background-position: center;" + " background-position: center;" +
...@@ -58,4 +63,14 @@ public class PDFService { ...@@ -58,4 +63,14 @@ public class PDFService {
} }
} }
/**
* Interpreta el parámetro opcional de orientación. Si es nulo, vacío o desconocido
* se asume vertical (portrait).
*/
public static boolean isLandscape(String orientation) {
if (orientation == null) return false;
String value = orientation.trim().toLowerCase();
return value.equals("horizontal") || value.equals("landscape") || value.equals("true");
}
} }
\ No newline at end of file
package web.multitask.trismegistoservices;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import org.json.JSONObject;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import web.multitask.trismegistoservices.rest.pdfRest;
import web.multitask.trismegistoservices.services.PDFService;
import web.multitask.trismegistoservices.utils.CommonUtils;
import java.io.ByteArrayInputStream;
import java.util.Base64;
import static org.junit.jupiter.api.Assertions.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
class PdfOrientationTest {
private static final String HTML = "<html><body><h1>Prueba</h1></body></html>";
private PDFService pdfService;
private MockMvc mockMvc;
@BeforeEach
void setUp() {
pdfService = new PDFService();
mockMvc = MockMvcBuilders.standaloneSetup(new pdfRest(pdfService, new CommonUtils())).build();
}
private static Rectangle firstPageSize(byte[] pdfBytes) throws Exception {
try (PdfDocument doc = new PdfDocument(new PdfReader(new ByteArrayInputStream(pdfBytes)))) {
return doc.getFirstPage().getPageSize();
}
}
private static void assertPortrait(byte[] pdfBytes) throws Exception {
Rectangle size = firstPageSize(pdfBytes);
assertTrue(size.getHeight() > size.getWidth(), "Se esperaba vertical, fue " + size);
}
private static void assertLandscape(byte[] pdfBytes) throws Exception {
Rectangle size = firstPageSize(pdfBytes);
assertTrue(size.getWidth() > size.getHeight(), "Se esperaba horizontal, fue " + size);
}
// ---- isLandscape ----
@Test
void isLandscapeDefaultsToPortrait() {
assertFalse(PDFService.isLandscape(null));
assertFalse(PDFService.isLandscape(""));
assertFalse(PDFService.isLandscape("vertical"));
assertFalse(PDFService.isLandscape("portrait"));
assertFalse(PDFService.isLandscape("cualquier-cosa"));
assertFalse(PDFService.isLandscape("false"));
}
@Test
void isLandscapeAcceptsHorizontalValues() {
assertTrue(PDFService.isLandscape("horizontal"));
assertTrue(PDFService.isLandscape("HORIZONTAL"));
assertTrue(PDFService.isLandscape(" landscape "));
assertTrue(PDFService.isLandscape("true"));
}
// ---- servicio ----
@Test
void serviceDefaultIsPortrait() throws Exception {
assertPortrait(pdfService.generatePdf(HTML, null));
assertPortrait(pdfService.generatePdf(HTML, null, false));
}
@Test
void serviceLandscape() throws Exception {
assertLandscape(pdfService.generatePdf(HTML, null, true));
}
@Test
void serviceLandscapeWithBackground() throws Exception {
// PNG 1x1 transparente
String png = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==";
assertLandscape(pdfService.generatePdf(HTML, png, true));
assertPortrait(pdfService.generatePdf(HTML, png, false));
}
// ---- endpoint ----
private byte[] postJson(JSONObject body) throws Exception {
MvcResult result = mockMvc.perform(post("/pdf/public/html")
.contentType(MediaType.APPLICATION_JSON)
.content(body.toString()))
.andExpect(status().isOk())
.andReturn();
return result.getResponse().getContentAsByteArray();
}
@Test
void endpointJsonWithoutOrientationIsPortrait() throws Exception {
assertPortrait(postJson(new JSONObject().put("html", HTML)));
}
@Test
void endpointJsonHorizontal() throws Exception {
assertLandscape(postJson(new JSONObject().put("html", HTML).put("orientation", "horizontal")));
}
@Test
void endpointJsonVertical() throws Exception {
assertPortrait(postJson(new JSONObject().put("html", HTML).put("orientation", "vertical")));
}
@Test
void endpointJsonHorizontalBase64() throws Exception {
byte[] raw = postJson(new JSONObject().put("html", HTML).put("orientation", "landscape").put("base64", true));
JSONObject json = new JSONObject(new String(raw));
assertLandscape(Base64.getDecoder().decode(json.getString("base64")));
}
@Test
void endpointFormDataHorizontal() throws Exception {
MvcResult result = mockMvc.perform(multipart("/pdf/public/html")
.param("html", HTML)
.param("orientation", "horizontal"))
.andExpect(status().isOk())
.andReturn();
assertLandscape(result.getResponse().getContentAsByteArray());
}
@Test
void endpointFormDataWithoutOrientationIsPortrait() throws Exception {
MvcResult result = mockMvc.perform(multipart("/pdf/public/html")
.param("html", HTML))
.andExpect(status().isOk())
.andReturn();
assertPortrait(result.getResponse().getContentAsByteArray());
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment