com.openhtmltopdf.objects.pdf.MergeBackgroundPdfDrawer Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of openhtmltopdf-objects Show documentation
Show all versions of openhtmltopdf-objects Show documentation
Openhtmltopdf is a CSS 2.1 renderer written in Java. This artifact adds some basic object-tag implementation for the PDF output. Some of
this also works with the Java2D output, but the PDFOut is required.
package com.openhtmltopdf.objects.pdf;
import java.awt.*;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.cos.COSStream;
import org.apache.pdfbox.multipdf.LayerUtility;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
import org.apache.pdfbox.util.Charsets;
import org.w3c.dom.Element;
import com.openhtmltopdf.extend.OutputDevice;
import com.openhtmltopdf.pdfboxout.PdfBoxOutputDevice;
import com.openhtmltopdf.render.RenderingContext;
public class MergeBackgroundPdfDrawer extends PdfDrawerBase
{
@Override
public Map drawObject(Element e, double x, double y, double width, double height,
OutputDevice outputDevice, RenderingContext ctx, int dotsPerPixel)
{
/*
* We can only do something if this is a PDF.
*/
if (!(outputDevice instanceof PdfBoxOutputDevice))
return null;
PdfBoxOutputDevice pdfBoxOutputDevice = (PdfBoxOutputDevice) outputDevice;
try
{
LayerUtility layerUtility = new LayerUtility(pdfBoxOutputDevice.getWriter());
PDFormXObject pdFormXObject = importPageAsXForm(ctx,e, pdfBoxOutputDevice, layerUtility);
PDPage page = pdfBoxOutputDevice.getPage();
/*
* This ensures that the Contents of the page is a COSArray. The first entry in
* the array is just a save state (e.g. 'q'). We can override it to add the
* XForm.
*/
layerUtility.wrapInSaveRestore(page);
COSArray cosArray = (COSArray) page.getCOSObject()
.getDictionaryObject(COSName.CONTENTS);
COSStream saveStateAndPlacePageBackgroundStream = (COSStream) cosArray.get(0);
OutputStream saveAndPlaceStream = saveStateAndPlacePageBackgroundStream
.createOutputStream();
saveAndPlaceStream.write("q\n".getBytes(Charsets.US_ASCII));
COSName name = page.getResources().add(pdFormXObject);
name.writePDF(saveAndPlaceStream);
saveAndPlaceStream.write(' ');
saveAndPlaceStream.write("Do\n".getBytes(Charsets.US_ASCII));
saveAndPlaceStream.write("Q\n".getBytes(Charsets.US_ASCII));
saveAndPlaceStream.write("q\n".getBytes(Charsets.US_ASCII));
saveAndPlaceStream.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
return null;
}
}