aboutsummaryrefslogtreecommitdiffstats
path: root/src/java/org/apache/fop/pdf/PDFMetadata.java
blob: 9af42e8b62bffb65302997539177976338ccf6ec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
/*
 * Copyright 2006 The Apache Software Foundation.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* $Id$ */
 
package org.apache.fop.pdf;

import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.fop.fo.ElementMapping;
import org.apache.fop.fo.extensions.xmp.XMPConstants;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * Special PDFStream for Metadata.
 * @since PDF 1.4
 */
public class PDFMetadata extends PDFStream {
    
    private Document xmpMetadata;
    private boolean readOnly = true;

    /** @see org.apache.fop.pdf.PDFObject#PDFObject() */
    public PDFMetadata(Document xmp, boolean readOnly) {
        super();
        if (xmp == null) {
            throw new NullPointerException(
                    "DOM Document representing the metadata must no be null");
        }
        this.xmpMetadata = xmp;
        this.readOnly = readOnly;
    }

    /** @see org.apache.fop.pdf.AbstractPDFStream#setupFilterList() */
    protected void setupFilterList() {
        if (!getFilterList().isInitialized()) {
            getFilterList().addDefaultFilters(
                getDocumentSafely().getFilterMap(), 
                PDFFilterList.METADATA_FILTER);
        }
        super.setupFilterList();
    }

    /** @see org.apache.fop.pdf.AbstractPDFStream#allowEncryption() */
    protected boolean allowEncryption() {
        return false; //XMP metadata packet must be scannable by non PDF-compatible readers
    }

    /**
     * overload the base object method so we don't have to copy
     * byte arrays around so much
     * @see org.apache.fop.pdf.PDFObject#output(OutputStream)
     */
    protected int output(java.io.OutputStream stream)
                throws java.io.IOException {
        int length = super.output(stream);
        this.xmpMetadata = null; //Release DOM when it's not used anymore
        return length;
    }
    
    /** @see org.apache.fop.pdf.AbstractPDFStream#outputRawStreamData(java.io.OutputStream) */
    protected void outputRawStreamData(OutputStream out) throws IOException {
        final String encoding = "UTF-8";
        out.write("<?xpacket begin=\"\uFEFF\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n"
                .getBytes(encoding));
        try {
            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
            transformer.setOutputProperty(OutputKeys.INDENT, "no");
            DOMSource src = new DOMSource(this.xmpMetadata);
            StreamResult res = new StreamResult(out);
            transformer.transform(src, res);
        } catch (TransformerConfigurationException e) {
            throw new IOException("Error setting up Transformer for XMP stream serialization: " 
                    + e.getMessage());
        } catch (TransformerException e) {
            throw new IOException("Error while serializing XMP stream: " 
                    + e.getMessage());
        }
        if (readOnly) {
            out.write("\n<?xpacket end=\"r\"?>".getBytes(encoding));
        } else {
            //Create padding string (40 * 101 characters is more or less the recommended 4KB)
            StringBuffer sb = new StringBuffer(101);
            sb.append('\n');
            for (int i = 0; i < 100; i++) {
                sb.append(" ");
            }
            byte[] padding = sb.toString().getBytes(encoding);
            for (int i = 0; i < 40; i++) {
                out.write(padding);
            }
            out.write("\n<?xpacket end=\"w\"?>".getBytes(encoding));
        }
    }
    
    /** @see org.apache.fop.pdf.AbstractPDFStream#buildStreamDict(String) */
    protected String buildStreamDict(String lengthEntry) {
        final String filterEntry = getFilterList().buildFilterDictEntries();
        if (getDocumentSafely().getPDFAMode().isPDFA1LevelB() 
                && filterEntry != null && filterEntry.length() > 0) {
            throw new PDFConformanceException(
                    "The Filter key is prohibited when PDF/A-1 is active");
        }
        final StringBuffer sb = new StringBuffer(128);
        sb.append(getObjectID());
        sb.append("<< ");
        sb.append("/Type /Metadata");
        sb.append("\n/Subtype /XML");
        sb.append("\n/Length " + lengthEntry);
        sb.append("\n" + filterEntry);
        sb.append("\n>>\n");
        return sb.toString();
    }

    /**
     * Creates an XMP document based on the settings on the PDF Document.
     * @param pdfDoc the PDF Document
     * @return a DOM document representing the requested XMP metadata
     */
    public static Document createXMPFromUserAgent(PDFDocument pdfDoc) {
        DOMImplementation domImplementation = ElementMapping.getDefaultDOMImplementation();
        Document doc = domImplementation.createDocument(
                XMPConstants.XMP_NAMESPACE, "x:xmpmeta", null);
        Element rdf = doc.createElementNS(XMPConstants.RDF_NAMESPACE, "rdf:RDF");
        doc.getDocumentElement().appendChild(rdf);
        
        Element desc, el;
        PDFInfo info = pdfDoc.getInfo();
        DateFormat pseudoISO8601DateFormat = new SimpleDateFormat(
            "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'");
        pseudoISO8601DateFormat.setTimeZone(TimeZone.getTimeZone("GMT+00"));
        
        //Set creation date if not available, yet
        if (info.getCreationDate() == null) {
            Date d = new Date();
            info.setCreationDate(d);
        }

        final String xmlns = "http://www.w3.org/2000/xmlns/";
        
        //Dublin Core
        desc = doc.createElementNS(XMPConstants.RDF_NAMESPACE, "rdf:Description");
        desc.setAttribute("about", "");
        desc.setAttributeNS(xmlns, "xmlns:dc", XMPConstants.DUBLIN_CORE_NAMESPACE);
        rdf.appendChild(desc);
        if (info.getAuthor() != null) {
            el = doc.createElementNS(XMPConstants.DUBLIN_CORE_NAMESPACE, "dc:creator");
            desc.appendChild(el);
            el.appendChild(doc.createTextNode(info.getAuthor()));
        }
        if (info.getTitle() != null) {
            el = doc.createElementNS(XMPConstants.DUBLIN_CORE_NAMESPACE, "dc:title");
            desc.appendChild(el);
            el.appendChild(doc.createTextNode(info.getTitle()));
        }
        if (info.getSubject() != null) {
            el = doc.createElementNS(XMPConstants.DUBLIN_CORE_NAMESPACE, "dc:subject");
            desc.appendChild(el);
            el.appendChild(doc.createTextNode(info.getSubject()));
        }
        el = doc.createElementNS(XMPConstants.DUBLIN_CORE_NAMESPACE, "dc:date");
        desc.appendChild(el);
        el.appendChild(doc.createTextNode(pseudoISO8601DateFormat.format(info.getCreationDate())));
        
        //XMP Basic Schema
        desc = doc.createElementNS(XMPConstants.RDF_NAMESPACE, "rdf:Description");
        desc.setAttribute("about", "");
        desc.setAttributeNS(xmlns, "xmlns:xmp", XMPConstants.XMP_BASIC_NAMESPACE);
        rdf.appendChild(desc);
        el = doc.createElementNS(XMPConstants.XMP_BASIC_NAMESPACE, "xmp:createDate");
        desc.appendChild(el);
        el.appendChild(doc.createTextNode(pseudoISO8601DateFormat.format(info.getCreationDate())));
        if (info.getCreator() != null) {
            el = doc.createElementNS(XMPConstants.XMP_BASIC_NAMESPACE, "xmp:creatorTool");
            desc.appendChild(el);
            el.appendChild(doc.createTextNode(info.getCreator()));
        }
        
        //Adobe PDF Schema
        desc = doc.createElementNS(XMPConstants.RDF_NAMESPACE, "rdf:Description");
        desc.setAttribute("about", "");
        desc.setAttributeNS(xmlns, "xmlns:pdf", XMPConstants.ADOBE_PDF_NAMESPACE);
        rdf.appendChild(desc);
        if (info.getKeywords() != null) {
            el = doc.createElementNS(XMPConstants.ADOBE_PDF_NAMESPACE, "pdf:Keywords");
            desc.appendChild(el);
            el.appendChild(doc.createTextNode(info.getKeywords()));
        }
        if (info.getProducer() != null) {
            el = doc.createElementNS(XMPConstants.ADOBE_PDF_NAMESPACE, "pdf:Producer");
            desc.appendChild(el);
            el.appendChild(doc.createTextNode(info.getProducer()));
        }
        el = doc.createElementNS(XMPConstants.ADOBE_PDF_NAMESPACE, "pdf:PDFVersion");
        desc.appendChild(el);
        el.appendChild(doc.createTextNode(pdfDoc.getPDFVersionString()));
        
        return doc;
    }
    
    
}