Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelogs/4.0.1.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
* **Tagged annotations (PR #1804, port of #1617).** `PdfStructureElement.addAnnotation(PdfAnnotation)` references a link or another annotation from the structure tree, as PDF/UA requires. The structure tree root gets a `/ParentTreeNextKey` entry.
* **PDF/A extension schemas and Factur-X metadata (PR #1808).** `PdfWriter.addXmpSchema(XmpSchema, PdfAExtensionSchema.Schema)` adds custom XMP properties and the PDF/A extension schema that describes them to the metadata of `createXmpMetadata()`. `FacturXSchema` has the `fx` properties of ZUGFeRD and Factur-X invoices, so that a PDF/A-3 invoice with the invoice XML as an associated file passes veraPDF.
* **PDF/X-4 (PR #1809).** `PdfWriter.PDFX4` creates PDF/X-4 (ISO 15930-7:2010) documents for print production, with transparency, layers and ICC based colour. OpenPDF writes PDF 1.6, the PDF/X-4 identification and media management properties in the XMP metadata and `/GTS_PDFXVersion` and `/Trapped` in the info dictionary, and requires an output intent with an ICC profile and embedded fonts.
* **CMYK colour conversion (PR #1811).** `CmykColorConverter` converts RGB colours and images to the CMYK colour space of a printing condition with its ICC profile, for example ISOnewspaper26v4 or FOGRA39, and sets that profile as the output intent. An image with transparency gets a soft mask. This prepares content for PDF/X-4 and PDF/A with a CMYK output intent.

## 🛠 Bug Fixes

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
package org.openpdf.text.pdf;

import java.awt.Color;
import java.awt.Transparency;
import java.awt.color.ColorSpace;
import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.awt.image.DataBuffer;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Objects;
import javax.imageio.ImageIO;
import org.openpdf.text.BadElementException;
import org.openpdf.text.DocumentException;
import org.openpdf.text.ExceptionConverter;
import org.openpdf.text.Image;

/**
* Converts RGB colours and images to the CMYK colour space of a printing condition, with the ICC profile of that
* condition, for example ISOnewspaper26v4 for newspapers or Coated FOGRA39 for offset printing on coated paper.
* Print production formats such as PDF/X-4 with a CMYK output intent expect the content in that colour space, see
* {@link #setOutputIntent(PdfWriter, String, String)}.
* <p>
* The conversion uses the colour management of the JDK (Little CMS) with the default rendering intent of the profile,
* usually perceptual. Colours of images are first converted to sRGB, so images with an embedded ICC profile, such as
* Adobe RGB, are converted correctly.
* <pre>{@code
* CmykColorConverter converter = new CmykColorConverter(ICC_Profile.getInstance(newspaperProfileBytes));
* writer.setPDFXConformance(PdfWriter.PDFX4);
* document.open();
* converter.setOutputIntent(writer, "ISOnewspaper26v4", "ISO 12647-3:2013, Newspaper");
* document.add(converter.toCmykImage(photoBytes));
* cb.setColorFill(converter.toCmyk(new Color(200, 30, 30)));
* }</pre>
*/
public class CmykColorConverter {

private static final int RGB_COMPONENTS = 3;
private static final int CMYK_COMPONENTS = 4;
private static final float MAX_USHORT = 65535f;
private static final int MAX_BYTE = 255;

private final ICC_Profile profile;
private final ICC_ColorSpace cmykColorSpace;
private final ColorSpace srgb = ColorSpace.getInstance(ColorSpace.CS_sRGB);

/**
* Creates a converter to the colour space of a CMYK profile.
*
* @param cmykProfile the ICC profile of the printing condition
* @throws IllegalArgumentException if the profile is not a CMYK profile
*/
public CmykColorConverter(ICC_Profile cmykProfile) {
Objects.requireNonNull(cmykProfile, "cmykProfile");
if (cmykProfile.getColorSpaceType() != ColorSpace.TYPE_CMYK) {
throw new IllegalArgumentException("The ICC profile is not a CMYK profile.");
}
this.profile = cmykProfile;
this.cmykColorSpace = new ICC_ColorSpace(cmykProfile);
}

/**
* Gets the CMYK profile.
*
* @return the ICC profile of the printing condition
*/
public ICC_Profile getProfile() {
return profile;
}

/**
* Sets the output intent of the document to the CMYK profile of this converter, so that the converted colours are
* interpreted for the printing condition. For PDF/X the output intent is a {@code GTS_PDFX} intent, for PDF/A a
* {@code GTS_PDFA1} intent.
*
* @param writer the writer
* @param outputConditionIdentifier the identifier of the printing condition, for example
* {@code ISOnewspaper26v4} or {@code FOGRA39}
* @param info a description of the printing condition, or {@code null}
* @throws IOException if the profile cannot be written
*/
public void setOutputIntent(PdfWriter writer, String outputConditionIdentifier, String info)
throws IOException {
writer.setOutputIntents(outputConditionIdentifier, null, "http://www.color.org", info, profile);
}

/**
* Converts a colour to CMYK. The alpha value of the colour is kept.
*
* @param color the colour, in sRGB
* @return the colour in the CMYK colour space of the profile
*/
public CMYKColor toCmyk(Color color) {
Objects.requireNonNull(color, "color");
if (color instanceof CMYKColor cmykColor) {
return cmykColor;
}
WritableRaster rgb = Raster.createInterleavedRaster(DataBuffer.TYPE_USHORT, 1, 1, RGB_COMPONENTS, null);
rgb.setPixel(0, 0, new int[]{color.getRed() * 257, color.getGreen() * 257, color.getBlue() * 257});
WritableRaster cmyk = Raster.createInterleavedRaster(DataBuffer.TYPE_USHORT, 1, 1, CMYK_COMPONENTS, null);
new ColorConvertOp(srgb, cmykColorSpace, null).filter(rgb, cmyk);
int[] values = cmyk.getPixel(0, 0, (int[]) null);
return new CMYKColor(values[0] / MAX_USHORT, values[1] / MAX_USHORT, values[2] / MAX_USHORT,
values[3] / MAX_USHORT, color.getAlpha() / (float) MAX_BYTE);
}

/**
* Reads an image file, for example a PNG or JPEG file, and converts it to CMYK.
*
* @param imageFile the bytes of the image file
* @return the image in the CMYK colour space of the profile, with a soft mask if the image has transparency
* @throws IOException if the image cannot be read
* @throws BadElementException if the image cannot be created
*/
public Image toCmykImage(byte[] imageFile) throws IOException, BadElementException {
BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageFile));
if (image == null) {
throw new IOException("The image format is not supported.");
}
return toCmykImage(image);
}

/**
* Converts an image to CMYK.
*
* @param image the image
* @return the image in the CMYK colour space of the profile, with a soft mask if the image has transparency
* @throws BadElementException if the image cannot be created
*/
public Image toCmykImage(java.awt.Image image) throws BadElementException {
BufferedImage source = toBufferedImage(image);
int width = source.getWidth();
int height = source.getHeight();
int[] argb = source.getRGB(0, 0, width, height, null, 0, width);

byte[] rgb = new byte[argb.length * RGB_COMPONENTS];
byte[] alpha = new byte[argb.length];
boolean transparent = false;
for (int i = 0; i < argb.length; i++) {
int pixel = argb[i];
rgb[i * RGB_COMPONENTS] = (byte) (pixel >> 16);
rgb[i * RGB_COMPONENTS + 1] = (byte) (pixel >> 8);
rgb[i * RGB_COMPONENTS + 2] = (byte) pixel;
alpha[i] = (byte) (pixel >>> 24);
transparent |= (pixel >>> 24) != MAX_BYTE;
}

WritableRaster rgbRaster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, width, height, RGB_COMPONENTS,
null);
rgbRaster.setDataElements(0, 0, width, height, rgb);
WritableRaster cmykRaster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, width, height,
CMYK_COMPONENTS, null);
new ColorConvertOp(srgb, cmykColorSpace, null).filter(rgbRaster, cmykRaster);
byte[] cmyk = (byte[]) cmykRaster.getDataElements(0, 0, width, height, null);

Image result = Image.getInstance(width, height, CMYK_COMPONENTS, 8, cmyk);
if (transparent && source.getTransparency() != Transparency.OPAQUE) {
Image mask = Image.getInstance(width, height, 1, 8, alpha);
try {
mask.makeMask();
result.setImageMask(mask);
} catch (DocumentException e) {
throw new ExceptionConverter(e);
}
}
return result;
}

private static BufferedImage toBufferedImage(java.awt.Image image) {
Objects.requireNonNull(image, "image");
if (image instanceof BufferedImage bufferedImage) {
return bufferedImage;
}
int width = image.getWidth(null);
int height = image.getHeight(null);
if (width <= 0 || height <= 0) {
throw new IllegalArgumentException("The image is not loaded or has no size.");
}
BufferedImage buffered = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
java.awt.Graphics2D g = buffered.createGraphics();
try {
g.drawImage(image, 0, 0, null);
} finally {
g.dispose();
}
return buffered;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
package org.openpdf.text.pdf;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.within;

import java.awt.Color;
import java.awt.color.ColorSpace;
import java.awt.color.ICC_Profile;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.imageio.ImageIO;
import org.junit.jupiter.api.Test;
import org.openpdf.text.Document;
import org.openpdf.text.Font;
import org.openpdf.text.Image;
import org.openpdf.text.PageSize;
import org.openpdf.text.Paragraph;
import org.verapdf.gf.model.GFModelParser;
import org.verapdf.pdfa.PDFAValidator;
import org.verapdf.pdfa.flavours.PDFAFlavour;
import org.verapdf.pdfa.results.TestAssertion;
import org.verapdf.pdfa.results.ValidationResult;
import org.verapdf.pdfa.validation.validators.ValidatorFactory;

class CmykColorConverterTest {

private static final String FONT = "/fonts/liberation/LiberationSerif-Regular.ttf";
private static final float TOLERANCE = 0.15f;

private final CmykColorConverter converter = new CmykColorConverter(TestCmykProfile.create());

@Test
void profileMustBeCmyk() {
assertThatThrownBy(() -> new CmykColorConverter(ICC_Profile.getInstance(ColorSpace.CS_sRGB)))

Check warning on line 39 in openpdf-core/src/test/java/org/openpdf/text/pdf/CmykColorConverterTest.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor the code of the lambda to have only one invocation possibly throwing a runtime exception.

See more on https://sonarcloud.io/project/issues?id=LibrePDF_OpenPDF&issues=AaI4wF5La0OLH1aYM8Pv&open=AaI4wF5La0OLH1aYM8Pv&pullRequest=1811
.isInstanceOf(IllegalArgumentException.class);
}

@Test
void whiteHasNoInk() {
assertCmyk(converter.toCmyk(Color.WHITE), 0, 0, 0, 0);
}

@Test
void blackIsPrintedWithBlackInk() {
CMYKColor black = converter.toCmyk(Color.BLACK);

assertThat(black.getBlack()).isGreaterThan(0.85f);
}

@Test
void redIsMagentaAndYellow() {
assertCmyk(converter.toCmyk(Color.RED), 0, 1, 1, 0);
}

@Test
void alphaIsKeptAndCmykColorIsUnchanged() {
assertThat(converter.toCmyk(new Color(0, 0, 255, 128)).getAlpha()).isEqualTo(128);
CMYKColor cmyk = new CMYKColor(0.1f, 0.2f, 0.3f, 0.4f);
assertThat(converter.toCmyk(cmyk)).isSameAs(cmyk);
}

@Test
void imageIsConvertedToCmyk() throws Exception {
BufferedImage rgb = new BufferedImage(2, 1, BufferedImage.TYPE_INT_RGB);
rgb.setRGB(0, 0, Color.RED.getRGB());
rgb.setRGB(1, 0, Color.WHITE.getRGB());

Image cmyk = converter.toCmykImage(rgb);

assertThat(cmyk.getColorspace()).isEqualTo(4);
assertThat(cmyk.getBpc()).isEqualTo(8);
assertThat(cmyk.getImageMask()).isNull();
byte[] data = cmyk.getRawData();
assertCmyk(new CMYKColor(data[0] & 0xFF, data[1] & 0xFF, data[2] & 0xFF, data[3] & 0xFF), 0, 1, 1, 0);
assertCmyk(new CMYKColor(data[4] & 0xFF, data[5] & 0xFF, data[6] & 0xFF, data[7] & 0xFF), 0, 0, 0, 0);
}

@Test
void transparencyBecomesASoftMask() throws Exception {
BufferedImage argb = new BufferedImage(2, 1, BufferedImage.TYPE_INT_ARGB);
argb.setRGB(0, 0, Color.RED.getRGB());
argb.setRGB(1, 0, new Color(0, 0, 255, 0).getRGB());

Image cmyk = converter.toCmykImage(argb);

Image mask = cmyk.getImageMask();
assertThat(mask).isNotNull();
assertThat(mask.getRawData()).containsExactly((byte) 255, (byte) 0);
}

@Test
void pngFileIsConverted() throws Exception {
Image cmyk = converter.toCmykImage(readResource("/GitHub-Mark-32px.png"));

BufferedImage original = ImageIO.read(new ByteArrayInputStream(readResource("/GitHub-Mark-32px.png")));
assertThat(cmyk.getColorspace()).isEqualTo(4);
assertThat((int) cmyk.getWidth()).isEqualTo(original.getWidth());
assertThat(cmyk.getImageMask()).isNotNull();
}

@Test
void unsupportedImageFileIsRejected() {
assertThatThrownBy(() -> converter.toCmykImage(new byte[]{1, 2, 3}))
.isInstanceOf(IOException.class);
}

@Test
void pdfA2bWithCmykOutputIntentAndConvertedContentIsCompliant() throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (Document document = new Document(PageSize.A4)) {
PdfWriter writer = PdfWriter.getInstance(document, out);
writer.setPDFXConformance(PdfWriter.PDFA2B);
document.addTitle("CMYK test");
document.open();
converter.setOutputIntent(writer, "OpenPDF test CMYK", "Test printing condition");

BaseFont font = BaseFont.createFont("LiberationSerif-Regular.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED,
true, readResource(FONT), null);
document.add(new Paragraph("Converted to CMYK",
new Font(font, 14, Font.NORMAL, converter.toCmyk(new Color(200, 30, 30)))));
document.add(converter.toCmykImage(readResource("/imageTest/ImageTest.jpg")));
document.add(converter.toCmykImage(readResource("/GitHub-Mark-32px.png")));
writer.createXmpMetadata();
}

try (PdfReader reader = new PdfReader(out.toByteArray())) {
PdfDictionary outputIntent = reader.getCatalog().getAsArray(PdfName.OUTPUTINTENTS).getAsDict(0);
assertThat(outputIntent.getAsName(PdfName.S)).isEqualTo(PdfName.GTS_PDFA1);
assertThat(outputIntent.get(PdfName.DESTOUTPUTPROFILE)).isNotNull();
}
assertThat(validate(out.toByteArray(), PDFAFlavour.PDFA_2_B)).as("veraPDF PDF/A-2b violations").isEmpty();
}

private static void assertCmyk(CMYKColor color, float c, float m, float y, float k) {
assertThat(color.getCyan()).as("cyan").isCloseTo(c, within(TOLERANCE));
assertThat(color.getMagenta()).as("magenta").isCloseTo(m, within(TOLERANCE));
assertThat(color.getYellow()).as("yellow").isCloseTo(y, within(TOLERANCE));
assertThat(color.getBlack()).as("black").isCloseTo(k, within(TOLERANCE));
}

private static List<String> validate(byte[] pdf, PDFAFlavour flavour) throws Exception {
try (GFModelParser parser = GFModelParser.createModelWithFlavour(new ByteArrayInputStream(pdf), flavour)) {
PDFAValidator validator = ValidatorFactory.createValidator(flavour, false, 100);
ValidationResult result = validator.validate(parser);
return result.getTestAssertions().stream()
.filter(assertion -> assertion.getStatus() == TestAssertion.Status.FAILED)
.map(assertion -> assertion.getRuleId().getClause() + "-" + assertion.getRuleId().getTestNumber()
+ ": " + assertion.getMessage())
.distinct()
.toList();
}
}

private static byte[] readResource(String name) throws IOException {
try (InputStream in = CmykColorConverterTest.class.getResourceAsStream(name)) {
assertThat(in).as(name).isNotNull();
return in.readAllBytes();
}
}
}
Loading
Loading