diff --git a/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/PDAbstractContentStream.java b/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/PDAbstractContentStream.java index a919475fbf6..6c1a98b1b7d 100644 --- a/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/PDAbstractContentStream.java +++ b/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/PDAbstractContentStream.java @@ -1674,4 +1674,31 @@ private List applyGSUBRules(GsubWorker gsubWorker, ByteArrayOutputStrea return glyphIdsAfterGsub; } + + /** + * Does a length unit conversion from millimeters or inches (depending on user choice) to points. + * + * @param items Items that needs to be converted. + * @param unit_type Specifies desired length unit (mm or inch) for conversion. + * @throws IllegalArgumentException If desired length unit is not supported. + */ + public static final void convertUnit(List items, String unitType) + { + float multiplier = 1; + switch (unitType) { + case "mm": + multiplier = 1 / (10 * 2.54f) * 72; + break; + case "inch": + multiplier = 72; + break; + default: + throw new IllegalArgumentException( + "could not find the unit type: " + unitType); + } + + for (int i=0; i < items.size(); i++) { + items.set(i, items.get(i) * multiplier); + } + } } diff --git a/pdfbox/src/test/java/org/apache/pdfbox/pdmodel/TestPDPageContentStream.java b/pdfbox/src/test/java/org/apache/pdfbox/pdmodel/TestPDPageContentStream.java index d197a7ae864..0c19c521e66 100644 --- a/pdfbox/src/test/java/org/apache/pdfbox/pdmodel/TestPDPageContentStream.java +++ b/pdfbox/src/test/java/org/apache/pdfbox/pdmodel/TestPDPageContentStream.java @@ -17,8 +17,10 @@ package org.apache.pdfbox.pdmodel; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.IOException; +import java.util.Arrays; import java.util.List; import org.apache.pdfbox.contentstream.operator.Operator; import org.apache.pdfbox.contentstream.operator.OperatorName; @@ -167,4 +169,29 @@ void testCloseContract() throws IOException contentStream.close(); } } + + /** + * PDFBOX-4073: test implemented choosable coordinate-unitsystem + * Checks that unitconversion is done right. + * Arguably the test could be also in some other file + */ + @Test + void testUnitConversion() + { + List itemsMm = Arrays.asList(1.0f, 2.4f); + List itemsInch = Arrays.asList(1.0f, 2.4f); + List itemsInMm = Arrays.asList(1.0f /(10 * 2.54f) * 72, 2.4f /(10 * 2.54f) * 72); + List itemsInInch = Arrays.asList(1.0f * 72, 2.4f * 72); + + PDAbstractContentStream.convertUnit(itemsMm, "mm"); + PDAbstractContentStream.convertUnit(itemsInch, "inch"); + // Should be converted to millimeters + assertEquals(itemsInMm, itemsMm); + // Should be converted to inches + assertEquals(itemsInInch, itemsInch); + // Should throw IllegalArgumentException if the unit is not valid + assertThrows(IllegalArgumentException.class, () -> { + PDAbstractContentStream.convertUnit(itemsMm, "invalid_unit"); + }); + } }