From 698a70e6a84cf7c0db667e9d9e021b4c34c85a3e Mon Sep 17 00:00:00 2001 From: m-holger Date: Wed, 24 May 2023 16:28:17 +0100 Subject: Code tidy - reflow comments and strings --- include/qpdf/Buffer.hh | 29 +- include/qpdf/JSON.hh | 235 +++--- include/qpdf/Pipeline.hh | 69 +- include/qpdf/Pl_Buffer.hh | 47 +- include/qpdf/QPDF.hh | 732 +++++++----------- include/qpdf/QPDFAcroFormDocumentHelper.hh | 234 +++--- include/qpdf/QPDFExc.hh | 37 +- include/qpdf/QPDFFormFieldObjectHelper.hh | 154 ++-- include/qpdf/QPDFJob.hh | 225 +++--- include/qpdf/QPDFObjectHandle.hh | 1158 +++++++++++----------------- include/qpdf/QPDFPageObjectHelper.hh | 440 +++++------ include/qpdf/QPDFTokenizer.hh | 106 ++- 12 files changed, 1415 insertions(+), 2051 deletions(-) (limited to 'include') diff --git a/include/qpdf/Buffer.hh b/include/qpdf/Buffer.hh index ab92bd53..719a6bd5 100644 --- a/include/qpdf/Buffer.hh +++ b/include/qpdf/Buffer.hh @@ -2,22 +2,19 @@ // // This file is part of qpdf. // -// 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 +// 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. +// 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. // -// Versions of qpdf prior to version 7 were released under the terms -// of version 2.0 of the Artistic License. At your option, you may -// continue to consider qpdf to be licensed under those terms. Please -// see the manual for additional information. +// Versions of qpdf prior to version 7 were released under the terms of version 2.0 of the Artistic +// License. At your option, you may continue to consider qpdf to be licensed under those terms. +// Please see the manual for additional information. #ifndef BUFFER_HH #define BUFFER_HH @@ -34,13 +31,13 @@ class Buffer QPDF_DLL Buffer(); - // Create a Buffer object whose memory is owned by the class and - // will be freed when the Buffer object is destroyed. + // Create a Buffer object whose memory is owned by the class and will be freed when the Buffer + // object is destroyed. QPDF_DLL Buffer(size_t size); - // Create a Buffer object whose memory is owned by the caller and - // will not be freed when the Buffer is destroyed. + // Create a Buffer object whose memory is owned by the caller and will not be freed when the + // Buffer is destroyed. QPDF_DLL Buffer(unsigned char* buf, size_t size); diff --git a/include/qpdf/JSON.hh b/include/qpdf/JSON.hh index 00f78112..ce37ef50 100644 --- a/include/qpdf/JSON.hh +++ b/include/qpdf/JSON.hh @@ -2,38 +2,31 @@ // // This file is part of qpdf. // -// 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 +// 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. +// 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. // -// Versions of qpdf prior to version 7 were released under the terms -// of version 2.0 of the Artistic License. At your option, you may -// continue to consider qpdf to be licensed under those terms. Please -// see the manual for additional information. +// Versions of qpdf prior to version 7 were released under the terms of version 2.0 of the Artistic +// License. At your option, you may continue to consider qpdf to be licensed under those terms. +// Please see the manual for additional information. #ifndef JSON_HH #define JSON_HH -// This is a simple JSON serializer and parser, primarily designed for -// serializing QPDF Objects as JSON. While it may work as a -// general-purpose JSON parser/serializer, there are better options. -// JSON objects contain their data as smart pointers. When one JSON object -// is added to another, this pointer is copied. This means you can -// create temporary JSON objects on the stack, add them to other -// objects, and let them go out of scope safely. It also means that if -// a JSON object is added in more than one place, all copies -// share the underlying data. This makes them similar in structure and -// behavior to QPDFObjectHandle and may feel natural within the QPDF -// codebase, but it is also a good reason not to use this as a -// general-purpose JSON package. +// This is a simple JSON serializer and parser, primarily designed for serializing QPDF Objects as +// JSON. While it may work as a general-purpose JSON parser/serializer, there are better options. +// JSON objects contain their data as smart pointers. When one JSON object is added to another, this +// pointer is copied. This means you can create temporary JSON objects on the stack, add them to +// other objects, and let them go out of scope safely. It also means that if a JSON object is added +// in more than one place, all copies share the underlying data. This makes them similar in +// structure and behavior to QPDFObjectHandle and may feel natural within the QPDF codebase, but it +// is also a good reason not to use this as a general-purpose JSON package. #include #include // unused -- remove in qpdf 12 (see #785) @@ -61,71 +54,60 @@ class JSON QPDF_DLL std::string unparse() const; - // Write the JSON object through a pipeline. The `depth` parameter - // specifies how deeply nested this is in another JSON structure, - // which makes it possible to write clean-looking JSON + // Write the JSON object through a pipeline. The `depth` parameter specifies how deeply nested + // this is in another JSON structure, which makes it possible to write clean-looking JSON // incrementally. QPDF_DLL void write(Pipeline*, size_t depth = 0) const; // Helper methods for writing JSON incrementally. // - // "first" -- Several methods take a `bool& first` parameter. The - // open methods always set it to true, and the methods to output - // items always set it to false. This way, the item and close - // methods can always know whether or not a first item is being - // written. The intended mode of operation is to start with a new - // `bool first = true` each time a new container is opened and - // to pass that `first` through to all the methods that are - // called to add top-level items to the container as well as to - // close the container. This lets the JSON object use it to keep - // track of when it's writing a first object and when it's not. If - // incrementally writing multiple levels of depth, a new `first` - // should used for each new container that is opened. + // "first" -- Several methods take a `bool& first` parameter. The open methods always set it to + // true, and the methods to output items always set it to false. This way, the item and close + // methods can always know whether or not a first item is being written. The intended mode of + // operation is to start with a new `bool first = true` each time a new container is opened and + // to pass that `first` through to all the methods that are called to add top-level items to the + // container as well as to close the container. This lets the JSON object use it to keep track + // of when it's writing a first object and when it's not. If incrementally writing multiple + // levels of depth, a new `first` should used for each new container that is opened. // - // "depth" -- Indicate the level of depth. This is used for - // consistent indentation. When writing incrementally, whenever - // you call a method to add an item to a container, the value of - // `depth` should be one more than whatever value is passed to the - // container open and close methods. + // "depth" -- Indicate the level of depth. This is used for consistent indentation. When writing + // incrementally, whenever you call a method to add an item to a container, the value of `depth` + // should be one more than whatever value is passed to the container open and close methods. // Open methods ignore the value of first and set it to false QPDF_DLL static void writeDictionaryOpen(Pipeline*, bool& first, size_t depth = 0); QPDF_DLL static void writeArrayOpen(Pipeline*, bool& first, size_t depth = 0); - // Close methods don't modify first. A true value indicates that - // we are closing an empty object. + // Close methods don't modify first. A true value indicates that we are closing an empty object. QPDF_DLL static void writeDictionaryClose(Pipeline*, bool first, size_t depth = 0); QPDF_DLL static void writeArrayClose(Pipeline*, bool first, size_t depth = 0); - // The item methods use the value of first to determine if this is - // the first item and always set it to false. + // The item methods use the value of first to determine if this is the first item and always set + // it to false. QPDF_DLL static void writeDictionaryItem( Pipeline*, bool& first, std::string const& key, JSON const& value, size_t depth = 0); - // Write just the key of a new dictionary item, useful if writing - // nested structures. Calls writeNext. + // Write just the key of a new dictionary item, useful if writing nested structures. Calls + // writeNext. QPDF_DLL static void writeDictionaryKey(Pipeline* p, bool& first, std::string const& key, size_t depth = 0); QPDF_DLL static void writeArrayItem(Pipeline*, bool& first, JSON const& element, size_t depth = 0); - // If writing nested structures incrementally, call writeNext - // before opening a new array or container in the midst of an - // existing one. The `first` you pass to writeNext should be the - // one for the parent object. The depth should be the one for the - // child object. Then start a new `first` for the nested item. - // Note that writeDictionaryKey and writeArrayItem call writeNext - // for you, so this is most important when writing subsequent - // items or container openers to an array. + // If writing nested structures incrementally, call writeNext before opening a new array or + // container in the midst of an existing one. The `first` you pass to writeNext should be the + // one for the parent object. The depth should be the one for the child object. Then start a new + // `first` for the nested item. Note that writeDictionaryKey and writeArrayItem call writeNext + // for you, so this is most important when writing subsequent items or container openers to an + // array. QPDF_DLL static void writeNext(Pipeline* p, bool& first, size_t depth = 0); - // The JSON spec calls dictionaries "objects", but that creates - // too much confusion when referring to instances of the JSON - // class. + // The JSON spec calls dictionaries "objects", but that creates too much confusion when + // referring to instances of the JSON class. QPDF_DLL static JSON makeDictionary(); // addDictionaryMember returns the newly added item. @@ -149,10 +131,9 @@ class JSON QPDF_DLL static JSON makeNull(); - // A blob serializes as a string. The function will be called by - // JSON with a pipeline and should write binary data to the - // pipeline but not call finish(). JSON will call finish() at the - // right time. + // A blob serializes as a string. The function will be called by JSON with a pipeline and should + // write binary data to the pipeline but not call finish(). JSON will call finish() at the right + // time. QPDF_DLL static JSON makeBlob(std::function); @@ -162,11 +143,9 @@ class JSON QPDF_DLL bool isDictionary() const; - // If the key is already in the dictionary, return true. - // Otherwise, mark it as seen and return false. This is primarily - // intended to be used by the parser to detect duplicate keys when - // the reactor blocks them from being added to the final - // dictionary. + // If the key is already in the dictionary, return true. Otherwise, mark it as seen and return + // false. This is primarily intended to be used by the parser to detect duplicate keys when the + // reactor blocks them from being added to the final dictionary. QPDF_DLL bool checkDictionaryKeySeen(std::string const& key); @@ -187,45 +166,35 @@ class JSON QPDF_DLL bool forEachArrayItem(std::function fn) const; - // Check this JSON object against a "schema". This is not a schema - // according to any standard. It's just a template of what the - // JSON is supposed to contain. The checking does the following: + // Check this JSON object against a "schema". This is not a schema according to any standard. + // It's just a template of what the JSON is supposed to contain. The checking does the + // following: // - // * The schema is a nested structure containing dictionaries, - // single-element arrays, and strings only. - // * Recursively walk the schema. In the items below, "schema - // object" refers to an object in the schema, and "checked - // object" refers to the corresponding part of the object - // being checked. - // * If the schema object is a dictionary, the checked object - // must have a dictionary in the same place with the same - // keys. If flags contains f_optional, a key in the schema - // does not have to be present in the object. Otherwise, all - // keys have to be present. Any key in the object must be - // present in the schema. - // * If the schema object is an array of length 1, the checked - // object may either be a single item or an array of items. - // The single item or each element of the checked object's - // array is validated against the single element of the - // schema's array. The rationale behind this logic is that a - // single element may appear wherever the schema allows a - // variable-length array. This makes it possible to start - // allowing an array in the future where a single element was - // previously required without breaking backward - // compatibility. - // * If the schema object is an array of length > 1, the checked - // object must be an array of the same length. In this case, - // each element of the checked object array is validated + // * The schema is a nested structure containing dictionaries, single-element arrays, and + // strings only. + // * Recursively walk the schema. In the items below, "schema object" refers to an object in + // the schema, and "checked object" refers to the corresponding part of the object being + // checked. + // * If the schema object is a dictionary, the checked object must have a dictionary in the + // same place with the same keys. If flags contains f_optional, a key in the schema does not + // have to be present in the object. Otherwise, all keys have to be present. Any key in the + // object must be present in the schema. + // * If the schema object is an array of length 1, the checked object may either be a single + // item or an array of items. The single item or each element of the checked object's + // array is validated against the single element of the schema's array. The rationale behind + // this logic is that a single element may appear wherever the schema allows a + // variable-length array. This makes it possible to start allowing an array in the future + // where a single element was previously required without breaking backward compatibility. + // * If the schema object is an array of length > 1, the checked object must be an array of + // the same length. In this case, each element of the checked object array is validated // against the corresponding element of the schema array. - // * Otherwise, the value must be a string whose value is a - // description of the object's corresponding value, which may - // have any type. + // * Otherwise, the value must be a string whose value is a description of the object's + // corresponding value, which may have any type. // - // QPDF's JSON output conforms to certain strict compatibility - // rules as discussed in the manual. The idea is that a JSON - // structure created manually in qpdf.cc doubles as both JSON help - // information and a schema for validating the JSON that qpdf - // generates. Any discrepancies are a bug in qpdf. + // QPDF's JSON output conforms to certain strict compatibility rules as discussed in the manual. + // The idea is that a JSON structure created manually in qpdf.cc doubles as both JSON help + // information and a schema for validating the JSON that qpdf generates. Any discrepancies are a + // bug in qpdf. // // Flags is a bitwise or of values from check_flags_e. enum check_flags_e { @@ -239,9 +208,8 @@ class JSON QPDF_DLL bool checkSchema(JSON schema, std::list& errors); - // An pointer to a Reactor class can be passed to parse, which - // will enable the caller to react to incremental events in the - // construction of the JSON object. This makes it possible to + // An pointer to a Reactor class can be passed to parse, which will enable the caller to react + // to incremental events in the construction of the JSON object. This makes it possible to // implement SAX-like handling of very large JSON objects. class QPDF_DLL_CLASS Reactor { @@ -249,17 +217,14 @@ class JSON QPDF_DLL virtual ~Reactor() = default; - // The start/end methods are called when parsing of a - // dictionary or array is started or ended. The item methods - // are called when an item is added to a dictionary or array. - // When adding a container to another container, the item - // method is called with an empty container before the lower - // container's start method is called. See important notes in + // The start/end methods are called when parsing of a dictionary or array is started or + // ended. The item methods are called when an item is added to a dictionary or array. When + // adding a container to another container, the item method is called with an empty + // container before the lower container's start method is called. See important notes in // "Item methods" below. - // During parsing of a JSON string, the parser is operating on - // a single object at a time. When a dictionary or array is - // started, a new context begins, and when that dictionary or + // During parsing of a JSON string, the parser is operating on a single object at a time. + // When a dictionary or array is started, a new context begins, and when that dictionary or // array is ended, the previous context is resumed. So, for // example, if you have `{"a": [1]}`, you will receive the // following method calls @@ -271,9 +236,8 @@ class JSON // containerEnd -- now current object is the dictionary again // containerEnd -- current object is undefined // - // If the top-level item in a JSON string is a scalar, the - // topLevelScalar() method will be called. No argument is - // passed since the object is the same as what is returned by + // If the top-level item in a JSON string is a scalar, the topLevelScalar() method will be + // called. No argument is passed since the object is the same as what is returned by // parse(). QPDF_DLL @@ -287,21 +251,17 @@ class JSON // Item methods: // - // The return value of the item methods indicate whether the - // item has been "consumed". If the item method returns true, - // then the item will not be added to the containing JSON + // The return value of the item methods indicate whether the item has been "consumed". If + // the item method returns true, then the item will not be added to the containing JSON // object. This is what allows arbitrarily large JSON objects // to be parsed and not have to be kept in memory. // - // NOTE: When a dictionary or an array is added to a - // container, the dictionaryItem or arrayItem method is called - // when the child item's start delimiter is encountered, so - // the JSON object passed in at that time will always be in - // its initial, empty state. Additionally, the child item's - // start method is not called until after the parent item's - // item method is called. This makes it possible to keep track - // of the current depth level by incrementing level on start - // methods and decrementing on end methods. + // NOTE: When a dictionary or an array is added to a container, the dictionaryItem or + // arrayItem method is called when the child item's start delimiter is encountered, so the + // JSON object passed in at that time will always be in its initial, empty state. + // Additionally, the child item's start method is not called until after the parent item's + // item method is called. This makes it possible to keep track of the current depth level by + // incrementing level on start methods and decrementing on end methods. QPDF_DLL virtual bool dictionaryItem(std::string const& key, JSON const& value) = 0; @@ -312,14 +272,13 @@ class JSON // Create a JSON object from a string. QPDF_DLL static JSON parse(std::string const&); - // Create a JSON object from an input source. See above for - // information about how to use the Reactor. + // Create a JSON object from an input source. See above for information about how to use the + // Reactor. QPDF_DLL static JSON parse(InputSource&, Reactor* reactor = nullptr); - // parse calls setOffsets to set the inclusive start and - // non-inclusive end offsets of an object relative to its input - // string. Otherwise, both values are 0. + // parse calls setOffsets to set the inclusive start and non-inclusive end offsets of an object + // relative to its input string. Otherwise, both values are 0. QPDF_DLL void setStart(qpdf_offset_t); QPDF_DLL diff --git a/include/qpdf/Pipeline.hh b/include/qpdf/Pipeline.hh index a35e7ec6..9b5bc483 100644 --- a/include/qpdf/Pipeline.hh +++ b/include/qpdf/Pipeline.hh @@ -2,44 +2,36 @@ // // This file is part of qpdf. // -// 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 +// 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. +// 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. // -// Versions of qpdf prior to version 7 were released under the terms -// of version 2.0 of the Artistic License. At your option, you may -// continue to consider qpdf to be licensed under those terms. Please -// see the manual for additional information. +// Versions of qpdf prior to version 7 were released under the terms of version 2.0 of the Artistic +// License. At your option, you may continue to consider qpdf to be licensed under those terms. +// Please see the manual for additional information. -// Generalized Pipeline interface. By convention, subclasses of -// Pipeline are called Pl_Something. +// Generalized Pipeline interface. By convention, subclasses of Pipeline are called Pl_Something. // -// When an instance of Pipeline is created with a pointer to a next -// pipeline, that pipeline writes its data to the next one when it -// finishes with it. In order to make possible a usage style in which -// a pipeline may be passed to a function which may stick other -// pipelines in front of it, the allocator of a pipeline is -// responsible for its destruction. In other words, one pipeline -// object does not attempt to manage the memory of its successor. +// When an instance of Pipeline is created with a pointer to a next pipeline, that pipeline writes +// its data to the next one when it finishes with it. In order to make possible a usage style in +// which a pipeline may be passed to a function which may stick other pipelines in front of it, the +// allocator of a pipeline is responsible for its destruction. In other words, one pipeline object +// does not attempt to manage the memory of its successor. // -// The client is required to call finish() before destroying a -// Pipeline in order to avoid loss of data. A Pipeline class should -// not throw an exception in the destructor if this hasn't been done +// The client is required to call finish() before destroying a Pipeline in order to avoid loss of +// data. A Pipeline class should not throw an exception in the destructor if this hasn't been done // though since doing so causes too much trouble when deleting // pipelines during error conditions. // -// Some pipelines are reusable (i.e., you can call write() after -// calling finish() and can call finish() multiple times) while others -// are not. It is up to the caller to use a pipeline according to its -// own restrictions. +// Some pipelines are reusable (i.e., you can call write() after calling finish() and can call +// finish() multiple times) while others are not. It is up to the caller to use a pipeline +// according to its own restrictions. #ifndef PIPELINE_HH #define PIPELINE_HH @@ -50,8 +42,8 @@ #include #include -// Remember to use QPDF_DLL_CLASS on anything derived from Pipeline so -// it will work with dynamic_cast across the shared object boundary. +// Remember to use QPDF_DLL_CLASS on anything derived from Pipeline so it will work with +// dynamic_cast across the shared object boundary. class QPDF_DLL_CLASS Pipeline { public: @@ -61,9 +53,8 @@ class QPDF_DLL_CLASS Pipeline QPDF_DLL virtual ~Pipeline() = default; - // Subclasses should implement write and finish to do their jobs - // and then, if they are not end-of-line pipelines, call - // getNext()->write or getNext()->finish. + // Subclasses should implement write and finish to do their jobs and then, if they are not + // end-of-line pipelines, call getNext()->write or getNext()->finish. QPDF_DLL virtual void write(unsigned char const* data, size_t len) = 0; QPDF_DLL @@ -71,17 +62,15 @@ class QPDF_DLL_CLASS Pipeline QPDF_DLL std::string getIdentifier() const; - // These are convenience methods for making it easier to write - // certain other types of data to pipelines without having to - // cast. The methods that take char const* expect null-terminated - // C strings and do not write the null terminators. + // These are convenience methods for making it easier to write certain other types of data to + // pipelines without having to cast. The methods that take char const* expect null-terminated C + // strings and do not write the null terminators. QPDF_DLL void writeCStr(char const* cstr); QPDF_DLL void writeString(std::string const&); - // This allows *p << "x" << "y" but is not intended to be a - // general purpose << compatible with ostream and does not have - // local awareness or the ability to be "imbued" with properties. + // This allows *p << "x" << "y" but is not intended to be a general purpose << compatible with + // ostream and does not have local awareness or the ability to be "imbued" with properties. QPDF_DLL Pipeline& operator<<(char const* cstr); QPDF_DLL diff --git a/include/qpdf/Pl_Buffer.hh b/include/qpdf/Pl_Buffer.hh index ffc01d95..b244a9f5 100644 --- a/include/qpdf/Pl_Buffer.hh +++ b/include/qpdf/Pl_Buffer.hh @@ -2,36 +2,31 @@ // // This file is part of qpdf. // -// 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 +// 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. +// 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. // -// Versions of qpdf prior to version 7 were released under the terms -// of version 2.0 of the Artistic License. At your option, you may -// continue to consider qpdf to be licensed under those terms. Please -// see the manual for additional information. +// Versions of qpdf prior to version 7 were released under the terms of version 2.0 of the Artistic +// License. At your option, you may continue to consider qpdf to be licensed under those terms. +// Please see the manual for additional information. #ifndef PL_BUFFER_HH #define PL_BUFFER_HH -// This pipeline accumulates the data passed to it into a memory -// buffer. Each subsequent use of this buffer appends to the data -// accumulated so far. getBuffer() may be called only after calling -// finish() and before calling any subsequent write(). At that point, -// a dynamically allocated Buffer object is returned and the internal -// buffer is reset. The caller is responsible for deleting the -// returned Buffer. +// This pipeline accumulates the data passed to it into a memory buffer. Each subsequent use of +// this buffer appends to the data accumulated so far. getBuffer() may be called only after calling +// finish() and before calling any subsequent write(). At that point, a dynamically allocated +// Buffer object is returned and the internal buffer is reset. The caller is responsible for +// deleting the returned Buffer. // -// For this pipeline, "next" may be null. If a next pointer is -// provided, this pipeline will also pass the data through to it. +// For this pipeline, "next" may be null. If a next pointer is provided, this pipeline will also +// pass the data through to it. #include #include @@ -61,12 +56,10 @@ class QPDF_DLL_CLASS Pl_Buffer: public Pipeline QPDF_DLL std::shared_ptr getBufferSharedPointer(); - // getMallocBuffer behaves in the same was as getBuffer except the - // buffer is allocated with malloc(), making it suitable for use - // when calling from other languages. If there is no data, *buf is - // set to a null pointer and *len is set to 0. Otherwise, *buf is - // a buffer of size *len allocated with malloc(). It is the - // caller's responsibility to call free() on the buffer. + // getMallocBuffer behaves in the same was as getBuffer except the buffer is allocated with + // malloc(), making it suitable for use when calling from other languages. If there is no data, + // *buf is set to a null pointer and *len is set to 0. Otherwise, *buf is a buffer of size *len + // allocated with malloc(). It is the caller's responsibility to call free() on the buffer. QPDF_DLL void getMallocBuffer(unsigned char** buf, size_t* len); diff --git a/include/qpdf/QPDF.hh b/include/qpdf/QPDF.hh index 87849dbd..707899cd 100644 --- a/include/qpdf/QPDF.hh +++ b/include/qpdf/QPDF.hh @@ -2,22 +2,19 @@ // // This file is part of qpdf. // -// 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 +// 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. +// 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. // -// Versions of qpdf prior to version 7 were released under the terms -// of version 2.0 of the Artistic License. At your option, you may -// continue to consider qpdf to be licensed under those terms. Please -// see the manual for additional information. +// Versions of qpdf prior to version 7 were released under the terms of version 2.0 of the Artistic +// License. At your option, you may continue to consider qpdf to be licensed under those terms. +// Please see the manual for additional information. #ifndef QPDF_HH #define QPDF_HH @@ -55,8 +52,7 @@ class QPDFParser; class QPDF { public: - // Get the current version of the QPDF software. See also - // qpdf/DLL.h + // Get the current version of the QPDF software. See also qpdf/DLL.h QPDF_DLL static std::string const& QPDFVersion(); @@ -68,92 +64,74 @@ class QPDF QPDF_DLL static std::shared_ptr create(); - // Associate a file with a QPDF object and do initial parsing of - // the file. PDF objects are not read until they are needed. A - // QPDF object may be associated with only one file in its - // lifetime. This method must be called before any methods that - // potentially ask for information about the PDF file are called. - // Prior to calling this, the only methods that are allowed are - // those that set parameters. If the input file is not - // encrypted,either a null password or an empty password can be - // used. If the file is encrypted, either the user password or - // the owner password may be supplied. The method - // setPasswordIsHexKey may be called prior to calling this method - // or any of the other process methods to force the password to be - // interpreted as a raw encryption key. See comments on - // setPasswordIsHexKey for more information. + // Associate a file with a QPDF object and do initial parsing of the file. PDF objects are not + // read until they are needed. A QPDF object may be associated with only one file in its + // lifetime. This method must be called before any methods that potentially ask for information + // about the PDF file are called. Prior to calling this, the only methods that are allowed are + // those that set parameters. If the input file is not encrypted,either a null password or an + // empty password can be used. If the file is encrypted, either the user password or the owner + // password may be supplied. The method setPasswordIsHexKey may be called prior to calling this + // method or any of the other process methods to force the password to be interpreted as a raw + // encryption key. See comments on setPasswordIsHexKey for more information. QPDF_DLL void processFile(char const* filename, char const* password = nullptr); - // Parse a PDF from a stdio FILE*. The FILE must be open in - // binary mode and must be seekable. It may be open read only. - // This works exactly like processFile except that the PDF file is - // read from an already opened FILE*. If close_file is true, the - // file will be closed at the end. Otherwise, the caller is - // responsible for closing the file. + // Parse a PDF from a stdio FILE*. The FILE must be open in binary mode and must be seekable. + // It may be open read only. This works exactly like processFile except that the PDF file is + // read from an already opened FILE*. If close_file is true, the file will be closed at the + // end. Otherwise, the caller is responsible for closing the file. QPDF_DLL void processFile( char const* description, FILE* file, bool close_file, char const* password = nullptr); - // Parse a PDF file loaded into a memory buffer. This works - // exactly like processFile except that the PDF file is in memory - // instead of on disk. The description appears in any warning or + // Parse a PDF file loaded into a memory buffer. This works exactly like processFile except + // that the PDF file is in memory instead of on disk. The description appears in any warning or // error message in place of the file name. QPDF_DLL void processMemoryFile( char const* description, char const* buf, size_t length, char const* password = nullptr); - // Parse a PDF file loaded from a custom InputSource. If you have - // your own method of retrieving a PDF file, you can subclass - // InputSource and use this method. + // Parse a PDF file loaded from a custom InputSource. If you have your own method of retrieving + // a PDF file, you can subclass InputSource and use this method. QPDF_DLL void processInputSource(std::shared_ptr, char const* password = nullptr); - // Create a PDF from an input source that contains JSON as written - // by writeJSON (or qpdf --json-output, version 2 or higher). The - // JSON must be a complete representation of a PDF. See "qpdf - // JSON" in the manual for details. The input JSON may be - // arbitrarily large. QPDF does not load stream data into memory - // for more than one stream at a time, even if the stream data is + // Create a PDF from an input source that contains JSON as written by writeJSON (or qpdf + // --json-output, version 2 or higher). The JSON must be a complete representation of a PDF. See + // "qpdf JSON" in the manual for details. The input JSON may be arbitrarily large. QPDF does not + // load stream data into memory for more than one stream at a time, even if the stream data is // specified inline. QPDF_DLL void createFromJSON(std::string const& json_file); QPDF_DLL void createFromJSON(std::shared_ptr); - // Update a PDF from an input source that contains JSON in the - // same format as is written by writeJSON (or qpdf --json-output, - // version 2 or higher). Objects in the PDF and not in the JSON - // are not modified. See "qpdf JSON" in the manual for details. As - // with createFromJSON, the input JSON may be arbitrarily large. + // Update a PDF from an input source that contains JSON in the same format as is written by + // writeJSON (or qpdf --json-output, version 2 or higher). Objects in the PDF and not in the + // JSON are not modified. See "qpdf JSON" in the manual for details. As with createFromJSON, the + // input JSON may be arbitrarily large. QPDF_DLL void updateFromJSON(std::string const& json_file); QPDF_DLL void updateFromJSON(std::shared_ptr); - // Write qpdf JSON format to the pipeline "p". The only supported - // version is 2. The finish() method is not called on the - // pipeline. + // Write qpdf JSON format to the pipeline "p". The only supported version is 2. The finish() + // method is not called on the pipeline. // - // The decode_level parameter controls which streams are - // uncompressed in the JSON. Use qpdf_dl_none to preserve all - // stream data exactly as it appears in the input. The possible - // values for json_stream_data can be found in qpdf/Constants.h - // and correspond to the --json-stream-data command-line argument. - // If json_stream_data is qpdf_sj_file, file_prefix must be - // specified. Each stream will be written to a file whose path is - // constructed by appending "-nnn" to file_prefix, where "nnn" is - // the object number (not zero-filled). If wanted_objects is - // empty, write all objects. Otherwise, write only objects whose - // keys are in wanted_objects. Keys may be either "trailer" or of - // the form "obj:n n R". Invalid keys are ignored. This - // corresponds to the --json-object command-line argument. + // The decode_level parameter controls which streams are uncompressed in the JSON. Use + // qpdf_dl_none to preserve all stream data exactly as it appears in the input. The possible + // values for json_stream_data can be found in qpdf/Constants.h and correspond to the + // --json-stream-data command-line argument. If json_stream_data is qpdf_sj_file, file_prefix + // must be specified. Each stream will be written to a file whose path is constructed by + // appending "-nnn" to file_prefix, where "nnn" is the object number (not zero-filled). If + // wanted_objects is empty, write all objects. Otherwise, write only objects whose keys are in + // wanted_objects. Keys may be either "trailer" or of the form "obj:n n R". Invalid keys are + // ignored. This corresponds to the --json-object command-line argument. // - // QPDF is efficient with regard to memory when writing, allowing - // you to write arbitrarily large PDF files to a pipeline. You can - // use a pipeline like Pl_Buffer or Pl_String to capture the JSON - // output in memory, but do so with caution as this will allocate - // enough memory to hold the entire PDF file. + // QPDF is efficient with regard to memory when writing, allowing you to write arbitrarily large + // PDF files to a pipeline. You can use a pipeline like Pl_Buffer or Pl_String to capture the + // JSON output in memory, but do so with caution as this will allocate enough memory to hold the + // entire PDF file. QPDF_DLL void writeJSON( int version, @@ -163,17 +141,13 @@ class QPDF std::string const& file_prefix, std::set wanted_objects); - // This version of writeJSON enables writing only the "qpdf" key - // of an in-progress dictionary. If the value of "complete" is - // true, a complete JSON object containing only the "qpdf" key is - // written to the pipeline. If the value of "complete" is false, - // the "qpdf" key and its value are written to the pipeline - // assuming that a dictionary is already open. The parameter - // first_key indicates whether this is the first key in an - // in-progress dictionary. It will be set to false by writeJSON. - // The "qpdf" key and value are written as if at depth 1 in a - // prettified JSON output. Remaining arguments are the same as the - // above version. + // This version of writeJSON enables writing only the "qpdf" key of an in-progress dictionary. + // If the value of "complete" is true, a complete JSON object containing only the "qpdf" key is + // written to the pipeline. If the value of "complete" is false, the "qpdf" key and its value + // are written to the pipeline assuming that a dictionary is already open. The parameter + // first_key indicates whether this is the first key in an in-progress dictionary. It will be + // set to false by writeJSON. The "qpdf" key and value are written as if at depth 1 in a + // prettified JSON output. Remaining arguments are the same as the above version. QPDF_DLL void writeJSON( int version, @@ -185,169 +159,135 @@ class QPDF std::string const& file_prefix, std::set wanted_objects); - // Close or otherwise release the input source. Once this has been - // called, no other methods of qpdf can be called safely except - // for getWarnings and anyWarnings(). After this has been called, - // it is safe to perform operations on the input file such as - // deleting or renaming it. + // Close or otherwise release the input source. Once this has been called, no other methods of + // qpdf can be called safely except for getWarnings and anyWarnings(). After this has been + // called, it is safe to perform operations on the input file such as deleting or renaming it. QPDF_DLL void closeInputSource(); - // For certain forensic or investigatory purposes, it may - // sometimes be useful to specify the encryption key directly, - // even though regular PDF applications do not provide a way to do - // this. Calling setPasswordIsHexKey(true) before calling any of - // the process methods will bypass the normal encryption key - // computation or recovery mechanisms and interpret the bytes in - // the password as a hex-encoded encryption key. Note that we - // hex-encode the key because it may contain null bytes and - // therefore can't be represented in a char const*. + // For certain forensic or investigatory purposes, it may sometimes be useful to specify the + // encryption key directly, even though regular PDF applications do not provide a way to do + // this. Calling setPasswordIsHexKey(true) before calling any of the process methods will bypass + // the normal encryption key computation or recovery mechanisms and interpret the bytes in the + // password as a hex-encoded encryption key. Note that we hex-encode the key because it may + // contain null bytes and therefore can't be represented in a char const*. QPDF_DLL void setPasswordIsHexKey(bool); - // Create a QPDF object for an empty PDF. This PDF has no pages - // or objects other than a minimal trailer, a document catalog, - // and a /Pages tree containing zero pages. Pages and other - // objects can be added to the file in the normal way, and the - // trailer and document catalog can be mutated. Calling this - // method is equivalent to calling processFile on an equivalent - // PDF file. See the pdf-create.cc example for a demonstration of - // how to use this method to create a PDF file from scratch. + // Create a QPDF object for an empty PDF. This PDF has no pages or objects other than a minimal + // trailer, a document catalog, and a /Pages tree containing zero pages. Pages and other + // objects can be added to the file in the normal way, and the trailer and document catalog can + // be mutated. Calling this method is equivalent to calling processFile on an equivalent PDF + // file. See the pdf-create.cc example for a demonstration of how to use this method to create + // a PDF file from scratch. QPDF_DLL void emptyPDF(); - // From 10.1: register a new filter implementation for a specific - // stream filter. You can add your own implementations for new - // filter types or override existing ones provided by the library. - // Registered stream filters are used for decoding only as you can - // override encoding with stream data providers. For example, you - // could use this method to add support for one of the other filter - // types by using additional third-party libraries that qpdf does - // not presently use. The standard filters are implemented using - // QPDFStreamFilter classes. + // From 10.1: register a new filter implementation for a specific stream filter. You can add + // your own implementations for new filter types or override existing ones provided by the + // library. Registered stream filters are used for decoding only as you can override encoding + // with stream data providers. For example, you could use this method to add support for one of + // the other filter types by using additional third-party libraries that qpdf does not presently + // use. The standard filters are implemented using QPDFStreamFilter classes. QPDF_DLL static void registerStreamFilter( std::string const& filter_name, std::function()> factory); // Parameter settings - // To capture or redirect output, configure the logger returned by - // getLogger(). By default, all QPDF and QPDFJob objects share the - // global logger. If you need a private logger for some reason, - // pass a new one to setLogger(). See comments in QPDFLogger.hh - // for details on configuring the logger. + // To capture or redirect output, configure the logger returned by getLogger(). By default, all + // QPDF and QPDFJob objects share the global logger. If you need a private logger for some + // reason, pass a new one to setLogger(). See comments in QPDFLogger.hh for details on + // configuring the logger. // - // Note that no normal QPDF operations generate output to standard - // output, so for applications that just wish to avoid creating - // output for warnings and don't call any check functions, calling - // setSuppressWarnings(true) is sufficient. + // Note that no normal QPDF operations generate output to standard output, so for applications + // that just wish to avoid creating output for warnings and don't call any check functions, + // calling setSuppressWarnings(true) is sufficient. QPDF_DLL std::shared_ptr getLogger(); QPDF_DLL void setLogger(std::shared_ptr); - // This deprecated method is the old way to capture output, but it - // didn't capture all output. See comments above for getLogger and - // setLogger. This will be removed in QPDF 12. For now, it - // configures a private logger, separating this object from the - // default logger, and calls setOutputStreams on that logger. See - // QPDFLogger.hh for additional details. + // This deprecated method is the old way to capture output, but it didn't capture all output. + // See comments above for getLogger and setLogger. This will be removed in QPDF 12. For now, it + // configures a private logger, separating this object from the default logger, and calls + // setOutputStreams on that logger. See QPDFLogger.hh for additional details. [[deprecated("configure logger from getLogger() or call setLogger()")]] QPDF_DLL void setOutputStreams(std::ostream* out_stream, std::ostream* err_stream); - // If true, ignore any cross-reference streams in a hybrid file - // (one that contains both cross-reference streams and - // cross-reference tables). This can be useful for testing to + // If true, ignore any cross-reference streams in a hybrid file (one that contains both + // cross-reference streams and cross-reference tables). This can be useful for testing to // ensure that a hybrid file would work with an older reader. QPDF_DLL void setIgnoreXRefStreams(bool); - // By default, any warnings are issued to std::cerr or the error - // stream specified in a call to setOutputStreams as they are - // encountered. If this method is called with a true value, reporting of - // warnings is suppressed. You may still retrieve warnings by - // calling getWarnings. + // By default, any warnings are issued to std::cerr or the error stream specified in a call to + // setOutputStreams as they are encountered. If this method is called with a true value, + // reporting of warnings is suppressed. You may still retrieve warnings by calling getWarnings. QPDF_DLL void setSuppressWarnings(bool); - // By default, QPDF will try to recover if it finds certain types - // of errors in PDF files. If turned off, it will throw an - // exception on the first such problem it finds without attempting + // By default, QPDF will try to recover if it finds certain types of errors in PDF files. If + // turned off, it will throw an exception on the first such problem it finds without attempting // recovery. QPDF_DLL void setAttemptRecovery(bool); - // Tell other QPDF objects that streams copied from this QPDF need - // to be fully copied when copyForeignObject is called on them. - // Calling setIgnoreXRefStreams(true) on a QPDF object makes it - // possible for the object and its input source to disappear - // before streams copied from it are written with the destination - // QPDF object. Confused? Ordinarily, if you are going to copy - // objects from a source QPDF object to a destination QPDF object - // using copyForeignObject or addPage, the source object's input - // source must stick around until after the destination PDF is - // written. If you call this method on the source QPDF object, it - // sends a signal to the destination object that it must fully - // copy the stream data when copyForeignObject. It will do this by - // making a copy in RAM. Ordinarily the stream data is copied - // lazily to avoid unnecessary duplication of the stream data. - // Note that the stream data is copied into RAM only once - // regardless of how many objects the stream is copied into. The - // result is that, if you called setImmediateCopyFrom(true) on a - // given QPDF object prior to copying any of its streams, you do - // not need to keep it or its input source around after copying - // its objects to another QPDF. This is true even if the source - // streams use StreamDataProvider. Note that this method is called - // on the QPDF object you are copying FROM, not the one you are - // copying to. The reasoning for this is that there's no reason a - // given QPDF may not get objects copied to it from a variety of - // other objects, some transient and some not. Since what's - // relevant is whether the source QPDF is transient, the method - // must be called on the source QPDF, not the destination one. - // This method will make a copy of the stream in RAM, so be - // sure you have enough memory to simultaneously hold all the - // streams you're copying. + // Tell other QPDF objects that streams copied from this QPDF need to be fully copied when + // copyForeignObject is called on them. Calling setIgnoreXRefStreams(true) on a QPDF object + // makes it possible for the object and its input source to disappear before streams copied from + // it are written with the destination QPDF object. Confused? Ordinarily, if you are going to + // copy objects from a source QPDF object to a destination QPDF object using copyForeignObject + // or addPage, the source object's input source must stick around until after the destination + // PDF is written. If you call this method on the source QPDF object, it sends a signal to the + // destination object that it must fully copy the stream data when copyForeignObject. It will do + // this by making a copy in RAM. Ordinarily the stream data is copied lazily to avoid + // unnecessary duplication of the stream data. Note that the stream data is copied into RAM only + // once regardless of how many objects the stream is copied into. The result is that, if you + // called setImmediateCopyFrom(true) on a given QPDF object prior to copying any of its streams, + // you do not need to keep it or its input source around after copying its objects to another + // QPDF. This is true even if the source streams use StreamDataProvider. Note that this method + // is called on the QPDF object you are copying FROM, not the one you are copying to. The + // reasoning for this is that there's no reason a given QPDF may not get objects copied to it + // from a variety of other objects, some transient and some not. Since what's relevant is + // whether the source QPDF is transient, the method must be called on the source QPDF, not the + // destination one. This method will make a copy of the stream in RAM, so be sure you have + // enough memory to simultaneously hold all the streams you're copying. QPDF_DLL void setImmediateCopyFrom(bool); // Other public methods - // Return the list of warnings that have been issued so far and - // clear the list. This method may be called even if processFile - // throws an exception. Note that if setSuppressWarnings was not - // called or was called with a false value, any warnings retrieved - // here will have already been output. + // Return the list of warnings that have been issued so far and clear the list. This method may + // be called even if processFile throws an exception. Note that if setSuppressWarnings was not + // called or was called with a false value, any warnings retrieved here will have already been + // output. QPDF_DLL std::vector getWarnings(); - // Indicate whether any warnings have been issued so far. Does not - // clear the list of warnings. + // Indicate whether any warnings have been issued so far. Does not clear the list of warnings. QPDF_DLL bool anyWarnings() const; - // Indicate the number of warnings that have been issued since the last - // call to getWarnings. Does not clear the list of warnings. + // Indicate the number of warnings that have been issued since the last call to getWarnings. + // Does not clear the list of warnings. QPDF_DLL size_t numWarnings() const; - // Return an application-scoped unique ID for this QPDF object. - // This is not a globally unique ID. It is constructed using a - // timestamp and a random number and is intended to be unique - // among QPDF objects that are created by a single run of an - // application. While it's very likely that these are actually - // globally unique, it is not recommended to use them for - // long-term purposes. + // Return an application-scoped unique ID for this QPDF object. This is not a globally unique + // ID. It is constructed using a timestamp and a random number and is intended to be unique + // among QPDF objects that are created by a single run of an application. While it's very likely + // that these are actually globally unique, it is not recommended to use them for long-term + // purposes. QPDF_DLL unsigned long long getUniqueId() const; - // Issue a warning on behalf of this QPDF object. It will be - // emitted with other warnings, following warning suppression - // rules, and it will be available with getWarnings(). + // Issue a warning on behalf of this QPDF object. It will be emitted with other warnings, + // following warning suppression rules, and it will be available with getWarnings(). QPDF_DLL void warn(QPDFExc const& e); - // Same as above but creates the QPDFExc object using the - // arguments passed to warn. The filename argument to QPDFExc is - // omitted. This method uses the filename associated with the QPDF + // Same as above but creates the QPDFExc object using the arguments passed to warn. The filename + // argument to QPDFExc is omitted. This method uses the filename associated with the QPDF // object. QPDF_DLL void warn( @@ -376,60 +316,48 @@ class QPDF // Public factory methods - // Create a new stream. A subsequent call must be made to - // replaceStreamData() to provide data for the stream. The stream's - // dictionary may be retrieved by calling getDict(), and the resulting - // dictionary may be modified. Alternatively, you can create a new - // dictionary and call replaceDict to install it. + // Create a new stream. A subsequent call must be made to replaceStreamData() to provide data + // for the stream. The stream's dictionary may be retrieved by calling getDict(), and the + // resulting dictionary may be modified. Alternatively, you can create a new dictionary and + // call replaceDict to install it. QPDF_DLL QPDFObjectHandle newStream(); - // Create a new stream. Use the given buffer as the stream data. The - // stream dictionary's /Length key will automatically be set to the size of - // the data buffer. If additional keys are required, the stream's - // dictionary may be retrieved by calling getDict(), and the resulting - // dictionary may be modified. This method is just a convenient wrapper - // around the newStream() and replaceStreamData(). It is a convenience - // methods for streams that require no parameters beyond the stream length. - // Note that you don't have to deal with compression yourself if you use - // QPDFWriter. By default, QPDFWriter will automatically compress - // uncompressed stream data. Example programs are provided that - // illustrate this. + // Create a new stream. Use the given buffer as the stream data. The stream dictionary's + // /Length key will automatically be set to the size of the data buffer. If additional keys are + // required, the stream's dictionary may be retrieved by calling getDict(), and the resulting + // dictionary may be modified. This method is just a convenient wrapper around the newStream() + // and replaceStreamData(). It is a convenience methods for streams that require no parameters + // beyond the stream length. Note that you don't have to deal with compression yourself if you + // use QPDFWriter. By default, QPDFWriter will automatically compress uncompressed stream data. + // Example programs are provided that illustrate this. QPDF_DLL QPDFObjectHandle newStream(std::shared_ptr data); - // Create new stream with data from string. This method will - // create a copy of the data rather than using the user-provided - // buffer as in the std::shared_ptr version of newStream. + // Create new stream with data from string. This method will create a copy of the data rather + // than using the user-provided buffer as in the std::shared_ptr version of newStream. QPDF_DLL QPDFObjectHandle newStream(std::string const& data); - // A reserved object is a special sentinel used for qpdf to - // reserve a spot for an object that is going to be added to the - // QPDF object. Normally you don't have to use this type since - // you can just call QPDF::makeIndirectObject. However, in some - // cases, if you have to create objects with circular references, - // you may need to create a reserved object so that you can have a - // reference to it and then replace the object later. Reserved - // objects have the special property that they can't be resolved - // to direct objects. This makes it possible to replace a - // reserved object with a new object while preserving existing - // references to them. When you are ready to replace a reserved - // object with its replacement, use QPDF::replaceReserved for this - // purpose rather than the more general QPDF::replaceObject. It - // is an error to try to write a QPDF with QPDFWriter if it has - // any reserved objects in it. + // A reserved object is a special sentinel used for qpdf to reserve a spot for an object that is + // going to be added to the QPDF object. Normally you don't have to use this type since you can + // just call QPDF::makeIndirectObject. However, in some cases, if you have to create objects + // with circular references, you may need to create a reserved object so that you can have a + // reference to it and then replace the object later. Reserved objects have the special + // property that they can't be resolved to direct objects. This makes it possible to replace a + // reserved object with a new object while preserving existing references to them. When you are + // ready to replace a reserved object with its replacement, use QPDF::replaceReserved for this + // purpose rather than the more general QPDF::replaceObject. It is an error to try to write a + // QPDF with QPDFWriter if it has any reserved objects in it. QPDF_DLL QPDFObjectHandle newReserved(); - // Install this object handle as an indirect object and return an - // indirect reference to it. + // Install this object handle as an indirect object and return an indirect reference to it. QPDF_DLL QPDFObjectHandle makeIndirectObject(QPDFObjectHandle); - // Retrieve an object by object ID and generation. Returns an - // indirect reference to it. The getObject() methods were added - // for qpdf 11. + // Retrieve an object by object ID and generation. Returns an indirect reference to it. The + // getObject() methods were added for qpdf 11. QPDF_DLL QPDFObjectHandle getObject(QPDFObjGen const&); QPDF_DLL @@ -441,83 +369,63 @@ class QPDF QPDF_DLL QPDFObjectHandle getObjectByID(int objid, int generation); - // Replace the object with the given object id with the given - // object. The object handle passed in must be a direct object, - // though it may contain references to other indirect objects - // within it. Prior to qpdf 10.2.1, after calling this method, - // existing QPDFObjectHandle instances that pointed to the - // original object still pointed to the original object, resulting - // in confusing and incorrect behavior. This was fixed in 10.2.1, - // so existing QPDFObjectHandle objects will start pointing to the - // newly replaced object. Note that replacing an object with - // QPDFObjectHandle::newNull() effectively removes the object from - // the file since a non-existent object is treated as a null - // object. To replace a reserved object, call replaceReserved + // Replace the object with the given object id with the given object. The object handle passed + // in must be a direct object, though it may contain references to other indirect objects within + // it. Prior to qpdf 10.2.1, after calling this method, existing QPDFObjectHandle instances that + // pointed to the original object still pointed to the original object, resulting in confusing + // and incorrect behavior. This was fixed in 10.2.1, so existing QPDFObjectHandle objects will + // start pointing to the newly replaced object. Note that replacing an object with + // QPDFObjectHandle::newNull() effectively removes the object from the file since a non-existent + // object is treated as a null object. To replace a reserved object, call replaceReserved // instead. QPDF_DLL void replaceObject(QPDFObjGen const& og, QPDFObjectHandle); QPDF_DLL void replaceObject(int objid, int generation, QPDFObjectHandle); - // Swap two objects given by ID. Prior to qpdf 10.2.1, existing - // QPDFObjectHandle instances that reference them objects not - // notice the swap, but this was fixed in 10.2.1. + // Swap two objects given by ID. Prior to qpdf 10.2.1, existing QPDFObjectHandle instances that + // reference them objects not notice the swap, but this was fixed in 10.2.1. QPDF_DLL void swapObjects(QPDFObjGen const& og1, QPDFObjGen const& og2); QPDF_DLL void swapObjects(int objid1, int generation1, int objid2, int generation2); - // Replace a reserved object. This is a wrapper around - // replaceObject but it guarantees that the underlying object is a - // reserved object. After this call, reserved will be a reference - // to replacement. + // Replace a reserved object. This is a wrapper around replaceObject but it guarantees that the + // underlying object is a reserved object. After this call, reserved will be a reference to + // replacement. QPDF_DLL void replaceReserved(QPDFObjectHandle reserved, QPDFObjectHandle replacement); - // Copy an object from another QPDF to this one. Starting with - // qpdf version 8.3.0, it is no longer necessary to keep the - // original QPDF around after the call to copyForeignObject as - // long as the source of any copied stream data is still - // available. Usually this means you just have to keep the input - // file around, not the QPDF object. The exception to this is if - // you copy a stream that gets its data from a - // QPDFObjectHandle::StreamDataProvider. In this case only, the - // original stream's QPDF object must stick around because the - // QPDF object is itself the source of the original stream data. - // For a more in-depth discussion, please see the TODO file. - // Starting in 8.4.0, you can call setImmediateCopyFrom(true) on - // the SOURCE QPDF object (the one you're copying FROM). If you do - // this prior to copying any of its objects, then neither the - // source QPDF object nor its input source needs to stick around - // at all regardless of the source. The cost is that the stream - // data is copied into RAM at the time copyForeignObject is + // Copy an object from another QPDF to this one. Starting with qpdf version 8.3.0, it is no + // longer necessary to keep the original QPDF around after the call to copyForeignObject as long + // as the source of any copied stream data is still available. Usually this means you just have + // to keep the input file around, not the QPDF object. The exception to this is if you copy a + // stream that gets its data from a QPDFObjectHandle::StreamDataProvider. In this case only, the + // original stream's QPDF object must stick around because the QPDF object is itself the source + // of the original stream data. For a more in-depth discussion, please see the TODO file. + // Starting in 8.4.0, you can call setImmediateCopyFrom(true) on the SOURCE QPDF object (the one + // you're copying FROM). If you do this prior to copying any of its objects, then neither the + // source QPDF object nor its input source needs to stick around at all regardless of the + // source. The cost is that the stream data is copied into RAM at the time copyForeignObject is // called. See setImmediateCopyFrom for more information. // - // The return value of this method is an indirect reference to the - // copied object in this file. This method is intended to be used - // to copy non-page objects. To copy page objects, pass the - // foreign page object directly to addPage (or addPageAt). If you - // copy objects that contain references to pages, you should copy - // the pages first using addPage(At). Otherwise references to the - // pages that have not been copied will be replaced with nulls. It - // is possible to use copyForeignObject on page objects if you are - // not going to use them as pages. Doing so copies the object - // normally but does not update the page structure. For example, - // it is a valid use case to use copyForeignObject for a page that - // you are going to turn into a form XObject, though you can also - // use QPDFPageObjectHelper::getFormXObjectForPage for that - // purpose. + // The return value of this method is an indirect reference to the copied object in this file. + // This method is intended to be used to copy non-page objects. To copy page objects, pass the + // foreign page object directly to addPage (or addPageAt). If you copy objects that contain + // references to pages, you should copy the pages first using addPage(At). Otherwise references + // to the pages that have not been copied will be replaced with nulls. It is possible to use + // copyForeignObject on page objects if you are not going to use them as pages. Doing so copies + // the object normally but does not update the page structure. For example, it is a valid use + // case to use copyForeignObject for a page that you are going to turn into a form XObject, + // though you can also use QPDFPageObjectHelper::getFormXObjectForPage for that purpose. // - // When copying objects with this method, object structure will be - // preserved, so all indirectly referenced indirect objects will - // be copied as well. This includes any circular references that - // may exist. The QPDF object keeps a record of what has already - // been copied, so shared objects will not be copied multiple - // times. This also means that if you mutate an object that has - // already been copied and try to copy it again, it won't work - // since the modified object will not be recopied. Therefore, you - // should do all mutation on the original file that you are going - // to do before you start copying its objects to a new file. + // When copying objects with this method, object structure will be preserved, so all indirectly + // referenced indirect objects will be copied as well. This includes any circular references + // that may exist. The QPDF object keeps a record of what has already been copied, so shared + // objects will not be copied multiple times. This also means that if you mutate an object that + // has already been copied and try to copy it again, it won't work since the modified object + // will not be recopied. Therefore, you should do all mutation on the original file that you + // are going to do before you start copying its objects to a new file. QPDF_DLL QPDFObjectHandle copyForeignObject(QPDFObjectHandle foreign); @@ -633,9 +541,8 @@ class QPDF QPDF_DLL bool allowModifyAll(); - // Helper function to trim padding from user password. Calling - // trim_user_password on the result of getPaddedUserPassword gives - // getTrimmedUserPassword's result. + // Helper function to trim padding from user password. Calling trim_user_password on the result + // of getPaddedUserPassword gives getTrimmedUserPassword's result. QPDF_DLL static void trim_user_password(std::string& user_password); QPDF_DLL @@ -678,47 +585,40 @@ class QPDF std::string& OE, std::string& UE, std::string& Perms); - // Return the full user password as stored in the PDF file. For - // files encrypted with 40-bit or 128-bit keys, the user password - // can be recovered when the file is opened using the owner - // password. This is not possible with newer encryption formats. - // If you are attempting to recover the user password in a - // user-presentable form, call getTrimmedUserPassword() instead. + // Return the full user password as stored in the PDF file. For files encrypted with 40-bit or + // 128-bit keys, the user password can be recovered when the file is opened using the owner + // password. This is not possible with newer encryption formats. If you are attempting to + // recover the user password in a user-presentable form, call getTrimmedUserPassword() instead. QPDF_DLL std::string const& getPaddedUserPassword() const; - // Return human-readable form of user password subject to same - // limitations as getPaddedUserPassword(). + // Return human-readable form of user password subject to same limitations as + // getPaddedUserPassword(). QPDF_DLL std::string getTrimmedUserPassword() const; - // Return the previously computed or retrieved encryption key for - // this file + // Return the previously computed or retrieved encryption key for this file QPDF_DLL std::string getEncryptionKey() const; - // Remove security restrictions associated with digitally signed - // files. + // Remove security restrictions associated with digitally signed files. QPDF_DLL void removeSecurityRestrictions(); // Linearization support - // Returns true iff the file starts with a linearization parameter - // dictionary. Does no additional validation. + // Returns true iff the file starts with a linearization parameter dictionary. Does no + // additional validation. QPDF_DLL bool isLinearized(); - // Performs various sanity checks on a linearized file. Return - // true if no errors or warnings. Otherwise, return false and - // output errors and warnings to the default output stream - // (std::cout or whatever is configured in the logger). It is - // recommended for linearization errors to be treated as warnings. + // Performs various sanity checks on a linearized file. Return true if no errors or warnings. + // Otherwise, return false and output errors and warnings to the default output stream + // (std::cout or whatever is configured in the logger). It is recommended for linearization + // errors to be treated as warnings. QPDF_DLL bool checkLinearization(); - // Calls checkLinearization() and, if possible, prints normalized - // contents of some of the hints tables to the default output - // stream. Normalization includes adding min values to delta - // values and adjusting offsets based on the location and size of - // the primary hint stream. + // Calls checkLinearization() and, if possible, prints normalized contents of some of the hints + // tables to the default output stream. Normalization includes adding min values to delta values + // and adjusting offsets based on the location and size of the primary hint stream. QPDF_DLL void showLinearizationData(); @@ -726,66 +626,52 @@ class QPDF QPDF_DLL void showXRefTable(); - // Starting from qpdf 11.0 user code should not need to call this method. - // Before 11.0 this method was used to detect all indirect references to - // objects that don't exist and resolve them by replacing them with null, - // which is how the PDF spec says to interpret such dangling references. - // This method is called automatically when you try to add any new objects, - // if you call getAllObjects, and before a file is written. The qpdf object - // caches whether it has run this to avoid running it multiple times. - // Before 11.2.1 you could pass true to force it to run again if you had - // explicitly added new objects that may have additional dangling - // references. + // Starting from qpdf 11.0 user code should not need to call this method. Before 11.0 this + // method was used to detect all indirect references to objects that don't exist and resolve + // them by replacing them with null, which is how the PDF spec says to interpret such dangling + // references. This method is called automatically when you try to add any new objects, if you + // call getAllObjects, and before a file is written. The qpdf object caches whether it has run + // this to avoid running it multiple times. Before 11.2.1 you could pass true to force it to run + // again if you had explicitly added new objects that may have additional dangling references. QPDF_DLL void fixDanglingReferences(bool force = false); - // Return the approximate number of indirect objects. It is - // approximate because not all objects in the file are preserved - // in all cases, and gaps in object numbering are not preserved. + // Return the approximate number of indirect objects. It is/ approximate because not all objects + // in the file are preserved in all cases, and gaps in object numbering are not preserved. QPDF_DLL size_t getObjectCount(); - // Returns a list of indirect objects for every object in the xref - // table. Useful for discovering objects that are not otherwise - // referenced. + // Returns a list of indirect objects for every object in the xref table. Useful for discovering + // objects that are not otherwise referenced. QPDF_DLL std::vector getAllObjects(); - // Optimization support -- see doc/optimization. Implemented in - // QPDF_optimization.cc - - // The object_stream_data map maps from a "compressed" object to - // the object stream that contains it. This enables optimize to - // populate the object <-> user maps with only uncompressed - // objects. If allow_changes is false, an exception will be thrown - // if any changes are made during the optimization process. This - // is available so that the test suite can make sure that a - // linearized file is already optimized. When called in this way, - // optimize() still populates the object <-> user maps. The - // optional skip_stream_parameters parameter, if present, is - // called for each stream object. The function should return 2 if - // optimization should discard /Length, /Filter, and /DecodeParms; - // 1 if it should discard /Length, and 0 if it should preserve all - // keys. This is used by QPDFWriter to avoid creation of dangling - // objects for stream dictionary keys it will be regenerating. + // Optimization support -- see doc/optimization. Implemented in QPDF_optimization.cc + + // The object_stream_data map maps from a "compressed" object to the object stream that contains + // it. This enables optimize to populate the object <-> user maps with only uncompressed + // objects. If allow_changes is false, an exception will be thrown if any changes are made + // during the optimization process. This is available so that the test suite can make sure that + // a linearized file is already optimized. When called in this way, optimize() still populates + // the object <-> user maps. The optional skip_stream_parameters parameter, if present, is + // called for each stream object. The function should return 2 if optimization should discard + // /Length, /Filter, and /DecodeParms; 1 if it should discard /Length, and 0 if it should + // preserve all keys. This is used by QPDFWriter to avoid creation of dangling objects for + // stream dictionary keys it will be regenerating. QPDF_DLL void optimize( std::map const& object_stream_data, bool allow_changes = true, std::function skip_stream_parameters = nullptr); - // Traverse page tree return all /Page objects. It also detects - // and resolves cases in which the same /Page object is - // duplicated. For efficiency, this method returns a const - // reference to an internal vector of pages. Calls to addPage, - // addPageAt, and removePage safely update this, but directly - // manipulation of the pages tree or pushing inheritable objects - // to the page level may invalidate it. See comments for - // updateAllPagesCache() for additional notes. Newer code should - // use QPDFPageDocumentHelper::getAllPages instead. The decision - // to expose this internal cache was arguably incorrect, but it is - // being left here for compatibility. It is, however, completely - // safe to use this for files that you are not modifying. + // Traverse page tree return all /Page objects. It also detects and resolves cases in which the + // same /Page object is duplicated. For efficiency, this method returns a const reference to an + // internal vector of pages. Calls to addPage, addPageAt, and removePage safely update this, but + // directly manipulation of the pages tree or pushing inheritable objects to the page level may + // invalidate it. See comments for updateAllPagesCache() for additional notes. Newer code should + // use QPDFPageDocumentHelper::getAllPages instead. The decision to expose this internal cache + // was arguably incorrect, but it is being left here for compatibility. It is, however, + // completely safe to use this for files that you are not modifying. QPDF_DLL std::vector const& getAllPages(); @@ -794,40 +680,32 @@ class QPDF QPDF_DLL bool everPushedInheritedAttributesToPages() const; - // These methods, given a page object or its object/generation - // number, returns the 0-based index into the array returned by - // getAllPages() for that page. An exception is thrown if the page - // is not found. + // These methods, given a page object or its object/generation number, returns the 0-based index + // into the array returned by getAllPages() for that page. An exception is thrown if the page is + // not found. QPDF_DLL int findPage(QPDFObjGen const& og); QPDF_DLL int findPage(QPDFObjectHandle& page); - // This method synchronizes QPDF's cache of the page structure - // with the actual /Pages tree. If you restrict changes to the - // /Pages tree, including addition, removal, or replacement of - // pages or changes to any /Pages objects, to calls to these page - // handling APIs, you never need to call this method. If you - // modify /Pages structures directly, you must call this method - // afterwards. This method updates the internal list of pages, so - // after calling this method, any previous references returned by - // getAllPages() will be valid again. It also resets any state - // about having pushed inherited attributes in /Pages objects down - // to the pages, so if you add any inheritable attributes to a - // /Pages object, you should also call this method. + // This method synchronizes QPDF's cache of the page structure with the actual /Pages tree. If + // you restrict changes to the /Pages tree, including addition, removal, or replacement of pages + // or changes to any /Pages objects, to calls to these page handling APIs, you never need to + // call this method. If you modify /Pages structures directly, you must call this method + // afterwards. This method updates the internal list of pages, so after calling this method, + // any previous references returned by getAllPages() will be valid again. It also resets any + // state about having pushed inherited attributes in /Pages objects down to the pages, so if you + // add any inheritable attributes to a /Pages object, you should also call this method. QPDF_DLL void updateAllPagesCache(); - // Legacy handling API. These methods are not going anywhere, and - // you should feel free to continue using them if it simplifies - // your code. Newer code should make use of QPDFPageDocumentHelper - // instead as future page handling methods will be added there. - // The functionality and specification of these legacy methods is - // identical to the identically named methods there, except that - // these versions use QPDFObjectHandle instead of - // QPDFPageObjectHelper, so please see comments in that file for - // descriptions. There are subtleties you need to know about, so - // please look at the comments there. + // Legacy handling API. These methods are not going anywhere, and you should feel free to + // continue using them if it simplifies your code. Newer code should make use of + // QPDFPageDocumentHelper instead as future page handling methods will be added there. The + // functionality and specification of these legacy methods is identical to the identically named + // methods there, except that these versions use QPDFObjectHandle instead of + // QPDFPageObjectHelper, so please see comments in that file for descriptions. There are + // subtleties you need to know about, so please look at the comments there. QPDF_DLL void pushInheritedAttributesToPage(); QPDF_DLL @@ -838,8 +716,7 @@ class QPDF void removePage(QPDFObjectHandle page); // End legacy page helpers - // Writer class is restricted to QPDFWriter so that only it can - // call certain methods. + // Writer class is restricted to QPDFWriter so that only it can call certain methods. class Writer { friend class QPDFWriter; @@ -884,8 +761,8 @@ class QPDF } }; - // The Resolver class is restricted to QPDFObject so that only it - // can resolve indirect references. + // The Resolver class is restricted to QPDFObject so that only it can resolve indirect + // references. class Resolver { friend class QPDFObject; @@ -898,8 +775,7 @@ class QPDF } }; - // StreamCopier class is restricted to QPDFObjectHandle so it can - // copy stream data. + // StreamCopier class is restricted to QPDFObjectHandle so it can copy stream data. class StreamCopier { friend class QPDFObjectHandle; @@ -974,12 +850,10 @@ class QPDF static bool test_json_validators(); private: - // It has never been safe to copy QPDF objects as there is code in - // the library that assumes there are no copies of a QPDF object. - // Copying QPDF objects was not prevented by the API until qpdf - // 11. If you have been copying QPDF objects, use - // std::shared_ptr instead. From qpdf 11, you can use - // QPDF::create to create them. + // It has never been safe to copy QPDF objects as there is code in the library that assumes + // there are no copies of a QPDF object. Copying QPDF objects was not prevented by the API until + // qpdf 11. If you have been copying QPDF objects, use std::shared_ptr instead. From qpdf + // 11, you can use QPDF::create to create them. QPDF(QPDF const&) = delete; QPDF& operator=(QPDF const&) = delete; @@ -1200,8 +1074,8 @@ class QPDF // For QPDFWriter: - // Get lists of all objects in order according to the part of a - // linearized file that they belong to. + // Get lists of all objects in order according to the part of a linearized file that they belong + // to. void getLinearizedParts( std::map const& object_stream_data, std::vector& part4, @@ -1221,8 +1095,7 @@ class QPDF // Map object to object stream that contains it void getObjectStreamData(std::map&); - // Get a list of objects that would be permitted in an object - // stream. + // Get a list of objects that would be permitted in an object stream. std::vector getCompressibleObjGens(); // methods to support page handling @@ -1418,20 +1291,16 @@ class QPDF qpdf_offset_t H_length; // length of primary hint stream }; - // Computed hint table value data structures. These tables - // contain the computed values on which the hint table values are - // based. They exclude things like number of bits and store - // actual values instead of mins and deltas. File offsets are - // also absolute rather than being offset by the size of the - // primary hint table. We populate the hint table structures from - // these during writing and compare the hint table values with - // these during validation. We ignore some values for various - // reasons described in the code. Those values are omitted from - // these structures. Note also that object numbers are object - // numbers from the input file, not the output file. - - // Naming convention: CHSomething is analogous to HSomething - // above. "CH" is computed hint. + // Computed hint table value data structures. These tables contain the computed values on which + // the hint table values are based. They exclude things like number of bits and store actual + // values instead of mins and deltas. File offsets are also absolute rather than being offset + // by the size of the primary hint table. We populate the hint table structures from these + // during writing and compare the hint table values with these during validation. We ignore + // some values for various reasons described in the code. Those values are omitted from these + // structures. Note also that object numbers are object numbers from the input file, not the + // output file. + + // Naming convention: CHSomething is analogous to HSomething above. "CH" is computed hint. struct CHPageOffsetEntry { @@ -1482,8 +1351,7 @@ class QPDF // No need for CHGeneric -- HGeneric is fine as is. - // Data structures to support optimization -- implemented in - // QPDF_optimization.cc + // Data structures to support optimization -- implemented in QPDF_optimization.cc class ObjUser { @@ -1535,8 +1403,7 @@ class QPDF bool findStartxref(); bool findEndstream(); - // methods to support linearization checking -- implemented in - // QPDF_linearization.cc + // methods to support linearization checking -- implemented in QPDF_linearization.cc void readLinearizationData(); bool checkLinearizationInternal(); void dumpLinearizationDataInternal(); @@ -1693,25 +1560,23 @@ class QPDF bool uncompressed_after_compressed{false}; bool linearization_warnings{false}; - // Linearization parameter dictionary and hint table data: may be - // read from file or computed prior to writing a linearized file + // Linearization parameter dictionary and hint table data: may be read from file or computed + // prior to writing a linearized file QPDFObjectHandle lindict; LinParameters linp; HPageOffset page_offset_hints; HSharedObject shared_object_hints; HGeneric outline_hints; - // Computed linearization data: used to populate above tables - // during writing and to compare with them during validation. - // c_ means computed. + // Computed linearization data: used to populate above tables during writing and to compare + // with them during validation. c_ means computed. LinParameters c_linp; CHPageOffset c_page_offset_data; CHSharedObject c_shared_object_data; HGeneric c_outline_data; - // Object ordering data for linearized files: initialized by - // calculateLinearizationData(). Part numbers refer to the PDF - // 1.4 specification. + // Object ordering data for linearized files: initialized by calculateLinearizationData(). + // Part numbers refer to the PDF 1.4 specification. std::vector part4; std::vector part6; std::vector part7; @@ -1723,9 +1588,8 @@ class QPDF std::map> object_to_obj_users; }; - // Keep all member variables inside the Members object, which we - // dynamically allocate. This makes it possible to add new private - // members without breaking binary compatibility. + // Keep all member variables inside the Members object, which we dynamically allocate. This + // makes it possible to add new private members without breaking binary compatibility. std::shared_ptr m; }; diff --git a/include/qpdf/QPDFAcroFormDocumentHelper.hh b/include/qpdf/QPDFAcroFormDocumentHelper.hh index 1ae593af..a86563fa 100644 --- a/include/qpdf/QPDFAcroFormDocumentHelper.hh +++ b/include/qpdf/QPDFAcroFormDocumentHelper.hh @@ -2,69 +2,55 @@ // // This file is part of qpdf. // -// 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 +// 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. +// 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. // -// Versions of qpdf prior to version 7 were released under the terms -// of version 2.0 of the Artistic License. At your option, you may -// continue to consider qpdf to be licensed under those terms. Please -// see the manual for additional information. +// Versions of qpdf prior to version 7 were released under the terms of version 2.0 of the Artistic +// License. At your option, you may continue to consider qpdf to be licensed under those terms. +// Please see the manual for additional information. #ifndef QPDFACROFORMDOCUMENTHELPER_HH #define QPDFACROFORMDOCUMENTHELPER_HH -// This document helper is intended to help with operations on -// interactive forms. Here are the key things to know: +// This document helper is intended to help with operations on interactive forms. Here are the key +// things to know: -// * The PDF specification talks about interactive forms and also -// about form XObjects. While form XObjects appear in parts of -// interactive forms, this class is concerned about interactive -// forms, not form XObjects. +// * The PDF specification talks about interactive forms and also about form XObjects. While form +// XObjects appear in parts of interactive forms, this class is concerned about interactive forms, +// not form XObjects. // -// * Interactive forms are discussed in the PDF Specification (ISO PDF -// 32000-1:2008) section 12.7. Also relevant is the section about -// Widget annotations. Annotations are discussed in section 12.5 -// with annotation dictionaries discussed in 12.5.1. Widget -// annotations are discussed specifically in section 12.5.6.19. +// * Interactive forms are discussed in the PDF Specification (ISO PDF 32000-1:2008) section 12.7. +// Also relevant is the section about Widget annotations. Annotations are discussed in +// section 12.5 with annotation dictionaries discussed in 12.5.1. Widget annotations are discussed +// specifically in section 12.5.6.19. // -// * What you need to know about the structure of interactive forms in -// PDF files: +// * What you need to know about the structure of interactive forms in PDF files: // -// - The document catalog contains the key "/AcroForm" which -// contains a list of fields. Fields are represented as a tree -// structure much like pages. Nodes in the fields tree may contain -// other fields. Fields may inherit values of many of their -// attributes from ancestors in the tree. +// - The document catalog contains the key "/AcroForm" which contains a list of fields. Fields are +// represented as a tree structure much like pages. Nodes in the fields tree may contain other +// fields. Fields may inherit values of many of their attributes from ancestors in the tree. // -// - Fields may also have children that are widget annotations. As a -// special case, and a cause of considerable confusion, if a field -// has a single annotation as a child, the annotation dictionary -// may be merged with the field dictionary. In that case, the -// field and the annotation are in the same object. Note that, -// while field dictionary attributes are inherited, annotation -// dictionary attributes are not. +// - Fields may also have children that are widget annotations. As a special case, and a cause of +// considerable confusion, if a field has a single annotation as a child, the annotation +// dictionary may be merged with the field dictionary. In that case, the field and the +// annotation are in the same object. Note that, while field dictionary attributes are +// inherited, annotation dictionary attributes are not. // -// - A page dictionary contains a key called "/Annots" which -// contains a simple list of annotations. For any given annotation -// of subtype "/Widget", you should encounter that annotation in -// the "/Annots" dictionary of a page, and you should also be able -// to reach it by traversing through the "/AcroForm" dictionary -// from the document catalog. In the simplest case (and also a -// very common case), a form field's widget annotation will be -// merged with the field object, and the object will appear -// directly both under "/Annots" in the page dictionary and under -// "/Fields" in the "/AcroForm" dictionary. In a more complex -// case, you may have to trace through various "/Kids" elements in -// the "/AcroForm" field entry until you find the annotation +// - A page dictionary contains a key called "/Annots" which contains a simple list of +// annotations. For any given annotation of subtype "/Widget", you should encounter that +// annotation in the "/Annots" dictionary of a page, and you should also be able to reach it by +// traversing through the "/AcroForm" dictionary from the document catalog. In the simplest case +// (and also a very common case), a form field's widget annotation will be merged with the field +// object, and the object will appear directly both under "/Annots" in the page dictionary and +// under "/Fields" in the "/AcroForm" dictionary. In a more complex case, you may have to trace +// through various "/Kids" elements in the "/AcroForm" field entry until you find the annotation // dictionary. #include @@ -87,34 +73,28 @@ class QPDFAcroFormDocumentHelper: public QPDFDocumentHelper QPDF_DLL virtual ~QPDFAcroFormDocumentHelper() = default; - // This class lazily creates an internal cache of the mapping - // among form fields, annotations, and pages. Methods within this - // class preserve the validity of this cache. However, if you - // modify pages' annotation dictionaries, the document's /AcroForm - // dictionary, or any form fields manually in a way that alters - // the association between forms, fields, annotations, and pages, - // it may cause this cache to become invalid. This method marks - // the cache invalid and forces it to be regenerated the next time - // it is needed. + // This class lazily creates an internal cache of the mapping among form fields, annotations, + // and pages. Methods within this class preserve the validity of this cache. However, if you + // modify pages' annotation dictionaries, the document's /AcroForm dictionary, or any form + // fields manually in a way that alters the association between forms, fields, annotations, and + // pages, it may cause this cache to become invalid. This method marks the cache invalid and + // forces it to be regenerated the next time it is needed. QPDF_DLL void invalidateCache(); QPDF_DLL bool hasAcroForm(); - // Add a form field, initializing the document's AcroForm - // dictionary if needed, updating the cache if necessary. Note - // that you are adding fields that are copies of other fields, - // this method may result in multiple fields existing with the - // same qualified name, which can have unexpected side effects. In - // that case, you should use addAndRenameFormFields() instead. + // Add a form field, initializing the document's AcroForm dictionary if needed, updating the + // cache if necessary. Note that you are adding fields that are copies of other fields, this + // method may result in multiple fields existing with the same qualified name, which can have + // unexpected side effects. In that case, you should use addAndRenameFormFields() instead. QPDF_DLL void addFormField(QPDFFormFieldObjectHelper); - // Add a collection of form fields making sure that their fully - // qualified names don't conflict with already present form - // fields. Fields within the collection of new fields that have - // the same name as each other will continue to do so. + // Add a collection of form fields making sure that their fully qualified names don't conflict + // with already present form fields. Fields within the collection of new fields that have the + // same name as each other will continue to do so. QPDF_DLL void addAndRenameFormFields(std::vector fields); @@ -122,31 +102,27 @@ class QPDFAcroFormDocumentHelper: public QPDFDocumentHelper QPDF_DLL void removeFormFields(std::set const&); - // Set the name of a field, updating internal records of field - // names. Name should be UTF-8 encoded. + // Set the name of a field, updating internal records of field names. Name should be UTF-8 + // encoded. QPDF_DLL void setFormFieldName(QPDFFormFieldObjectHelper, std::string const& name); - // Return a vector of all terminal fields in a document. Terminal - // fields are fields that have no children that are also fields. - // Terminal fields may still have children that are annotations. - // Intermediate nodes in the fields tree are not included in this - // list, but you can still reach them through the getParent method - // of the field object helper. + // Return a vector of all terminal fields in a document. Terminal fields are fields that have no + // children that are also fields. Terminal fields may still have children that are annotations. + // Intermediate nodes in the fields tree are not included in this list, but you can still reach + // them through the getParent method of the field object helper. QPDF_DLL std::vector getFormFields(); - // Return all the form fields that have the given fully-qualified - // name and also have an explicit "/T" attribute. For this - // information to be accurate, any changes to field names must be - // done through setFormFieldName() above. + // Return all the form fields that have the given fully-qualified name and also have an explicit + // "/T" attribute. For this information to be accurate, any changes to field names must be done + // through setFormFieldName() above. QPDF_DLL std::set getFieldsWithQualifiedName(std::string const& name); - // Return the annotations associated with a terminal field. Note - // that in the case of a field having a single annotation, the - // underlying object will typically be the same as the underlying - // object for the field. + // Return the annotations associated with a terminal field. Note that in the case of a field + // having a single annotation, the underlying object will typically be the same as the + // underlying object for the field. QPDF_DLL std::vector getAnnotationsForField(QPDFFormFieldObjectHelper); @@ -158,63 +134,49 @@ class QPDFAcroFormDocumentHelper: public QPDFDocumentHelper QPDF_DLL std::vector getFormFieldsForPage(QPDFPageObjectHelper); - // Return the terminal field that is associated with this - // annotation. If the annotation dictionary is merged with the - // field dictionary, the underlying object will be the same, but - // this is not always the case. Note that if you call this method - // with an annotation that is not a widget annotation, there will - // not be an associated field, and this method will return a + // Return the terminal field that is associated with this annotation. If the annotation + // dictionary is merged with the field dictionary, the underlying object will be the same, but + // this is not always the case. Note that if you call this method with an annotation that is not + // a widget annotation, there will not be an associated field, and this method will return a // helper associated with a null object (isNull() == true). QPDF_DLL QPDFFormFieldObjectHelper getFieldForAnnotation(QPDFAnnotationObjectHelper); - // Return the current value of /NeedAppearances. If - // /NeedAppearances is missing, return false as that is how PDF - // viewers are supposed to interpret it. + // Return the current value of /NeedAppearances. If /NeedAppearances is missing, return false as + // that is how PDF viewers are supposed to interpret it. QPDF_DLL bool getNeedAppearances(); - // Indicate whether appearance streams must be regenerated. If you - // modify a field value, you should call setNeedAppearances(true) - // unless you also generate an appearance stream for the - // corresponding annotation at the same time. If you generate - // appearance streams for all fields, you can call - // setNeedAppearances(false). If you use - // QPDFFormFieldObjectHelper::setV, it will automatically call - // this method unless you tell it not to. + // Indicate whether appearance streams must be regenerated. If you modify a field value, you + // should call setNeedAppearances(true) unless you also generate an appearance stream for the + // corresponding annotation at the same time. If you generate appearance streams for all fields, + // you can call setNeedAppearances(false). If you use QPDFFormFieldObjectHelper::setV, it will + // automatically call this method unless you tell it not to. QPDF_DLL void setNeedAppearances(bool); - // If /NeedAppearances is false, do nothing. Otherwise generate - // appearance streams for all widget annotations that need them. - // See comments in QPDFFormFieldObjectHelper.hh for - // generateAppearance for limitations. For checkbox and radio - // button fields, this code ensures that appearance state is - // consistent with the field's value and uses any pre-existing + // If /NeedAppearances is false, do nothing. Otherwise generate appearance streams for all + // widget annotations that need them. See comments in QPDFFormFieldObjectHelper.hh for + // generateAppearance for limitations. For checkbox and radio button fields, this code ensures + // that appearance state is consistent with the field's value and uses any pre-existing // appearance streams. QPDF_DLL void generateAppearancesIfNeeded(); - // Note: this method works on all annotations, not just ones with - // associated fields. For each annotation in old_annots, apply the - // given transformation matrix to create a new annotation. New - // annotations are appended to new_annots. If the annotation is - // associated with a form field, a new form field is created that - // points to the new annotation and is appended to new_fields, and - // the old field is added to old_fields. + // Note: this method works on all annotations, not just ones with associated fields. For each + // annotation in old_annots, apply the given transformation matrix to create a new annotation. + // New annotations are appended to new_annots. If the annotation is associated with a form + // field, a new form field is created that points to the new annotation and is appended to + // new_fields, and the old field is added to old_fields. // - // old_annots may belong to a different QPDF object. In that case, - // you should pass in from_qpdf, and copyForeignObject will be - // called automatically. If this is the case, for efficiency, you - // may pass in a QPDFAcroFormDocumentHelper for the other file to - // avoid the expensive process of creating one for each call to - // transformAnnotations. New fields and annotations are not added - // to the document or pages. You have to do that yourself after - // calling transformAnnotations. If this operation will leave - // orphaned fields behind, such as if you are replacing the old - // annotations with the new ones on the same page and the fields - // and annotations are not shared, you will also need to remove - // the old fields to prevent them from hanging round unreferenced. + // old_annots may belong to a different QPDF object. In that case, you should pass in from_qpdf, + // and copyForeignObject will be called automatically. If this is the case, for efficiency, you + // may pass in a QPDFAcroFormDocumentHelper for the other file to avoid the expensive process of + // creating one for each call to transformAnnotations. New fields and annotations are not added + // to the document or pages. You have to do that yourself after calling transformAnnotations. If + // this operation will leave orphaned fields behind, such as if you are replacing the old + // annotations with the new ones on the same page and the fields and annotations are not shared, + // you will also need to remove the old fields to prevent them from hanging round unreferenced. QPDF_DLL void transformAnnotations( QPDFObjectHandle old_annots, @@ -225,18 +187,14 @@ class QPDFAcroFormDocumentHelper: public QPDFDocumentHelper QPDF* from_qpdf = nullptr, QPDFAcroFormDocumentHelper* from_afdh = nullptr); - // Copy form fields and annotations from one page to another, - // allowing the from page to be in a different QPDF or in the same - // QPDF. This would typically be called after calling addPage to - // add field/annotation awareness. When just copying the page by - // itself, annotations end up being shared, and fields end up - // being omitted because there is no reference to the field from - // the page. This method ensures that each separate copy of a page - // has private annotations and that fields and annotations are - // properly updated to resolve conflicts that may occur from - // common resource and field names across documents. It is - // basically a wrapper around transformAnnotations that handles - // updating the receiving page. If new_fields is non-null, any + // Copy form fields and annotations from one page to another, allowing the from page to be in a + // different QPDF or in the same QPDF. This would typically be called after calling addPage to + // add field/annotation awareness. When just copying the page by itself, annotations end up + // being shared, and fields end up being omitted because there is no reference to the field from + // the page. This method ensures that each separate copy of a page has private annotations and + // that fields and annotations are properly updated to resolve conflicts that may occur from + // common resource and field names across documents. It is basically a wrapper around + // transformAnnotations that handles updating the receiving page. If new_fields is non-null, any // newly created fields are added to it. QPDF_DLL void fixCopiedAnnotations( diff --git a/include/qpdf/QPDFExc.hh b/include/qpdf/QPDFExc.hh index b53aa405..1a9e16f2 100644 --- a/include/qpdf/QPDFExc.hh +++ b/include/qpdf/QPDFExc.hh @@ -2,22 +2,19 @@ // // This file is part of qpdf. // -// 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 +// 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. +// 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. // -// Versions of qpdf prior to version 7 were released under the terms -// of version 2.0 of the Artistic License. At your option, you may -// continue to consider qpdf to be licensed under those terms. Please -// see the manual for additional information. +// Versions of qpdf prior to version 7 were released under the terms of version 2.0 of the Artistic +// License. At your option, you may continue to consider qpdf to be licensed under those terms. +// Please see the manual for additional information. #ifndef QPDFEXC_HH #define QPDFEXC_HH @@ -42,14 +39,12 @@ class QPDF_DLL_CLASS QPDFExc: public std::runtime_error QPDF_DLL virtual ~QPDFExc() noexcept = default; - // To get a complete error string, call what(), provided by - // std::exception. The accessors below return the original values - // used to create the exception. Only the error code and message - // are guaranteed to have non-zero/empty values. + // To get a complete error string, call what(), provided by std::exception. The accessors below + // return the original values used to create the exception. Only the error code and message are + // guaranteed to have non-zero/empty values. - // There is no lookup code that maps numeric error codes into - // strings. The numeric error code is just another way to get at - // the underlying issue, but it is more programmer-friendly than + // There is no lookup code that maps numeric error codes into strings. The numeric error code + // is just another way to get at the underlying issue, but it is more programmer-friendly than // trying to parse a string that is subject to change. QPDF_DLL @@ -71,8 +66,8 @@ class QPDF_DLL_CLASS QPDFExc: public std::runtime_error qpdf_offset_t offset, std::string const& message); - // This class does not use the Members pattern to avoid needless - // memory allocations during exception handling. + // This class does not use the Members pattern to avoid needless memory allocations during + // exception handling. qpdf_error_code_e error_code; std::string filename; diff --git a/include/qpdf/QPDFFormFieldObjectHelper.hh b/include/qpdf/QPDFFormFieldObjectHelper.hh index 2221684a..fbd5547f 100644 --- a/include/qpdf/QPDFFormFieldObjectHelper.hh +++ b/include/qpdf/QPDFFormFieldObjectHelper.hh @@ -2,29 +2,25 @@ // // This file is part of qpdf. // -// 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 +// 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. +// 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. // -// Versions of qpdf prior to version 7 were released under the terms -// of version 2.0 of the Artistic License. At your option, you may -// continue to consider qpdf to be licensed under those terms. Please -// see the manual for additional information. +// Versions of qpdf prior to version 7 were released under the terms of version 2.0 of the Artistic +// License. At your option, you may continue to consider qpdf to be licensed under those terms. +// Please see the manual for additional information. #ifndef QPDFFORMFIELDOBJECTHELPER_HH #define QPDFFORMFIELDOBJECTHELPER_HH -// This object helper helps with form fields for interactive forms. -// Please see comments in QPDFAcroFormDocumentHelper.hh for additional -// details. +// This object helper helps with form fields for interactive forms. Please see comments in +// QPDFAcroFormDocumentHelper.hh for additional details. #include @@ -46,37 +42,32 @@ class QPDFFormFieldObjectHelper: public QPDFObjectHelper QPDF_DLL bool isNull(); - // Return the field's parent. A form field object helper whose - // underlying object is null is returned if there is no parent. - // This condition may be tested by calling isNull(). + // Return the field's parent. A form field object helper whose underlying object is null is + // returned if there is no parent. This condition may be tested by calling isNull(). QPDF_DLL QPDFFormFieldObjectHelper getParent(); - // Return the top-level field for this field. Typically this will - // be the field itself or its parent. If is_different is provided, - // it is set to true if the top-level field is different from the - // field itself; otherwise it is set to false. + // Return the top-level field for this field. Typically this will be the field itself or its + // parent. If is_different is provided, it is set to true if the top-level field is different + // from the field itself; otherwise it is set to false. QPDF_DLL QPDFFormFieldObjectHelper getTopLevelField(bool* is_different = nullptr); - // Get a field value, possibly inheriting the value from an - // ancestor node. + // Get a field value, possibly inheriting the value from an ancestor node. QPDF_DLL QPDFObjectHandle getInheritableFieldValue(std::string const& name); - // Get an inherited field value as a string. If it is not a - // string, silently return the empty string. + // Get an inherited field value as a string. If it is not a string, silently return the empty + // string. QPDF_DLL std::string getInheritableFieldValueAsString(std::string const& name); - // Get an inherited field value of type name as a string - // representing the name. If it is not a name, silently return - // the empty string. + // Get an inherited field value of type name as a string representing the name. If it is not a + // name, silently return the empty string. QPDF_DLL std::string getInheritableFieldValueAsName(std::string const& name); - // Returns the value of /FT if present, otherwise returns the - // empty string. + // Returns the value of /FT if present, otherwise returns the empty string. QPDF_DLL std::string getFieldType(); @@ -86,60 +77,53 @@ class QPDFFormFieldObjectHelper: public QPDFObjectHelper QPDF_DLL std::string getPartialName(); - // Return the alternative field name (/TU), which is the field - // name intended to be presented to users. If not present, fall - // back to the fully qualified name. + // Return the alternative field name (/TU), which is the field name intended to be presented to + // users. If not present, fall back to the fully qualified name. QPDF_DLL std::string getAlternativeName(); - // Return the mapping field name (/TM). If not present, fall back - // to the alternative name, then to the partial name. + // Return the mapping field name (/TM). If not present, fall back to the alternative name, then + // to the partial name. QPDF_DLL std::string getMappingName(); QPDF_DLL QPDFObjectHandle getValue(); - // Return the field's value as a string. If this is called with a - // field whose value is not a string, the empty string will be - // silently returned. + // Return the field's value as a string. If this is called with a field whose value is not a + // string, the empty string will be silently returned. QPDF_DLL std::string getValueAsString(); QPDF_DLL QPDFObjectHandle getDefaultValue(); - // Return the field's default value as a string. If this is called - // with a field whose value is not a string, the empty string will - // be silently returned. + // Return the field's default value as a string. If this is called with a field whose value is + // not a string, the empty string will be silently returned. QPDF_DLL std::string getDefaultValueAsString(); - // Return the default appearance string, taking inheritance from - // the field tree into account. Returns the empty string if the - // default appearance string is not available (because it's - // erroneously absent or because this is not a variable text - // field). If not found in the field hierarchy, look in /AcroForm. + // Return the default appearance string, taking inheritance from the field tree into account. + // Returns the empty string if the default appearance string is not available (because it's + // erroneously absent or because this is not a variable text field). If not found in the field + // hierarchy, look in /AcroForm. QPDF_DLL std::string getDefaultAppearance(); - // Return the default resource dictionary for the field. This - // comes not from the field but from the document-level /AcroForm - // dictionary. While several PDF generates put a /DR key in the - // form field's dictionary, experimentation suggests that many - // popular readers, including Adobe Acrobat and Acrobat Reader, - // ignore any /DR item on the field. + // Return the default resource dictionary for the field. This comes not from the field but from + // the document-level /AcroForm dictionary. While several PDF generates put a /DR key in the + // form field's dictionary, experimentation suggests that many popular readers, including Adobe + // Acrobat and Acrobat Reader, ignore any /DR item on the field. QPDF_DLL QPDFObjectHandle getDefaultResources(); - // Return the quadding value, taking inheritance from the field - // tree into account. Returns 0 if quadding is not specified. Look - // in /AcroForm if not found in the field hierarchy. + // Return the quadding value, taking inheritance from the field tree into account. Returns 0 if + // quadding is not specified. Look in /AcroForm if not found in the field hierarchy. QPDF_DLL int getQuadding(); - // Return field flags from /Ff. The value is a logical or of - // pdf_form_field_flag_e as defined in qpdf/Constants.h + // Return field flags from /Ff. The value is a logical or of pdf_form_field_flag_e as defined in + // qpdf/Constants.h QPDF_DLL int getFlags(); @@ -148,19 +132,16 @@ class QPDFFormFieldObjectHelper: public QPDFObjectHelper // Returns true if field is of type /Tx QPDF_DLL bool isText(); - // Returns true if field is of type /Btn and flags do not indicate - // some other type of button. + // Returns true if field is of type /Btn and flags do not indicate some other type of button. QPDF_DLL bool isCheckbox(); // Returns true if field is a checkbox and is checked. QPDF_DLL bool isChecked(); - // Returns true if field is of type /Btn and flags indicate that - // it is a radio button + // Returns true if field is of type /Btn and flags indicate that it is a radio button QPDF_DLL bool isRadioButton(); - // Returns true if field is of type /Btn and flags indicate that - // it is a pushbutton + // Returns true if field is of type /Btn and flags indicate that it is a pushbutton QPDF_DLL bool isPushbutton(); // Returns true if fields if of type /Ch @@ -170,45 +151,36 @@ class QPDFFormFieldObjectHelper: public QPDFObjectHelper QPDF_DLL std::vector getChoices(); - // Set an attribute to the given value. If you have a - // QPDFAcroFormDocumentHelper and you want to set the name of a - // field, use QPDFAcroFormDocumentHelper::setFormFieldName - // instead. + // Set an attribute to the given value. If you have a QPDFAcroFormDocumentHelper and you want to + // set the name of a field, use QPDFAcroFormDocumentHelper::setFormFieldName instead. QPDF_DLL void setFieldAttribute(std::string const& key, QPDFObjectHandle value); - // Set an attribute to the given value as a Unicode string (UTF-16 - // BE encoded). The input string should be UTF-8 encoded. If you - // have a QPDFAcroFormDocumentHelper and you want to set the name - // of a field, use QPDFAcroFormDocumentHelper::setFormFieldName - // instead. + // Set an attribute to the given value as a Unicode string (UTF-16 BE encoded). The input string + // should be UTF-8 encoded. If you have a QPDFAcroFormDocumentHelper and you want to set the + // name of a field, use QPDFAcroFormDocumentHelper::setFormFieldName instead. QPDF_DLL void setFieldAttribute(std::string const& key, std::string const& utf8_value); - // Set /V (field value) to the given value. If need_appearances is - // true and the field type is either /Tx (text) or /Ch (choice), - // set /NeedAppearances to true. You can explicitly tell this - // method not to set /NeedAppearances if you are going to generate - // an appearance stream yourself. Starting with qpdf 8.3.0, this - // method handles fields of type /Btn (checkboxes, radio buttons, - // pushbuttons) specially. + // Set /V (field value) to the given value. If need_appearances is true and the field type is + // either /Tx (text) or /Ch (choice), set /NeedAppearances to true. You can explicitly tell this + // method not to set /NeedAppearances if you are going to generate an appearance stream + // yourself. Starting with qpdf 8.3.0, this method handles fields of type /Btn (checkboxes, + // radio buttons, pushbuttons) specially. QPDF_DLL void setV(QPDFObjectHandle value, bool need_appearances = true); - // Set /V (field value) to the given string value encoded as a - // Unicode string. The input value should be UTF-8 encoded. See - // comments above about /NeedAppearances. + // Set /V (field value) to the given string value encoded as a Unicode string. The input value + // should be UTF-8 encoded. See comments above about /NeedAppearances. QPDF_DLL void setV(std::string const& utf8_value, bool need_appearances = true); - // Update the appearance stream for this field. Note that qpdf's - // ability to generate appearance streams is limited. We only - // generate appearance streams for streams of type text or choice. - // The appearance uses the default parameters provided in the - // file, and it only supports ASCII characters. Quadding is - // currently ignored. While this functionality is limited, it - // should do a decent job on properly constructed PDF files when - // field values are restricted to ASCII characters. + // Update the appearance stream for this field. Note that qpdf's ability to generate appearance + // streams is limited. We only generate appearance streams for streams of type text or choice. + // The appearance uses the default parameters provided in the file, and it only supports ASCII + // characters. Quadding is currently ignored. While this functionality is limited, it should do + // a decent job on properly constructed PDF files when field values are restricted to ASCII + // characters. QPDF_DLL void generateAppearance(QPDFAnnotationObjectHelper&); diff --git a/include/qpdf/QPDFJob.hh b/include/qpdf/QPDFJob.hh index 4f90990f..37067108 100644 --- a/include/qpdf/QPDFJob.hh +++ b/include/qpdf/QPDFJob.hh @@ -2,22 +2,19 @@ // // This file is part of qpdf. // -// 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 +// 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. +// 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. // -// Versions of qpdf prior to version 7 were released under the terms -// of version 2.0 of the Artistic License. At your option, you may -// continue to consider qpdf to be licensed under those terms. Please -// see the manual for additional information. +// Versions of qpdf prior to version 7 were released under the terms of version 2.0 of the Artistic +// License. At your option, you may continue to consider qpdf to be licensed under those terms. +// Please see the manual for additional information. #ifndef QPDFJOB_HH #define QPDFJOB_HH @@ -55,99 +52,80 @@ class QPDFJob static int constexpr EXIT_IS_NOT_ENCRYPTED = qpdf_exit_is_not_encrypted; static int constexpr EXIT_CORRECT_PASSWORD = qpdf_exit_correct_password; - // QPDFUsage is thrown if there are any usage-like errors when - // calling Config methods. + // QPDFUsage is thrown if there are any usage-like errors when calling Config methods. QPDF_DLL QPDFJob(); // SETUP FUNCTIONS - // Initialize a QPDFJob object from argv, which must be a - // null-terminated array of null-terminated UTF-8-encoded C - // strings. The progname_env argument is the name of an - // environment variable which, if set, overrides the name of the - // executable for purposes of generating the --completion options. - // See QPDFArgParser for details. If a null pointer is passed in, - // the default value of "QPDF_EXECUTABLE" is used. This is used by - // the QPDF cli, which just initializes a QPDFJob from argv, calls - // run(), and handles errors and exit status issues. You can - // perform much of the cli functionality programmatically in this - // way rather than using the regular API. This is exposed in the C - // API, which makes it easier to get certain high-level qpdf - // functionality from other languages. If there are any - // command-line errors, this method will throw QPDFUsage which is - // derived from std::runtime_error. Other exceptions may be thrown - // in some cases. Note that argc, and argv should be UTF-8 - // encoded. If you are calling this from a Windows Unicode-aware - // main (wmain), see QUtil::call_main_from_wmain for information - // about converting arguments to UTF-8. This method will mutate - // arguments that are passed to it. + // Initialize a QPDFJob object from argv, which must be a null-terminated array of + // null-terminated UTF-8-encoded C strings. The progname_env argument is the name of an + // environment variable which, if set, overrides the name of the executable for purposes of + // generating the --completion options. See QPDFArgParser for details. If a null pointer is + // passed in, the default value of "QPDF_EXECUTABLE" is used. This is used by the QPDF cli, + // which just initializes a QPDFJob from argv, calls run(), and handles errors and exit status + // issues. You can perform much of the cli functionality programmatically in this way rather + // than using the regular API. This is exposed in the C API, which makes it easier to get + // certain high-level qpdf functionality from other languages. If there are any command-line + // errors, this method will throw QPDFUsage which is derived from std::runtime_error. Other + // exceptions may be thrown in some cases. Note that argc, and argv should be UTF-8 encoded. If + // you are calling this from a Windows Unicode-aware main (wmain), see + // QUtil::call_main_from_wmain for information about converting arguments to UTF-8. This method + // will mutate arguments that are passed to it. QPDF_DLL void initializeFromArgv(char const* const argv[], char const* progname_env = nullptr); - // Initialize a QPDFJob from json. Passing partial = true prevents - // this method from doing the final checks (calling - // checkConfiguration) after processing the json file. This makes - // it possible to initialize QPDFJob in stages using multiple json - // files or to have a json file that can be processed from the CLI - // with --job-json-file and be combined with other arguments. For - // example, you might include only encryption parameters, leaving - // it up to the rest of the command-line arguments to provide - // input and output files. initializeFromJson is called with - // partial = true when invoked from the command line. To make sure - // that the json file is fully valid on its own, just don't - // specify any other command-line flags. If there are any - // configuration errors, QPDFUsage is thrown. Some error messages - // may be CLI-centric. If an an exception tells you to use the - // "--some-option" option, set the "someOption" key in the JSON + // Initialize a QPDFJob from json. Passing partial = true prevents this method from doing the + // final checks (calling checkConfiguration) after processing the json file. This makes it + // possible to initialize QPDFJob in stages using multiple json files or to have a json file + // that can be processed from the CLI with --job-json-file and be combined with other arguments. + // For example, you might include only encryption parameters, leaving it up to the rest of the + // command-line arguments to provide input and output files. initializeFromJson is called with + // partial = true when invoked from the command line. To make sure that the json file is fully + // valid on its own, just don't specify any other command-line flags. If there are any + // configuration errors, QPDFUsage is thrown. Some error messages may be CLI-centric. If an + // exception tells you to use the "--some-option" option, set the "someOption" key in the JSON // object instead. QPDF_DLL void initializeFromJson(std::string const& json, bool partial = false); - // Set name that is used to prefix verbose messages, progress - // messages, and other things that the library writes to output - // and error streams on the caller's behalf. Defaults to "qpdf". + // Set name that is used to prefix verbose messages, progress messages, and other things that + // the library writes to output and error streams on the caller's behalf. Defaults to "qpdf". QPDF_DLL void setMessagePrefix(std::string const&); QPDF_DLL std::string getMessagePrefix() const; - // To capture or redirect output, configure the logger returned by - // getLogger(). By default, all QPDF and QPDFJob objects share the - // global logger. If you need a private logger for some reason, - // pass a new one to setLogger(). See comments in QPDFLogger.hh - // for details on configuring the logger. + // To capture or redirect output, configure the logger returned by getLogger(). By default, all + // QPDF and QPDFJob objects share the global logger. If you need a private logger for some + // reason, pass a new one to setLogger(). See comments in QPDFLogger.hh for details on + // configuring the logger. // - // If you set a custom logger here, the logger will be passed to - // all subsequent QPDF objects created by this QPDFJob object. + // If you set a custom logger here, the logger will be passed to all subsequent QPDF objects + // created by this QPDFJob object. QPDF_DLL std::shared_ptr getLogger(); QPDF_DLL void setLogger(std::shared_ptr); - // This deprecated method is the old way to capture output, but it - // didn't capture all output. See comments above for getLogger and - // setLogger. This will be removed in QPDF 12. For now, it - // configures a private logger, separating this object from the - // default logger, and calls setOutputStreams on that logger. See - // QPDFLogger.hh for additional details. + // This deprecated method is the old way to capture output, but it didn't capture all output. + // See comments above for getLogger and setLogger. This will be removed in QPDF 12. For now, it + // configures a private logger, separating this object from the default logger, and calls + // setOutputStreams on that logger. See QPDFLogger.hh for additional details. [[deprecated("configure logger from getLogger() or call setLogger()")]] QPDF_DLL void setOutputStreams(std::ostream* out_stream, std::ostream* err_stream); - // You can register a custom progress reporter to be called by - // QPDFWriter (see QPDFWriter::registerProgressReporter). This is - // only called if you also request progress reporting through - // normal configuration methods (e.g., pass --progress, call + // You can register a custom progress reporter to be called by QPDFWriter (see + // QPDFWriter::registerProgressReporter). This is only called if you also request progress + // reporting through normal configuration methods (e.g., pass --progress, call // config()->progress, etc.) QPDF_DLL void registerProgressReporter(std::function); - // Check to make sure no contradictory options have been - // specified. This is called automatically after initializing from - // argv or json and is also called by run, but you can call it - // manually as well. It throws a QPDFUsage exception if there are - // any errors. This Config object (see CONFIGURATION) also has a - // checkConfiguration method which calls this one. + // Check to make sure no contradictory options have been specified. This is called automatically + // after initializing from argv or json and is also called by run, but you can call it manually + // as well. It throws a QPDFUsage exception if there are any errors. This Config object (see + // CONFIGURATION) also has a checkConfiguration method which calls this one. QPDF_DLL void checkConfiguration(); @@ -157,8 +135,7 @@ class QPDFJob // SEE BELOW FOR MORE PUBLIC METHODS AND CLASSES private: - // These structures are private but we need to define them before - // the public Config classes. + // These structures are private but we need to define them before the public Config classes. struct CopyAttachmentFrom { std::string path; @@ -197,33 +174,27 @@ class QPDFJob // Configuration classes are implemented in QPDFJob_config.cc. - // The config() method returns a shared pointer to a Config - // object. The Config object contains methods that correspond with - // qpdf command-line arguments. You can use a fluent interface to - // configure a QPDFJob object that would do exactly the same thing - // as a specific qpdf command. The example qpdf-job.cc contains an - // example of this usage. You can also use initializeFromJson or - // initializeFromArgv to initialize a QPDFJob object. + // The config() method returns a shared pointer to a Config object. The Config object contains + // methods that correspond with qpdf command-line arguments. You can use a fluent interface to + // configure a QPDFJob object that would do exactly the same thing as a specific qpdf command. + // The example qpdf-job.cc contains an example of this usage. You can also use + // initializeFromJson or initializeFromArgv to initialize a QPDFJob object. // Notes about the Config methods: // - // * Most of the method declarations are automatically generated - // in header files that are included within the class - // definitions. They correspond in predictable ways to the - // command-line arguments and are generated from the same code - // that generates the command-line argument parsing code. + // * Most of the method declarations are automatically generated in header files that are + // included within the class definitions. They correspond in predictable ways to the + // command-line arguments and are generated from the same code that generates the command-line + // argument parsing code. // - // * Methods return pointers, rather than references, to - // configuration objects. References might feel more familiar to - // users of fluent interfaces, so why do we use pointers? The - // main methods that create them return smart pointers so that - // users can initialize them when needed, which you can't do - // with references. Returning pointers instead of references - // makes for a more uniform interface. - - // Maintainer documentation: see the section in README-maintainer - // called "HOW TO ADD A COMMAND-LINE ARGUMENT", which contains - // references to additional places in the documentation. + // * Methods return pointers, rather than references, to configuration objects. References + // might feel more familiar to users of fluent interfaces, so why do we use pointers? The + // main methods that create them return smart pointers so that users can initialize them when + // needed, which you can't do with references. Returning pointers instead of references makes + // for a more uniform interface. + + // Maintainer documentation: see the section in README-maintainer called "HOW TO ADD A + // COMMAND-LINE ARGUMENT", which contains references to additional places in the documentation. class Config; @@ -374,13 +345,11 @@ class QPDFJob QPDFJob& o; }; - // Return a top-level configuration item. See CONFIGURATION above - // for details. If an invalid configuration is created (such as - // supplying contradictory options, omitting an input file, etc.), - // QPDFUsage is thrown. Note that error messages are CLI-centric, - // but you can map them into config calls. For example, if an - // exception tells you to use the --some-option flag, you should - // call config()->someOption() instead. + // Return a top-level configuration item. See CONFIGURATION above for details. If an invalid + // configuration is created (such as supplying contradictory options, omitting an input file, + // etc.), QPDFUsage is thrown. Note that error messages are CLI-centric, but you can map them + // into config calls. For example, if an exception tells you to use the --some-option flag, you + // should call config()->someOption() instead. QPDF_DLL std::shared_ptr config(); @@ -388,33 +357,27 @@ class QPDFJob QPDF_DLL void run(); - // The following two methods allow a job to be run in two stages - creation - // of a QPDF object and writing of the QPDF object. This allows the QPDF - // object to be modified prior to writing it out. See - // examples/qpdfjob-remove-annotations for an illustration of its use. + // The following two methods allow a job to be run in two stages - creation of a QPDF object and + // writing of the QPDF object. This allows the QPDF object to be modified prior to writing it + // out. See examples/qpdfjob-remove-annotations for an illustration of its use. - // Run the first stage of the job. Return a nullptr if the configuration is - // not valid. + // Run the first stage of the job. Return a nullptr if the configuration is not valid. QPDF_DLL std::unique_ptr createQPDF(); - // Run the second stage of the job. Do nothing if a nullptr is passed as - // parameter. + // Run the second stage of the job. Do nothing if a nullptr is passed as parameter. QPDF_DLL void writeQPDF(QPDF& qpdf); - // CHECK STATUS -- these methods provide information known after - // run() is called. + // CHECK STATUS -- these methods provide information known after run() is called. QPDF_DLL bool hasWarnings() const; - // Return one of the EXIT_* constants defined at the top of the - // class declaration. This may be called after run() when run() - // did not throw an exception. Takes into consideration whether - // isEncrypted or requiresPassword was called. Note that this - // function does not know whether run() threw an exception, so - // code that uses this to determine how to exit should explicitly + // Return one of the EXIT_* constants defined at the top of the class declaration. This may be + // called after run() when run() did not throw an exception. Takes into consideration whether + // isEncrypted or requiresPassword was called. Note that this function does not know whether + // run() threw an exception, so code that uses this to determine how to exit should explicitly // use EXIT_ERROR if run() threw an exception. QPDF_DLL int getExitCode() const; @@ -423,24 +386,22 @@ class QPDFJob QPDF_DLL unsigned long getEncryptionStatus(); - // HELPER FUNCTIONS -- methods useful for calling in handlers that - // interact with QPDFJob during run or initialization. + // HELPER FUNCTIONS -- methods useful for calling in handlers that interact with QPDFJob during + // run or initialization. - // If in verbose mode, call the given function, passing in the - // output stream and message prefix. + // If in verbose mode, call the given function, passing in the output stream and message prefix. QPDF_DLL void doIfVerbose(std::function fn); - // Provide a string that is the help information ("schema" for the - // qpdf-specific JSON object) for the specified version of JSON - // output. + // Provide a string that is the help information ("schema" for the qpdf-specific JSON object) + // for the specified version of JSON output. QPDF_DLL static std::string json_out_schema(int version); [[deprecated("use json_out_schema(version)")]] static std::string QPDF_DLL json_out_schema_v1(); - // Provide a string that is the help information for specified - // version of JSON format for QPDFJob. + // Provide a string that is the help information for specified version of JSON format for + // QPDFJob. QPDF_DLL static std::string job_json_schema(int version); diff --git a/include/qpdf/QPDFObjectHandle.hh b/include/qpdf/QPDFObjectHandle.hh index 358f0465..45ad1079 100644 --- a/include/qpdf/QPDFObjectHandle.hh +++ b/include/qpdf/QPDFObjectHandle.hh @@ -66,9 +66,8 @@ class QPDFObjectHandle friend class QPDFParser; public: - // This class is used by replaceStreamData. It provides an - // alternative way of associating stream data with a stream. See - // comments on replaceStreamData and newStream for additional + // This class is used by replaceStreamData. It provides an alternative way of associating + // stream data with a stream. See comments on replaceStreamData and newStream for additional // details. class QPDF_DLL_CLASS StreamDataProvider { @@ -78,55 +77,40 @@ class QPDFObjectHandle QPDF_DLL virtual ~StreamDataProvider(); - // The implementation of this function must write stream data - // to the given pipeline. The stream data must conform to - // whatever filters are explicitly associated with the stream. - // QPDFWriter may, in some cases, add compression, but if it - // does, it will update the filters as needed. Every call to - // provideStreamData for a given stream must write the same - // data. Note that, when writing linearized files, qpdf will - // call your provideStreamData twice, and if it generates - // different output, you risk generating invalid output or - // having qpdf throw an exception. The object ID and - // generation passed to this method are those that belong to - // the stream on behalf of which the provider is called. They - // may be ignored or used by the implementation for indexing - // or other purposes. This information is made available just - // to make it more convenient to use a single - // StreamDataProvider object to provide data for multiple - // streams. + // The implementation of this function must write stream data to the given pipeline. The + // stream data must conform to whatever filters are explicitly associated with the stream. + // QPDFWriter may, in some cases, add compression, but if it does, it will update the + // filters as needed. Every call to provideStreamData for a given stream must write the same + // data. Note that, when writing linearized files, qpdf will call your provideStreamData + // twice, and if it generates different output, you risk generating invalid output or having + // qpdf throw an exception. The object ID and generation passed to this method are those + // that belong to the stream on behalf of which the provider is called. They may be ignored + // or used by the implementation for indexing or other purposes. This information is made + // available just to make it more convenient to use a single StreamDataProvider object to + // provide data for multiple streams. // A few things to keep in mind: // - // * Stream data providers must not modify any objects since - // they may be called after some parts of the file have - // already been written. + // * Stream data providers must not modify any objects since they may be called after some + // parts of the file have already been written. // - // * Since qpdf may call provideStreamData multiple times when - // writing linearized files, if the work done by your stream - // data provider is slow or computationally intensive, you + // * Since qpdf may call provideStreamData multiple times when writing linearized files, if + // the work done by your stream data provider is slow or computationally intensive, you // might want to implement your own cache. // - // * Once you have called replaceStreamData, the original - // stream data is no longer directly accessible from the - // stream, but this is easy to work around by copying the - // stream to a separate QPDF object. The qpdf library - // implements this very efficiently without actually making - // a copy of the stream data. You can find examples of this - // pattern in some of the examples, including - // pdf-custom-filter.cc and pdf-invert-images.cc. - - // Prior to qpdf 10.0.0, it was not possible to handle errors - // the way pipeStreamData does or to pass back success. - // Starting in qpdf 10.0.0, those capabilities have been added - // by allowing an alternative provideStreamData to be - // implemented. You must implement at least one of the - // versions of provideStreamData below. If you implement the - // version that supports retry and returns a value, you should - // pass true as the value of supports_retry in the base class - // constructor. This will cause the library to call that - // version of the method, which should also return a boolean - // indicating whether it ran without errors. + // * Once you have called replaceStreamData, the original stream data is no longer directly + // accessible from the stream, but this is easy to work around by copying the stream to + // a separate QPDF object. The qpdf library implements this very efficiently without + // actually making a copy of the stream data. You can find examples of this pattern in + // some of the examples, including pdf-custom-filter.cc and pdf-invert-images.cc. + + // Prior to qpdf 10.0.0, it was not possible to handle errors the way pipeStreamData does or + // to pass back success. Starting in qpdf 10.0.0, those capabilities have been added by + // allowing an alternative provideStreamData to be implemented. You must implement at least + // one of the versions of provideStreamData below. If you implement the version that + // supports retry and returns a value, you should pass true as the value of supports_retry + // in the base class constructor. This will cause the library to call that version of the + // method, which should also return a boolean indicating whether it ran without errors. QPDF_DLL virtual void provideStreamData(QPDFObjGen const& og, Pipeline* pipeline); QPDF_DLL @@ -142,41 +126,31 @@ class QPDFObjectHandle bool supports_retry; }; - // The TokenFilter class provides a way to filter content streams - // in a lexically aware fashion. TokenFilters can be attached to - // streams using the addTokenFilter or addContentTokenFilter - // methods or can be applied on the spot by filterPageContents. - // You may also use Pl_QPDFTokenizer directly if you need full - // control. + // The TokenFilter class provides a way to filter content streams in a lexically aware fashion. + // TokenFilters can be attached to streams using the addTokenFilter or addContentTokenFilter + // methods or can be applied on the spot by filterPageContents. You may also use + // Pl_QPDFTokenizer directly if you need full control. // - // The handleToken method is called for each token, including the - // eof token, and then handleEOF is called at the very end. - // Handlers may call write (or writeToken) to pass data - // downstream. Please see examples/pdf-filter-tokens.cc and - // examples/pdf-count-strings.cc for examples of using - // TokenFilters. + // The handleToken method is called for each token, including the eof token, and then handleEOF + // is called at the very end. Handlers may call write (or writeToken) to pass data downstream. + // Please see examples/pdf-filter-tokens.cc and examples/pdf-count-strings.cc for examples of + // using TokenFilters. // - // Please note that when you call token.getValue() on a token of - // type tt_string or tt_name, you get the canonical, "parsed" - // representation of the token. For a string, this means that - // there are no delimiters, and for a name, it means that all - // escaping (# followed by two hex digits) has been resolved. - // qpdf's internal representation of a name includes the leading - // slash. As such, you can't write the value of token.getValue() - // directly to output that is supposed to be valid PDF syntax. If - // you want to do that, you need to call writeToken() instead, or - // you can retrieve the token as it appeared in the input with - // token.getRawValue(). To construct a new string or name token - // from a canonical representation, use + // Please note that when you call token.getValue() on a token of type tt_string or tt_name, you + // get the canonical, "parsed" representation of the token. For a string, this means that there + // are no delimiters, and for a name, it means that all escaping (# followed by two hex digits) + // has been resolved. qpdf's internal representation of a name includes the leading slash. As + // such, you can't write the value of token.getValue() directly to output that is supposed to be + // valid PDF syntax. If you want to do that, you need to call writeToken() instead, or you can + // retrieve the token as it appeared in the input with token.getRawValue(). To construct a new + // string or name token from a canonical representation, use // QPDFTokenizer::Token(QPDFTokenizer::tt_string, "parsed-str") or // QPDFTokenizer::Token(QPDFTokenizer::tt_name, - // "/Canonical-Name"). Tokens created this way won't have a - // PDF-syntax raw value, but you can still write them with - // writeToken(). Example: + // "/Canonical-Name"). Tokens created this way won't have a PDF-syntax raw value, but you can + // still write them with writeToken(). Example: // writeToken(QPDFTokenizer::Token(QPDFTokenizer::tt_name, "/text/plain")) // would write `/text#2fplain`, and - // writeToken(QPDFTokenizer::Token(QPDFTokenizer::tt_string, "a\\(b")) - // would write `(a\(b)`. + // writeToken(QPDFTokenizer::Token(QPDFTokenizer::tt_string, "a\\(b")) would write `(a\(b)`. class QPDF_DLL_CLASS TokenFilter { public: @@ -215,8 +189,8 @@ class QPDFObjectHandle Pipeline* pipeline; }; - // This class is used by parse to decrypt strings when reading an - // object that contains encrypted strings. + // This class is used by parse to decrypt strings when reading an object that contains encrypted + // strings. class StringDecrypter { public: @@ -225,9 +199,8 @@ class QPDFObjectHandle virtual void decryptString(std::string& val) = 0; }; - // This class is used by parsePageContents. Callers must - // instantiate a subclass of this with handlers defined to accept - // QPDFObjectHandles that are parsed from the stream. + // This class is used by parsePageContents. Callers must instantiate a subclass of this with + // handlers defined to accept QPDFObjectHandles that are parsed from the stream. class QPDF_DLL_CLASS ParserCallbacks { public: @@ -241,17 +214,14 @@ class QPDFObjectHandle virtual void handleEOF() = 0; - // Override this if you want to know the full size of the - // contents, possibly after concatenation of multiple streams. - // This is called before the first call to handleObject. + // Override this if you want to know the full size of the contents, possibly after + // concatenation of multiple streams. This is called before the first call to handleObject. QPDF_DLL virtual void contentSize(size_t); protected: - // Implementors may call this method during parsing to - // terminate parsing early. This method throws an exception - // that is caught by parsePageContents, so its effect is - // immediate. + // Implementors may call this method during parsing to terminate parsing early. This method + // throws an exception that is caught by parsePageContents, so its effect is immediate. QPDF_DLL void terminateParsing(); }; @@ -281,9 +251,8 @@ class QPDFObjectHandle double ury; }; - // Convenience object for transformation matrices. See also - // QPDFMatrix. Unfortunately we can't replace this with QPDFMatrix - // because QPDFMatrix's default constructor creates the identity + // Convenience object for transformation matrices. See also QPDFMatrix. Unfortunately we can't + // replace this with QPDFMatrix because QPDFMatrix's default constructor creates the identity // transform matrix and this one is all zeroes. class Matrix { @@ -324,25 +293,22 @@ class QPDFObjectHandle QPDF_DLL inline bool isInitialized() const; - // This method returns true if the QPDFObjectHandle objects point - // to exactly the same underlying object, meaning that changes to - // one are reflected in the other, or "if you paint one, the other - // one changes color." This does not perform a structural - // comparison of the contents of the objects. + // This method returns true if the QPDFObjectHandle objects point to exactly the same underlying + // object, meaning that changes to one are reflected in the other, or "if you paint one, the + // other one changes color." This does not perform a structural comparison of the contents of + // the objects. QPDF_DLL bool isSameObjectAs(QPDFObjectHandle const&) const; - // Return type code and type name of underlying object. These are - // useful for doing rapid type tests (like switch statements) or - // for testing and debugging. + // Return type code and type name of underlying object. These are useful for doing rapid type + // tests (like switch statements) or for testing and debugging. QPDF_DLL qpdf_object_type_e getTypeCode(); QPDF_DLL char const* getTypeName(); - // Exactly one of these will return true for any initialized - // object. Operator and InlineImage are only allowed in content - // streams. + // Exactly one of these will return true for any initialized object. Operator and InlineImage + // are only allowed in content streams. QPDF_DLL bool isBool(); QPDF_DLL @@ -368,26 +334,22 @@ class QPDFObjectHandle QPDF_DLL bool isReserved(); - // True for objects that are direct nulls. Does not attempt to - // resolve objects. This is intended for internal use, but it can - // be used as an efficient way to check for nulls that are not + // True for objects that are direct nulls. Does not attempt to resolve objects. This is intended + // for internal use, but it can be used as an efficient way to check for nulls that are not // indirect objects. QPDF_DLL bool isDirectNull() const; - // This returns true in addition to the query for the specific - // type for indirect objects. + // This returns true in addition to the query for the specific type for indirect objects. QPDF_DLL inline bool isIndirect() const; - // This returns true for indirect objects from a QPDF that has - // been destroyed. Trying unparse such an object will throw a - // logic_error. + // This returns true for indirect objects from a QPDF that has been destroyed. Trying unparse + // such an object will throw a logic_error. QPDF_DLL bool isDestroyed(); - // True for everything except array, dictionary, stream, word, and - // inline image. + // True for everything except array, dictionary, stream, word, and inline image. QPDF_DLL bool isScalar(); @@ -395,53 +357,44 @@ class QPDFObjectHandle QPDF_DLL bool isNameAndEquals(std::string const& name); - // True if the object is a dictionary of the specified type and - // subtype, if any. + // True if the object is a dictionary of the specified type and subtype, if any. QPDF_DLL bool isDictionaryOfType(std::string const& type, std::string const& subtype = ""); - // True if the object is a stream of the specified type and - // subtype, if any. + // True if the object is a stream of the specified type and subtype, if any. QPDF_DLL bool isStreamOfType(std::string const& type, std::string const& subtype = ""); // Public factory methods - // Wrap an object in an array if it is not already an array. This - // is a helper for cases in which something in a PDF may either be - // a single item or an array of items, which is a common idiom. + // Wrap an object in an array if it is not already an array. This is a helper for cases in which + // something in a PDF may either be a single item or an array of items, which is a common idiom. QPDF_DLL QPDFObjectHandle wrapInArray(); - // Construct an object of any type from a string representation of - // the object. Throws QPDFExc with an empty filename and an - // offset into the string if there is an error. Any indirect - // object syntax (obj gen R) will cause a logic_error exception to - // be thrown. If object_description is provided, it will appear - // in the message of any QPDFExc exception thrown for invalid - // syntax. See also the global `operator ""_qpdf` defined below. + // Construct an object of any type from a string representation of the object. Throws QPDFExc + // with an empty filename and an offset into the string if there is an error. Any indirect + // object syntax (obj gen R) will cause a logic_error exception to be thrown. If + // object_description is provided, it will appear in the message of any QPDFExc exception thrown + // for invalid syntax. See also the global `operator ""_qpdf` defined below. QPDF_DLL static QPDFObjectHandle parse(std::string const& object_str, std::string const& object_description = ""); - // Construct an object of any type from a string representation of - // the object. Indirect object syntax (obj gen R) is allowed and - // will create indirect references within the passed-in context. - // If object_description is provided, it will appear in the - // message of any QPDFExc exception thrown for invalid syntax. - // Note that you can't parse an indirect object reference all by - // itself as parse will stop at the end of the first complete - // object, which will just be the first number and will report - // that there is trailing data at the end of the string. + // Construct an object of any type from a string representation of the object. Indirect object + // syntax (obj gen R) is allowed and will create indirect references within the passed-in + // context. If object_description is provided, it will appear in the message of any QPDFExc + // exception thrown for invalid syntax. Note that you can't parse an indirect object reference + // all by itself as parse will stop at the end of the first complete object, which will just be + // the first number and will report that there is trailing data at the end of the string. QPDF_DLL static QPDFObjectHandle parse(QPDF* context, std::string const& object_str, std::string const& object_description = ""); - // Construct an object as above by reading from the given - // InputSource at its current position and using the tokenizer you - // supply. Indirect objects and encrypted strings are permitted. - // This method was intended to be called by QPDF for parsing - // objects that are ready from the object's input stream. + // Construct an object as above by reading from the given InputSource at its current position + // and using the tokenizer you supply. Indirect objects and encrypted strings are permitted. + // This method was intended to be called by QPDF for parsing objects that are ready from the + // object's input stream. QPDF_DLL static QPDFObjectHandle parse( std::shared_ptr input, @@ -451,60 +404,46 @@ class QPDFObjectHandle StringDecrypter* decrypter, QPDF* context); - // Return the offset where the object was found when parsed. A - // negative value means that the object was created without - // parsing. If the object is in a stream, the offset is from the - // beginning of the stream. Otherwise, the offset is from the - // beginning of the file. + // Return the offset where the object was found when parsed. A negative value means that the + // object was created without parsing. If the object is in a stream, the offset is from the + // beginning of the stream. Otherwise, the offset is from the beginning of the file. QPDF_DLL qpdf_offset_t getParsedOffset(); - // Older method: stream_or_array should be the value of /Contents - // from a page object. It's more convenient to just call - // QPDFPageObjectHelper::parsePageContents on the page object, and - // error messages will also be more useful because the page object - // information will be known. + // Older method: stream_or_array should be the value of /Contents from a page object. It's more + // convenient to just call QPDFPageObjectHelper::parsePageContents on the page object, and error + // messages will also be more useful because the page object information will be known. QPDF_DLL static void parseContentStream(QPDFObjectHandle stream_or_array, ParserCallbacks* callbacks); - // When called on a stream or stream array that is some page's - // content streams, do the same as pipePageContents. This method - // is a lower level way to do what - // QPDFPageObjectHelper::pipePageContents does, but it allows you - // to perform this operation on a contents object that is - // disconnected from a page object. The description argument - // should describe the containing page and is used in error - // messages. The all_description argument is initialized to - // something that could be used to describe the result of the - // pipeline. It is the description amended with the identifiers of - // the underlying objects. Please note that if there is an array - // of content streams, p->finish() is called after each stream. If - // you pass a pipeline that doesn't allow write() to be called - // after finish(), you can wrap it in an instance of - // Pl_Concatenate and then call manualFinish() on the - // Pl_Concatenate pipeline at the end. + // When called on a stream or stream array that is some page's content streams, do the same as + // pipePageContents. This method is a lower level way to do what + // QPDFPageObjectHelper::pipePageContents does, but it allows you to perform this operation on a + // contents object that is disconnected from a page object. The description argument should + // describe the containing page and is used in error messages. The all_description argument is + // initialized to something that could be used to describe the result of the pipeline. It is the + // description amended with the identifiers of the underlying objects. Please note that if there + // is an array of content streams, p->finish() is called after each stream. If you pass a + // pipeline that doesn't allow write() to be called after finish(), you can wrap it in an + // instance of Pl_Concatenate and then call manualFinish() on the Pl_Concatenate pipeline at the + // end. QPDF_DLL void pipeContentStreams(Pipeline* p, std::string const& description, std::string& all_description); - // As of qpdf 8, it is possible to add custom token filters to a - // stream. The tokenized stream data is passed through the token - // filter after all original filters but before content stream - // normalization if requested. This is a low-level interface to - // add it to a stream. You will usually want to call - // QPDFPageObjectHelper::addContentTokenFilter instead, which can - // be applied to a page object, and which will automatically - // handle the case of pages whose contents are split across - // multiple streams. + // As of qpdf 8, it is possible to add custom token filters to a stream. The tokenized stream + // data is passed through the token filter after all original filters but before content stream + // normalization if requested. This is a low-level interface to add it to a stream. You will + // usually want to call QPDFPageObjectHelper::addContentTokenFilter instead, which can be + // applied to a page object, and which will automatically handle the case of pages whose + // contents are split across multiple streams. QPDF_DLL void addTokenFilter(std::shared_ptr token_filter); - // Legacy helpers for parsing content streams. These methods are - // not going away, but newer code should call the correspond - // methods in QPDFPageObjectHelper instead. The specification and - // behavior of these methods are the same as the identically named - // methods in that class, but newer functionality will be added - // there. + // Legacy helpers for parsing content streams. These methods are not going away, but newer code + // should call the correspond methods in QPDFPageObjectHelper instead. The specification and + // behavior of these methods are the same as the identically named methods in that class, but + // newer functionality will be added there. QPDF_DLL void parsePageContents(ParserCallbacks* callbacks); QPDF_DLL @@ -516,13 +455,12 @@ class QPDFObjectHandle void addContentTokenFilter(std::shared_ptr token_filter); // End legacy content stream helpers - // Called on a stream to filter the stream as if it were page - // contents. This can be used to apply a TokenFilter to a form - // XObject, whose data is in the same format as a content stream. + // Called on a stream to filter the stream as if it were page contents. This can be used to + // apply a TokenFilter to a form XObject, whose data is in the same format as a content stream. QPDF_DLL void filterAsContents(TokenFilter* filter, Pipeline* next = nullptr); - // Called on a stream to parse the stream as page contents. This - // can be used to parse a form XObject. + // Called on a stream to parse the stream as page contents. This can be used to parse a form + // XObject. QPDF_DLL void parseAsContents(ParserCallbacks* callbacks); @@ -538,32 +476,25 @@ class QPDFObjectHandle QPDF_DLL static QPDFObjectHandle newReal(double value, int decimal_places = 0, bool trim_trailing_zeroes = true); - // Note about name objects: qpdf's internal representation of a - // PDF name is a sequence of bytes, excluding the NUL character, - // and starting with a slash. Name objects as represented in the - // PDF specification can contain characters escaped with #, but - // such escaping is not of concern when calling QPDFObjectHandle - // methods not directly relating to parsing. For example, - // newName("/text/plain").getName() and - // parse("/text#2fplain").getName() both return "/text/plain", - // while newName("/text/plain").unparse() and - // parse("/text#2fplain").unparse() both return "/text#2fplain". - // When working with the qpdf API for creating, retrieving, and - // modifying objects, you want to work with the internal, - // canonical representation. For names containing alphanumeric - // characters, dashes, and underscores, there is no difference - // between the two representations. For a lengthy discussion, see + // Note about name objects: qpdf's internal representation of a PDF name is a sequence of bytes, + // excluding the NUL character, and starting with a slash. Name objects as represented in the + // PDF specification can contain characters escaped with #, but such escaping is not of concern + // when calling QPDFObjectHandle methods not directly relating to parsing. For example, + // newName("/text/plain").getName() and parse("/text#2fplain").getName() both return + // "/text/plain", while newName("/text/plain").unparse() and parse("/text#2fplain").unparse() + // both return "/text#2fplain". When working with the qpdf API for creating, retrieving, and + // modifying objects, you want to work with the internal, canonical representation. For names + // containing alphanumeric characters, dashes, and underscores, there is no difference between + // the two representations. For a lengthy discussion, see // https://github.com/qpdf/qpdf/discussions/625. QPDF_DLL static QPDFObjectHandle newName(std::string const& name); QPDF_DLL static QPDFObjectHandle newString(std::string const& str); - // Create a string encoded from the given utf8-encoded string - // appropriately encoded to appear in PDF files outside of content - // streams, such as in document metadata form field values, page - // labels, outlines, and similar locations. We try ASCII first, - // then PDFDocEncoding, then UTF-16 as needed to successfully - // encode all the characters. + // Create a string encoded from the given utf8-encoded string appropriately encoded to appear in + // PDF files outside of content streams, such as in document metadata form field values, page + // labels, outlines, and similar locations. We try ASCII first, then PDFDocEncoding, then UTF-16 + // as needed to successfully encode all the characters. QPDF_DLL static QPDFObjectHandle newUnicodeString(std::string const& utf8_str); QPDF_DLL @@ -585,86 +516,67 @@ class QPDFObjectHandle QPDF_DLL static QPDFObjectHandle newDictionary(std::map const& items); - // Create an array from a rectangle. Equivalent to the rectangle - // form of newArray. + // Create an array from a rectangle. Equivalent to the rectangle form of newArray. QPDF_DLL static QPDFObjectHandle newFromRectangle(Rectangle const&); - // Create an array from a matrix. Equivalent to the matrix - // form of newArray. + // Create an array from a matrix. Equivalent to the matrix form of newArray. QPDF_DLL static QPDFObjectHandle newFromMatrix(Matrix const&); QPDF_DLL static QPDFObjectHandle newFromMatrix(QPDFMatrix const&); - // Note: new stream creation methods have were added to the QPDF - // class starting with version 11.2.0. The ones in this class are - // here for backward compatibility. + // Note: new stream creation methods have were added to the QPDF class starting with + // version 11.2.0. The ones in this class are here for backward compatibility. - // Create a new stream and associate it with the given qpdf - // object. A subsequent call must be made to replaceStreamData() - // to provide data for the stream. The stream's dictionary may be - // retrieved by calling getDict(), and the resulting dictionary - // may be modified. Alternatively, you can create a new dictionary - // and call replaceDict to install it. From QPDF 11.2, you can + // Create a new stream and associate it with the given qpdf object. A subsequent call must be + // made to replaceStreamData() to provide data for the stream. The stream's dictionary may be + // retrieved by calling getDict(), and the resulting dictionary may be modified. Alternatively, + // you can create a new dictionary and call replaceDict to install it. From QPDF 11.2, you can // call QPDF::newStream() instead. QPDF_DLL static QPDFObjectHandle newStream(QPDF* qpdf); - // Create a new stream and associate it with the given qpdf - // object. Use the given buffer as the stream data. The stream - // dictionary's /Length key will automatically be set to the size - // of the data buffer. If additional keys are required, the - // stream's dictionary may be retrieved by calling getDict(), and - // the resulting dictionary may be modified. This method is just a - // convenient wrapper around the newStream() and - // replaceStreamData(). It is a convenience methods for streams - // that require no parameters beyond the stream length. Note that - // you don't have to deal with compression yourself if you use - // QPDFWriter. By default, QPDFWriter will automatically compress - // uncompressed stream data. Example programs are provided that + // Create a new stream and associate it with the given qpdf object. Use the given buffer as the + // stream data. The stream dictionary's /Length key will automatically be set to the size of the + // data buffer. If additional keys are required, the stream's dictionary may be retrieved by + // calling getDict(), and the resulting dictionary may be modified. This method is just a + // convenient wrapper around the newStream() and replaceStreamData(). It is a convenience + // methods for streams that require no parameters beyond the stream length. Note that you don't + // have to deal with compression yourself if you use QPDFWriter. By default, QPDFWriter will + // automatically compress uncompressed stream data. Example programs are provided that // illustrate this. From QPDF 11.2, you can call QPDF::newStream() // instead. QPDF_DLL static QPDFObjectHandle newStream(QPDF* qpdf, std::shared_ptr data); - // Create new stream with data from string. This method will - // create a copy of the data rather than using the user-provided - // buffer as in the std::shared_ptr version of newStream. + // Create new stream with data from string. This method will create a copy of the data rather + // than using the user-provided buffer as in the std::shared_ptr version of newStream. // From QPDF 11.2, you can call QPDF::newStream() instead. QPDF_DLL static QPDFObjectHandle newStream(QPDF* qpdf, std::string const& data); - // A reserved object is a special sentinel used for qpdf to - // reserve a spot for an object that is going to be added to the - // QPDF object. Normally you don't have to use this type since - // you can just call QPDF::makeIndirectObject. However, in some - // cases, if you have to create objects with circular references, - // you may need to create a reserved object so that you can have a - // reference to it and then replace the object later. Reserved - // objects have the special property that they can't be resolved - // to direct objects. This makes it possible to replace a - // reserved object with a new object while preserving existing - // references to them. When you are ready to replace a reserved - // object with its replacement, use QPDF::replaceReserved for this - // purpose rather than the more general QPDF::replaceObject. It - // is an error to try to write a QPDF with QPDFWriter if it has - // any reserved objects in it. From QPDF 11.4, you can - // call QPDF::newReserved() instead. + // A reserved object is a special sentinel used for qpdf to reserve a spot for an object that is + // going to be added to the QPDF object. Normally you don't have to use this type since you can + // just call QPDF::makeIndirectObject. However, in some cases, if you have to create objects + // with circular references, you may need to create a reserved object so that you can have a + // reference to it and then replace the object later. Reserved objects have the special + // property that they can't be resolved to direct objects. This makes it possible to replace a + // reserved object with a new object while preserving existing references to them. When you are + // ready to replace a reserved object with its replacement, use QPDF::replaceReserved for this + // purpose rather than the more general QPDF::replaceObject. It is an error to try to write a + // QPDF with QPDFWriter if it has any reserved objects in it. From QPDF 11.4, you can call + // QPDF::newReserved() instead. QPDF_DLL static QPDFObjectHandle newReserved(QPDF* qpdf); - // Provide an owning qpdf and object description. The library does - // this automatically with objects that are read from the input - // PDF and with objects that are created programmatically and - // inserted into the QPDF as a new indirect object. Most end user - // code will not need to call this. If an object has an owning - // qpdf and object description, it enables qpdf to give warnings - // with proper context in some cases where it would otherwise - // raise exceptions. It is okay to add objects without an - // owning_qpdf to objects that have one, but it is an error to - // have a QPDF contain objects with owning_qpdf set to something - // else. To add objects from another qpdf, use copyForeignObject - // instead. + // Provide an owning qpdf and object description. The library does this automatically with + // objects that are read from the input PDF and with objects that are created programmatically + // and inserted into the QPDF as a new indirect object. Most end user code will not need to call + // this. If an object has an owning qpdf and object description, it enables qpdf to give + // warnings with proper context in some cases where it would otherwise raise exceptions. It is + // okay to add objects without an owning_qpdf to objects that have one, but it is an error to + // have a QPDF contain objects with owning_qpdf set to something else. To add objects from + // another qpdf, use copyForeignObject instead. QPDF_DLL void setObjectDescription(QPDF* owning_qpdf, std::string const& object_description); QPDF_DLL @@ -674,62 +586,47 @@ class QPDFObjectHandle // // (Note: this comment is referenced in qpdf-c.h and the manual.) // - // In PDF files, objects have specific types, but there is nothing - // that prevents PDF files from containing objects of types that - // aren't expected by the specification. + // In PDF files, objects have specific types, but there is nothing that prevents PDF files from + // containing objects of types that aren't expected by the specification. // // There are two flavors of accessor methods: // - // * getSomethingValue() returns the value and issues a type - // warning if the type is incorrect. + // * getSomethingValue() returns the value and issues a type warning if the type is incorrect. // - // * getValueAsSomething() returns false if the value is the wrong - // type. Otherwise, it returns true and initializes a reference - // of the appropriate type. These methods never issue type + // * getValueAsSomething() returns false if the value is the wrong type. Otherwise, it returns + // true and initializes a reference of the appropriate type. These methods never issue type // warnings. // - // The getSomethingValue() accessors and some of the other methods - // expect objects of a particular type. Prior to qpdf 8, calling - // an accessor on a method of the wrong type, such as trying to - // get a dictionary key from an array, trying to get the string - // value of a number, etc., would throw an exception, but since - // qpdf 8, qpdf issues a warning and recovers using the following - // behavior: + // The getSomethingValue() accessors and some of the other methods expect objects of a + // particular type. Prior to qpdf 8, calling an accessor on a method of the wrong type, such as + // trying to get a dictionary key from an array, trying to get the string value of a number, + // etc., would throw an exception, but since qpdf 8, qpdf issues a warning and recovers using + // the following behavior: // - // * Requesting a value of the wrong type (int value from string, - // array item from a scalar or dictionary, etc.) will return a - // zero-like value for that type: false for boolean, 0 for - // number, the empty string for string, or the null object for - // an object handle. + // * Requesting a value of the wrong type (int value from string, array item from a scalar or + // dictionary, etc.) will return a zero-like value for that type: false for boolean, 0 for + // number, the empty string for string, or the null object for an object handle. // - // * Accessing an array item that is out of bounds will return a - // null object. + // * Accessing an array item that is out of bounds will return a null object. // - // * Attempts to mutate an object of the wrong type (e.g., - // attempting to add a dictionary key to a scalar or array) will - // be ignored. + // * Attempts to mutate an object of the wrong type (e.g., attempting to add a dictionary key to + // a scalar or array) will be ignored. // - // When any of these fallback behaviors are used, qpdf issues a - // warning. Starting in qpdf 10.5, these warnings have the error - // code qpdf_e_object. Prior to 10.5, they had the error code - // qpdf_e_damaged_pdf. If the QPDFObjectHandle is associated with - // a QPDF object (as is the case for all objects whose origin was - // a PDF file), the warning is issued using the normal warning - // mechanism (as described in QPDF.hh), making it possible to - // suppress or otherwise detect them. If the QPDFObjectHandle is - // not associated with a QPDF object (meaning it was created + // When any of these fallback behaviors are used, qpdf issues a warning. Starting in qpdf 10.5, + // these warnings have the error code qpdf_e_object. Prior to 10.5, they had the error code + // qpdf_e_damaged_pdf. If the QPDFObjectHandle is associated with a QPDF object (as is the case + // for all objects whose origin was a PDF file), the warning is issued using the normal warning + // mechanism (as described in QPDF.hh), making it possible to suppress or otherwise detect them. + // If the QPDFObjectHandle is not associated with a QPDF object (meaning it was created // programmatically), an exception will be thrown. // - // The way to avoid getting any type warnings or exceptions, even - // when working with malformed PDF files, is to always check the - // type of a QPDFObjectHandle before accessing it (for example, - // make sure that isString() returns true before calling - // getStringValue()) and to always be sure that any array indices - // are in bounds. + // The way to avoid getting any type warnings or exceptions, even when working with malformed + // PDF files, is to always check the type of a QPDFObjectHandle before accessing it (for + // example, make sure that isString() returns true before calling getStringValue()) and to + // always be sure that any array indices are in bounds. // - // For additional discussion and rationale for this behavior, see - // the section in the QPDF manual entitled "Object Accessor - // Methods". + // For additional discussion and rationale for this behavior, see the section in the QPDF manual + // entitled "Object Accessor Methods". // Methods for bool objects QPDF_DLL @@ -737,12 +634,10 @@ class QPDFObjectHandle QPDF_DLL bool getValueAsBool(bool&); - // Methods for integer objects. Note: if an integer value is too - // big (too far away from zero in either direction) to fit in the - // requested return type, the maximum or minimum value for that - // return type may be returned. For example, on a system with - // 32-bit int, a numeric object with a value of 2^40 (or anything - // too big for 32 bits) will be returned as INT_MAX. + // Methods for integer objects. Note: if an integer value is too big (too far away from zero in + // either direction) to fit in the requested return type, the maximum or minimum value for that + // return type may be returned. For example, on a system with 32-bit int, a numeric object with + // a value of 2^40 (or anything too big for 32 bits) will be returned as INT_MAX. QPDF_DLL long long getIntValue(); QPDF_DLL @@ -774,9 +669,8 @@ class QPDFObjectHandle QPDF_DLL bool getValueAsNumber(double&); - // Methods for name objects. The returned name value is in qpdf's - // canonical form with all escaping resolved. See comments for - // newName() for details. + // Methods for name objects. The returned name value is in qpdf's canonical form with all + // escaping resolved. See comments for newName() for details. QPDF_DLL std::string getName(); QPDF_DLL @@ -788,12 +682,10 @@ class QPDFObjectHandle QPDF_DLL bool getValueAsString(std::string&); - // If a string starts with the UTF-16 marker, it is converted from - // UTF-16 to UTF-8. Otherwise, it is treated as a string encoded - // with PDF Doc Encoding. PDF Doc Encoding is identical to - // ISO-8859-1 except in the range from 0200 through 0240, where - // there is a mapping of characters to Unicode. QPDF versions - // prior to version 8.0.0 erroneously left characters in that range + // If a string starts with the UTF-16 marker, it is converted from UTF-16 to UTF-8. Otherwise, + // it is treated as a string encoded with PDF Doc Encoding. PDF Doc Encoding is identical to + // ISO-8859-1 except in the range from 0200 through 0240, where there is a mapping of characters + // to Unicode. QPDF versions prior to version 8.0.0 erroneously left characters in that range // unmapped. QPDF_DLL std::string getUTF8Value(); @@ -812,8 +704,7 @@ class QPDFObjectHandle // Methods for array objects; see also name and array objects. - // Return an object that enables iteration over members. You can - // do + // Return an object that enables iteration over members. You can do // // for (auto iter: obj.aitems()) // { @@ -827,32 +718,29 @@ class QPDFObjectHandle int getArrayNItems(); QPDF_DLL QPDFObjectHandle getArrayItem(int n); - // Note: QPDF arrays internally optimize memory for arrays - // containing lots of nulls. Calling getArrayAsVector may cause a - // lot of memory to be allocated for very large arrays with lots - // of nulls. + // Note: QPDF arrays internally optimize memory for arrays containing lots of nulls. Calling + // getArrayAsVector may cause a lot of memory to be allocated for very large arrays with lots of + // nulls. QPDF_DLL std::vector getArrayAsVector(); QPDF_DLL bool isRectangle(); - // If the array is an array of four numeric values, return as a - // rectangle. Otherwise, return the rectangle [0, 0, 0, 0] + // If the array is an array of four numeric values, return as a rectangle. Otherwise, return the + // rectangle [0, 0, 0, 0] QPDF_DLL Rectangle getArrayAsRectangle(); QPDF_DLL bool isMatrix(); - // If the array is an array of six numeric values, return as a - // matrix. Otherwise, return the matrix [1, 0, 0, 1, 0, 0] + // If the array is an array of six numeric values, return as a matrix. Otherwise, return the + // matrix [1, 0, 0, 1, 0, 0] QPDF_DLL Matrix getArrayAsMatrix(); - // Methods for dictionary objects. In all dictionary methods, keys - // are specified/represented as canonical name strings starting - // with a leading slash and not containing any PDF syntax + // Methods for dictionary objects. In all dictionary methods, keys are specified/represented as + // canonical name strings starting with a leading slash and not containing any PDF syntax // escaping. See comments for getName() for details. - // Return an object that enables iteration over members. You can - // do + // Return an object that enables iteration over members. You can do // // for (auto iter: obj.ditems()) // { @@ -863,185 +751,149 @@ class QPDFObjectHandle QPDF_DLL QPDFDictItems ditems(); - // Return true if key is present. Keys with null values are treated as if - // they are not present. This is as per the PDF spec. + // Return true if key is present. Keys with null values are treated as if they are not present. + // This is as per the PDF spec. QPDF_DLL bool hasKey(std::string const&); - // Return the value for the key. If the key is not present, null is - // returned. + // Return the value for the key. If the key is not present, null is returned. QPDF_DLL QPDFObjectHandle getKey(std::string const&); - // If the object is null, return null. Otherwise, call getKey(). - // This makes it easier to access lower-level dictionaries, as in + // If the object is null, return null. Otherwise, call getKey(). This makes it easier to access + // lower-level dictionaries, as in // auto font = page.getKeyIfDict("/Resources").getKeyIfDict("/Font"); QPDF_DLL QPDFObjectHandle getKeyIfDict(std::string const&); - // Return all keys. Keys with null values are treated as if - // they are not present. This is as per the PDF spec. + // Return all keys. Keys with null values are treated as if they are not present. This is as + // per the PDF spec. QPDF_DLL std::set getKeys(); // Return dictionary as a map. Entries with null values are included. QPDF_DLL std::map getDictAsMap(); - // Methods for name and array objects. The name value is in qpdf's - // canonical form with all escaping resolved. See comments for - // newName() for details. + // Methods for name and array objects. The name value is in qpdf's canonical form with all + // escaping resolved. See comments for newName() for details. QPDF_DLL bool isOrHasName(std::string const&); - // Make all resources in a resource dictionary indirect. This just - // goes through all entries of top-level subdictionaries and - // converts any direct objects to indirect objects. This can be - // useful to call before mergeResources if it is going to be - // called multiple times to prevent resources from being copied - // multiple times. + // Make all resources in a resource dictionary indirect. This just goes through all entries of + // top-level subdictionaries and converts any direct objects to indirect objects. This can be + // useful to call before mergeResources if it is going to be called multiple times to prevent + // resources from being copied multiple times. QPDF_DLL void makeResourcesIndirect(QPDF& owning_qpdf); - // Merge resource dictionaries. If the "conflicts" parameter is - // provided, conflicts in dictionary subitems are resolved, and - // "conflicts" is initialized to a map such that + // Merge resource dictionaries. If the "conflicts" parameter is provided, conflicts in + // dictionary subitems are resolved, and "conflicts" is initialized to a map such that // conflicts[resource_type][old_key] == [new_key] // - // See also makeResourcesIndirect, which can be useful to call - // before calling this. + // See also makeResourcesIndirect, which can be useful to call before calling this. // - // This method does nothing if both this object and the other - // object are not dictionaries. Otherwise, it has following - // behavior, where "object" refers to the object whose method is + // This method does nothing if both this object and the other object are not dictionaries. + // Otherwise, it has following behavior, where "object" refers to the object whose method is // invoked, and "other" refers to the argument: // // * For each key in "other" whose value is an array: // * If "object" does not have that entry, shallow copy it. - // * Otherwise, if "object" has an array in the same place, - // append to that array any objects in "other"'s array that - // are not already present. + // * Otherwise, if "object" has an array in the same place, append to that array any objects + // in "other"'s array that are not already present. // * For each key in "other" whose value is a dictionary: // * If "object" does not have that entry, shallow copy it. // * Otherwise, for each key in the subdictionary: - // * If key is not present in "object"'s entry, shallow copy - // it if direct or just add it if indirect. + // * If key is not present in "object"'s entry, shallow copy it if direct or just add it if + // indirect. // * Otherwise, if conflicts are being detected: - // * If there is a key (oldkey) already in the dictionary - // that points to the same indirect destination as key, - // indicate that key was replaced by oldkey. This would - // happen if these two resource dictionaries have - // previously been merged. - // * Otherwise pick a new key (newkey) that is unique within - // the resource dictionary, store that in the resource - // dictionary with key's destination as its destination, - // and indicate that key was replaced by newkey. + // * If there is a key (oldkey) already in the dictionary that points to the same indirect + // destination as key, indicate that key was replaced by oldkey. This would happen if + // these two resource dictionaries have previously been merged. + // * Otherwise pick a new key (newkey) that is unique within the resource dictionary, + // store that in the resource dictionary with key's destination as its destination, and + // indicate that key was replaced by newkey. // - // The primary purpose of this method is to facilitate merging of - // resource dictionaries that are supposed to have the same scope - // as each other. For example, this can be used to merge a form - // XObject's /Resources dictionary with a form field's /DR or to - // merge two /DR dictionaries. The "conflicts" parameter may be - // previously initialized. This method adds to whatever is already + // The primary purpose of this method is to facilitate merging of resource dictionaries that are + // supposed to have the same scope as each other. For example, this can be used to merge a form + // XObject's /Resources dictionary with a form field's /DR or to merge two /DR dictionaries. The + // "conflicts" parameter may be previously initialized. This method adds to whatever is already // there, which can be useful when merging with multiple things. QPDF_DLL void mergeResources( QPDFObjectHandle other, std::map>* conflicts = nullptr); - // Get all resource names from a resource dictionary. If this - // object is a dictionary, this method returns a set of all the - // keys in all top-level subdictionaries. For resources - // dictionaries, this is the collection of names that may be - // referenced in the content stream. + // Get all resource names from a resource dictionary. If this object is a dictionary, this + // method returns a set of all the keys in all top-level subdictionaries. For resources + // dictionaries, this is the collection of names that may be referenced in the content stream. QPDF_DLL std::set getResourceNames(); - // Find a unique name within a resource dictionary starting with a - // given prefix. This method works by appending a number to the - // given prefix. It searches starting with min_suffix and sets - // min_suffix to selected value upon return. This can be used to - // increase efficiency if adding multiple items with the same - // prefix. (Why doesn't it set min_suffix to the next number? - // Well, maybe you aren't going to actually use the name it - // returns.) If you are calling this multiple times on the same - // resource dictionary, you can initialize resource_names by - // calling getResourceNames(), incrementally update it as you add - // resources, and keep passing it in so that getUniqueResourceName - // doesn't have to traverse the resource dictionary each time it's - // called. + // Find a unique name within a resource dictionary starting with a given prefix. This method + // works by appending a number to the given prefix. It searches starting with min_suffix and + // sets min_suffix to selected value upon return. This can be used to increase efficiency if + // adding multiple items with the same prefix. (Why doesn't it set min_suffix to the next + // number? Well, maybe you aren't going to actually use the name it returns.) If you are calling + // this multiple times on the same resource dictionary, you can initialize resource_names by + // calling getResourceNames(), incrementally update it as you add resources, and keep passing it + // in so that getUniqueResourceName doesn't have to traverse the resource dictionary each time + // it's called. QPDF_DLL std::string getUniqueResourceName( std::string const& prefix, int& min_suffix, std::set* resource_names = nullptr); - // A QPDFObjectHandle has an owning QPDF if it is associated with - // ("owned by") a specific QPDF object. Indirect objects always - // have an owning QPDF. Direct objects that are read from the - // input source will also have an owning QPDF. Programmatically - // created objects will only have one if setObjectDescription was - // called. + // A QPDFObjectHandle has an owning QPDF if it is associated with ("owned by") a specific QPDF + // object. Indirect objects always have an owning QPDF. Direct objects that are read from the + // input source will also have an owning QPDF. Programmatically created objects will only have + // one if setObjectDescription was called. // - // When the QPDF object that owns an object is destroyed, the - // object is changed into a null, and its owner is cleared. - // Therefore you should not retain the value of an owning QPDF - // beyond the life of the QPDF. If in doubt, ask for it each time - // you need it. + // When the QPDF object that owns an object is destroyed, the object is changed into a null, and + // its owner is cleared. Therefore you should not retain the value of an owning QPDF beyond the + // life of the QPDF. If in doubt, ask for it each time you need it. - // getOwningQPDF returns a pointer to the owning QPDF is the - // object has one. Otherwise, it returns a null pointer. Use this - // when you are able to handle the case of an object that doesn't - // have an owning QPDF. + // getOwningQPDF returns a pointer to the owning QPDF is the object has one. Otherwise, it + // returns a null pointer. Use this when you are able to handle the case of an object that + // doesn't have an owning QPDF. QPDF_DLL QPDF* getOwningQPDF() const; - // getQPDF, new in qpdf 11, returns a reference owning QPDF. If - // there is none, it throws a runtime_error. Use this when you - // know the object has to have an owning QPDF, such as when it's a - // known indirect object. Since streams are always indirect - // objects, this method can be used safely for streams. If - // error_msg is specified, it will be used at the contents of the + // getQPDF, new in qpdf 11, returns a reference owning QPDF. If there is none, it throws a + // runtime_error. Use this when you know the object has to have an owning QPDF, such as when + // it's a known indirect object. Since streams are always indirect objects, this method can be + // used safely for streams. If error_msg is specified, it will be used at the contents of the // runtime_error if there is now owner. QPDF_DLL QPDF& getQPDF(std::string const& error_msg = "") const; - // Create a shallow copy of an object as a direct object, but do not - // traverse across indirect object boundaries. That means that, - // for dictionaries and arrays, any keys or items that were - // indirect objects will still be indirect objects that point to - // the same place. In the strictest sense, this is not a shallow - // copy because it recursively descends arrays and dictionaries; - // it just doesn't cross over indirect objects. See also - // unsafeShallowCopy(). You can't copy a stream this way. See - // copyStream() instead. + // Create a shallow copy of an object as a direct object, but do not traverse across indirect + // object boundaries. That means that, for dictionaries and arrays, any keys or items that were + // indirect objects will still be indirect objects that point to the same place. In the + // strictest sense, this is not a shallow copy because it recursively descends arrays and + // dictionaries; it just doesn't cross over indirect objects. See also unsafeShallowCopy(). You + // can't copy a stream this way. See copyStream() instead. QPDF_DLL QPDFObjectHandle shallowCopy(); - // Create a true shallow copy of an array or dictionary, just - // copying the immediate items (array) or keys (dictionary). This - // is "unsafe" because, if you *modify* any of the items in the - // copy, you are modifying the original, which is almost never - // what you want. However, if your intention is merely to - // *replace* top-level items or keys and not to modify lower-level - // items in the copy, this method is much faster than - // shallowCopy(). + // Create a true shallow copy of an array or dictionary, just copying the immediate items + // (array) or keys (dictionary). This is "unsafe" because, if you *modify* any of the items in + // the copy, you are modifying the original, which is almost never what you want. However, if + // your intention is merely to *replace* top-level items or keys and not to modify lower-level + // items in the copy, this method is much faster than shallowCopy(). QPDF_DLL QPDFObjectHandle unsafeShallowCopy(); - // Create a copy of this stream. The new stream and the old stream - // are independent: after the copy, either the original or the - // copy's dictionary or data can be modified without affecting the - // other. This uses StreamDataProvider internally, so no - // unnecessary copies of the stream's data are made. If the source - // stream's data is already being provided by a - // StreamDataProvider, the new stream will use the same one, so - // you have to make sure your StreamDataProvider can handle that - // case. But if you're already using a StreamDataProvider, you - // probably don't need to call this method. + // Create a copy of this stream. The new stream and the old stream are independent: after the + // copy, either the original or the copy's dictionary or data can be modified without affecting + // the other. This uses StreamDataProvider internally, so no unnecessary copies of the stream's + // data are made. If the source stream's data is already being provided by a StreamDataProvider, + // the new stream will use the same one, so you have to make sure your StreamDataProvider can + // handle that case. But if you're already using a StreamDataProvider, you probably don't need + // to call this method. QPDF_DLL QPDFObjectHandle copyStream(); // Mutator methods. - // Since qpdf 11: for mutators that may add or remove an item, - // there are additional versions whose names contain "AndGet" that - // return the added or removed item. For example: + // Since qpdf 11: for mutators that may add or remove an item, there are additional versions + // whose names contain "AndGet" that return the added or removed item. For example: // // auto new_dict = dict.replaceKeyAndGetNew( // "/New", QPDFObjectHandle::newDictionary()); @@ -1049,15 +901,12 @@ class QPDFObjectHandle // auto old_value = dict.replaceKeyAndGetOld( // "/New", "(something)"_qpdf); - // Recursively copy this object, making it direct. An exception is - // thrown if a loop is detected. With allow_streams true, keep - // indirect object references to streams. Otherwise, throw an - // exception if any sub-object is a stream. Note that, when - // allow_streams is true and a stream is found, the resulting - // object is still associated with the containing qpdf. When - // allow_streams is false, the object will no longer be connected - // to the original QPDF object after this call completes - // successfully. + // Recursively copy this object, making it direct. An exception is thrown if a loop is detected. + // With allow_streams true, keep indirect object references to streams. Otherwise, throw an + // exception if any sub-object is a stream. Note that, when allow_streams is true and a stream + // is found, the resulting object is still associated with the containing qpdf. When + // allow_streams is false, the object will no longer be connected to the original QPDF object + // after this call completes successfully. QPDF_DLL void makeDirect(bool allow_streams = false); @@ -1066,9 +915,8 @@ class QPDFObjectHandle void setArrayItem(int, QPDFObjectHandle const&); QPDF_DLL void setArrayFromVector(std::vector const& items); - // Insert an item before the item at the given position ("at") so - // that it has that position after insertion. If "at" is equal to - // the size of the array, insert the item at the end. + // Insert an item before the item at the given position ("at") so that it has that position + // after insertion. If "at" is equal to the size of the array, insert the item at the end. QPDF_DLL void insertItem(int at, QPDFObjectHandle const& item); // Like insertItem but return the item that was inserted. @@ -1080,8 +928,7 @@ class QPDFObjectHandle // Append an item, and return the newly added item. QPDF_DLL QPDFObjectHandle appendItemAndGetNew(QPDFObjectHandle const& item); - // Remove the item at that position, reducing the size of the - // array by one. + // Remove the item at that position, reducing the size of the array by one. QPDF_DLL void eraseItem(int at); // Erase and item and return the item that was removed. @@ -1090,22 +937,19 @@ class QPDFObjectHandle // Mutator methods for dictionary objects - // Replace value of key, adding it if it does not exist. If value - // is null, remove the key. + // Replace value of key, adding it if it does not exist. If value is null, remove the key. QPDF_DLL void replaceKey(std::string const& key, QPDFObjectHandle const& value); // Replace value of key and return the value. QPDF_DLL QPDFObjectHandle replaceKeyAndGetNew(std::string const& key, QPDFObjectHandle const& value); - // Replace value of key and return the old value, or null if the - // key was previously not present. + // Replace value of key and return the old value, or null if the key was previously not present. QPDF_DLL QPDFObjectHandle replaceKeyAndGetOld(std::string const& key, QPDFObjectHandle const& value); // Remove key, doing nothing if key does not exist. QPDF_DLL void removeKey(std::string const& key); - // Remove key and return the old value. If the old value didn't - // exist, return a null object. + // Remove key and return the old value. If the old value didn't exist, return a null object. QPDF_DLL QPDFObjectHandle removeKeyAndGetOld(std::string const& key); @@ -1117,31 +961,26 @@ class QPDFObjectHandle QPDF_DLL QPDFObjectHandle getDict(); - // By default, or if true passed, QPDFWriter will attempt to - // filter a stream based on decode level, whether compression is - // enabled, and its ability to filter. Passing false will prevent - // QPDFWriter from attempting to filter the stream even if it can. - // This includes both decoding and compressing. This makes it - // possible for you to prevent QPDFWriter from uncompressing and - // recompressing a stream that it knows how to operate on for any - // application-specific reason, such as that you have already - // optimized its filtering. Note that this doesn't affect any - // other ways to get the stream's data, such as pipeStreamData or - // getStreamData. + // By default, or if true passed, QPDFWriter will attempt to filter a stream based on decode + // level, whether compression is enabled, and its ability to filter. Passing false will prevent + // QPDFWriter from attempting to filter the stream even if it can. This includes both decoding + // and compressing. This makes it possible for you to prevent QPDFWriter from uncompressing and + // recompressing a stream that it knows how to operate on for any application-specific reason, + // such as that you have already optimized its filtering. Note that this doesn't affect any + // other ways to get the stream's data, such as pipeStreamData or getStreamData. QPDF_DLL void setFilterOnWrite(bool); QPDF_DLL bool getFilterOnWrite(); - // If addTokenFilter has been called for this stream, then the - // original data should be considered to be modified. This means we - // should avoid optimizations such as not filtering a stream that - // is already compressed. + // If addTokenFilter has been called for this stream, then the original data should be + // considered to be modified. This means we should avoid optimizations such as not filtering a + // stream that is already compressed. QPDF_DLL bool isDataModified(); - // Returns filtered (uncompressed) stream data. Throws an - // exception if the stream is filtered and we can't decode it. + // Returns filtered (uncompressed) stream data. Throws an exception if the stream is filtered + // and we can't decode it. QPDF_DLL std::shared_ptr getStreamData(qpdf_stream_decode_level_e level = qpdf_dl_generalized); @@ -1149,17 +988,15 @@ class QPDFObjectHandle QPDF_DLL std::shared_ptr getRawStreamData(); - // Write stream data through the given pipeline. A null pipeline - // value may be used if all you want to do is determine whether a - // stream is filterable and would be filtered based on the - // provided flags. If flags is 0, write raw stream data and return - // false. Otherwise, the flags alter the behavior in the following - // way: + // Write stream data through the given pipeline. A null pipeline value may be used if all you + // want to do is determine whether a stream is filterable and would be filtered based on the + // provided flags. If flags is 0, write raw stream data and return false. Otherwise, the flags + // alter the behavior in the following way: // // encode_flags: // - // qpdf_sf_compress -- compress data with /FlateDecode if no other - // compression filters are applied. + // qpdf_sf_compress -- compress data with /FlateDecode if no other compression filters are + // applied. // // qpdf_sf_normalize -- tokenize as content stream and normalize tokens // @@ -1167,45 +1004,33 @@ class QPDFObjectHandle // // qpdf_dl_none -- do not decode any streams. // - // qpdf_dl_generalized -- decode supported general-purpose - // filters. This includes /ASCIIHexDecode, /ASCII85Decode, - // /LZWDecode, and /FlateDecode. + // qpdf_dl_generalized -- decode supported general-purpose filters. This includes + // /ASCIIHexDecode, /ASCII85Decode, /LZWDecode, and /FlateDecode. // - // qpdf_dl_specialized -- in addition to generalized filters, also - // decode supported non-lossy specialized filters. This includes - // /RunLengthDecode. + // qpdf_dl_specialized -- in addition to generalized filters, also decode supported non-lossy + // specialized filters. This includes /RunLengthDecode. // - // qpdf_dl_all -- in addition to generalized and non-lossy - // specialized filters, decode supported lossy filters. This - // includes /DCTDecode. + // qpdf_dl_all -- in addition to generalized and non-lossy specialized filters, decode supported + // lossy filters. This includes /DCTDecode. // - // If, based on the flags and the filters and decode parameters, - // we determine that we know how to apply all requested filters, - // do so and return true if we are successful. + // If, based on the flags and the filters and decode parameters, we determine that we know how + // to apply all requested filters, do so and return true if we are successful. // - // The exact meaning of the return value differs the different - // versions of this function, but for any version, the meaning has - // been the same. For the main version, added in qpdf 10, the - // return value indicates whether the overall operation succeeded. - // The filter parameter, if specified, will be set to whether or - // not filtering was attempted. If filtering was not requested, - // this value will be false even if the overall operation - // succeeded. + // The exact meaning of the return value differs the different versions of this function, but + // for any version, the meaning has been the same. For the main version, added in qpdf 10, the + // return value indicates whether the overall operation succeeded. The filter parameter, if + // specified, will be set to whether or not filtering was attempted. If filtering was not + // requested, this value will be false even if the overall operation succeeded. // - // If filtering is requested but this method returns false, it - // means there was some error in the filtering, in which case the - // resulting data is likely partially filtered and/or incomplete - // and may not be consistent with the configured filters. - // QPDFWriter handles this by attempting to get the stream data - // without filtering, but callers should consider a false return - // value when decode_level is not qpdf_dl_none to be a potential - // loss of data. If you intend to retry in that case, pass true as - // the value of will_retry. This changes the warning issued by the - // library to indicate that the operation will be retried without - // filtering to avoid data loss. - - // Return value is overall success, even if filtering is not - // requested. + // If filtering is requested but this method returns false, it means there was some error in the + // filtering, in which case the resulting data is likely partially filtered and/or incomplete + // and may not be consistent with the configured filters. QPDFWriter handles this by attempting + // to get the stream data without filtering, but callers should consider a false return value + // when decode_level is not qpdf_dl_none to be a potential loss of data. If you intend to retry + // in that case, pass true as the value of will_retry. This changes the warning issued by the + // library to indicate that the operation will be retried without filtering to avoid data loss. + + // Return value is overall success, even if filtering is not requested. QPDF_DLL bool pipeStreamData( Pipeline*, @@ -1215,9 +1040,8 @@ class QPDFObjectHandle bool suppress_warnings = false, bool will_retry = false); - // Legacy version. Return value is whether filtering was - // attempted. There is no way to determine success if filtering - // was not attempted. + // Legacy version. Return value is whether filtering was attempted. There is no way to determine + // success if filtering was not attempted. QPDF_DLL bool pipeStreamData( Pipeline*, @@ -1226,8 +1050,7 @@ class QPDFObjectHandle bool suppress_warnings = false, bool will_retry = false); - // Legacy pipeStreamData. This maps to the the flags-based - // pipeStreamData as follows: + // Legacy pipeStreamData. This maps to the the flags-based pipeStreamData as follows: // filter = false -> encode_flags = 0 // filter = true -> decode_level = qpdf_dl_generalized // normalize = true -> encode_flags |= qpdf_sf_normalize @@ -1236,70 +1059,57 @@ class QPDFObjectHandle QPDF_DLL bool pipeStreamData(Pipeline*, bool filter, bool normalize, bool compress); - // Replace a stream's dictionary. The new dictionary must be - // consistent with the stream's data. This is most appropriately - // used when creating streams from scratch that will use a stream - // data provider and therefore start with an empty dictionary. It - // may be more convenient in this case than calling getDict and - // modifying it for each key. The pdf-create example does this. + // Replace a stream's dictionary. The new dictionary must be consistent with the stream's data. + // This is most appropriately used when creating streams from scratch that will use a stream + // data provider and therefore start with an empty dictionary. It may be more convenient in + // this case than calling getDict and modifying it for each key. The pdf-create example does + // this. QPDF_DLL void replaceDict(QPDFObjectHandle const&); // REPLACING STREAM DATA - // Note about all replaceStreamData methods: whatever values are - // passed as filter and decode_parms will overwrite /Filter and - // /DecodeParms in the stream. Passing a null object - // (QPDFObjectHandle::newNull()) will remove those values from the - // stream dictionary. From qpdf 11, passing an *uninitialized* - // QPDFObjectHandle (QPDFObjectHandle()) will leave any existing + // Note about all replaceStreamData methods: whatever values are passed as filter and + // decode_parms will overwrite /Filter and /DecodeParms in the stream. Passing a null object + // (QPDFObjectHandle::newNull()) will remove those values from the stream dictionary. From qpdf + // 11, passing an *uninitialized* QPDFObjectHandle (QPDFObjectHandle()) will leave any existing // values untouched. - // Replace this stream's stream data with the given data buffer. - // The stream's /Length key is replaced with the length of the - // data buffer. The stream is interpreted as if the data read from - // the file, after any decryption filters have been applied, is as - // presented. + // Replace this stream's stream data with the given data buffer. The stream's /Length key is + // replaced with the length of the data buffer. The stream is interpreted as if the data read + // from the file, after any decryption filters have been applied, is as presented. QPDF_DLL void replaceStreamData( std::shared_ptr data, QPDFObjectHandle const& filter, QPDFObjectHandle const& decode_parms); - // Replace the stream's stream data with the given string. - // This method will create a copy of the data rather than using - // the user-provided buffer as in the std::shared_ptr version - // of replaceStreamData. + // Replace the stream's stream data with the given string. This method will create a copy of the + // data rather than using the user-provided buffer as in the std::shared_ptr version of + // replaceStreamData. QPDF_DLL void replaceStreamData( std::string const& data, QPDFObjectHandle const& filter, QPDFObjectHandle const& decode_parms); - // As above, replace this stream's stream data. Instead of - // directly providing a buffer with the stream data, call the - // given provider's provideStreamData method. See comments on the - // StreamDataProvider class (defined above) for details on the - // method. The data must be consistent with filter and - // decode_parms as provided. Although it is more complex to use - // this form of replaceStreamData than the one that takes a - // buffer, it makes it possible to avoid allocating memory for the - // stream data. Example programs are provided that use both forms - // of replaceStreamData. - - // Note about stream length: for any given stream, the provider - // must provide the same amount of data each time it is called. - // This is critical for making linearization work properly. - // Versions of qpdf before 3.0.0 required a length to be specified - // here. Starting with version 3.0.0, this is no longer necessary - // (or permitted). The first time the stream data provider is - // invoked for a given stream, the actual length is stored. - // Subsequent times, it is enforced that the length be the same as - // the first time. - - // If you have gotten a compile error here while building code - // that worked with older versions of qpdf, just omit the length - // parameter. You can also simplify your code by not having to + // As above, replace this stream's stream data. Instead of directly providing a buffer with the + // stream data, call the given provider's provideStreamData method. See comments on the + // StreamDataProvider class (defined above) for details on the method. The data must be + // consistent with filter and decode_parms as provided. Although it is more complex to use this + // form of replaceStreamData than the one that takes a buffer, it makes it possible to avoid + // allocating memory for the stream data. Example programs are provided that use both forms of + // replaceStreamData. + + // Note about stream length: for any given stream, the provider must provide the same amount of + // data each time it is called. This is critical for making linearization work properly. + // Versions of qpdf before 3.0.0 required a length to be specified here. Starting with + // version 3.0.0, this is no longer necessary (or permitted). The first time the stream data + // provider is invoked for a given stream, the actual length is stored. Subsequent times, it is + // enforced that the length be the same as the first time. + + // If you have gotten a compile error here while building code that worked with older versions + // of qpdf, just omit the length parameter. You can also simplify your code by not having to // compute the length in advance. QPDF_DLL void replaceStreamData( @@ -1307,33 +1117,28 @@ class QPDFObjectHandle QPDFObjectHandle const& filter, QPDFObjectHandle const& decode_parms); - // Starting in qpdf 10.2, you can use C++-11 function objects - // instead of StreamDataProvider. + // Starting in qpdf 10.2, you can use C++-11 function objects instead of StreamDataProvider. - // The provider should write the stream data to the pipeline. For - // a one-liner to replace stream data with the contents of a file, - // pass QUtil::file_provider(filename) as provider. + // The provider should write the stream data to the pipeline. For a one-liner to replace stream + // data with the contents of a file, pass QUtil::file_provider(filename) as provider. QPDF_DLL void replaceStreamData( std::function provider, QPDFObjectHandle const& filter, QPDFObjectHandle const& decode_parms); - // The provider should write the stream data to the pipeline, - // returning true if it succeeded without errors. + // The provider should write the stream data to the pipeline, returning true if it succeeded + // without errors. QPDF_DLL void replaceStreamData( std::function provider, QPDFObjectHandle const& filter, QPDFObjectHandle const& decode_parms); - // Access object ID and generation. For direct objects, return - // object ID 0. + // Access object ID and generation. For direct objects, return object ID 0. - // NOTE: Be careful about calling getObjectID() and - // getGeneration() directly as this can lead to the pattern of - // depending on object ID or generation without the other. In - // general, when keeping track of object IDs, it's better to use - // QPDFObjGen instead. + // NOTE: Be careful about calling getObjectID() and getGeneration() directly as this can lead to + // the pattern of depending on object ID or generation without the other. In general, when + // keeping track of object IDs, it's better to use QPDFObjGen instead. QPDF_DLL QPDFObjGen getObjGen() const; @@ -1346,51 +1151,40 @@ class QPDFObjectHandle std::string unparse(); QPDF_DLL std::string unparseResolved(); - // For strings only, force binary representation. Otherwise, same - // as unparse. + // For strings only, force binary representation. Otherwise, same as unparse. QPDF_DLL std::string unparseBinary(); - // Return encoded as JSON. The constant JSON::LATEST can be used - // to specify the latest available JSON version. The JSON is - // generated as follows: - // * Arrays, dictionaries, booleans, nulls, integers, and real - // numbers are represented by their native JSON types. - // * Names are encoded as strings representing the canonical - // representation (after parsing #xx) and preceded by a slash, - // just as unparse() returns. For example, the JSON for the + // Return encoded as JSON. The constant JSON::LATEST can be used to specify the latest available + // JSON version. The JSON is generated as follows: + // * Arrays, dictionaries, booleans, nulls, integers, and real numbers are represented by their + // native JSON types. + // * Names are encoded as strings representing the canonical representation (after parsing #xx) + // and preceded by a slash, just as unparse() returns. For example, the JSON for the // PDF-syntax name /Text#2fPlain would be "/Text/Plain". // * Indirect references are encoded as strings containing "obj gen R" // * Strings - // * JSON v1: Strings are encoded as UTF-8 strings with - // unrepresentable binary characters encoded as \uHHHH. - // Characters in PDF Doc encoding that don't have - // bidirectional unicode mappings are not reversible. There is - // no way to tell the difference between a string that looks - // like a name or indirect object from an actual name or - // indirect object. + // * JSON v1: Strings are encoded as UTF-8 strings with unrepresentable binary characters + // encoded as \uHHHH. Characters in PDF Doc encoding that don't have bidirectional unicode + // mappings are not reversible. There is no way to tell the difference between a string that + // looks like a name or indirect object from an actual name or indirect object. // * JSON v2: - // * Unicode strings and strings encoded with PDF Doc encoding - // that can be bidrectionally mapped two Unicode (which is - // all strings without undefined characters) are represented + // * Unicode strings and strings encoded with PDF Doc encoding that can be bidrectionally + // mapped two Unicode (which is all strings without undefined characters) are represented // as "u:" followed by the UTF-8 encoded string. Example: // "u:potato". - // * All other strings are represented as "b:" followed by a - // hexadecimal encoding of the string. Example: "b:0102cacb" + // * All other strings are represented as "b:" followed by a hexadecimal encoding of the + // string. Example: "b:0102cacb" // * Streams - // * JSON v1: Only the stream's dictionary is encoded. There is - // no way tell a stream from a dictionary other than context. - // * JSON v2: A stream is encoded as {"dict": {...}} with the - // value being the encoding of the stream's dictionary. Since - // "dict" does not otherwise represent anything, this is - // unambiguous. The getStreamJSON() call can be used to add - // encoding of the stream's data. - // * Object types that are only valid in content streams (inline - // image, operator) are serialized as "null". Attempting to - // serialize a "reserved" object is an error. - // If dereference_indirect is true and this is an indirect object, - // show the actual contents of the object. The effect of - // dereference_indirect applies only to this object. It is not + // * JSON v1: Only the stream's dictionary is encoded. There is no way tell a stream from a + // dictionary other than context. + // * JSON v2: A stream is encoded as {"dict": {...}} with the value being the encoding of the + // stream's dictionary. Since "dict" does not otherwise represent anything, this is + // unambiguous. The getStreamJSON() call can be used to add encoding of the stream's data. + // * Object types that are only valid in content streams (inline image, operator) are serialized + // as "null". Attempting to serialize a "reserved" object is an error. + // If dereference_indirect is true and this is an indirect object, show the actual contents of + // the object. The effect of dereference_indirect applies only to this object. It is not // recursive. QPDF_DLL JSON getJSON(int json_version, bool dereference_indirect = false); @@ -1400,36 +1194,28 @@ class QPDFObjectHandle [[deprecated("Use getJSON(int version)")]] QPDF_DLL JSON getJSON(bool dereference_indirect = false); - // This method can be called on a stream to get a more extended - // JSON representation of the stream that includes the stream's - // data. The JSON object returned is always a dictionary whose - // "dict" key is an encoding of the stream's dictionary. The - // representation of the data is determined by the json_data - // field. + // This method can be called on a stream to get a more extended JSON representation of the + // stream that includes the stream's data. The JSON object returned is always a dictionary whose + // "dict" key is an encoding of the stream's dictionary. The representation of the data is + // determined by the json_data field. // - // The json_data field may have the value qpdf_sj_none, - // qpdf_sj_inline, or qpdf_sj_file. + // The json_data field may have the value qpdf_sj_none, qpdf_sj_inline, or qpdf_sj_file. // // If json_data is qpdf_sj_none, stream data is not represented. // - // If json_data is qpdf_sj_inline or qpdf_sj_file, then stream - // data is filtered or not based on the value of decode_level, - // which has the same meaning as with pipeStreamData. + // If json_data is qpdf_sj_inline or qpdf_sj_file, then stream data is filtered or not based on + // the value of decode_level, which has the same meaning as with pipeStreamData. // - // If json_data is qpdf_sj_inline, the base64-encoded stream data - // is included in the "data" field of the dictionary that is - // returned. + // If json_data is qpdf_sj_inline, the base64-encoded stream data is included in the "data" + // field of the dictionary that is returned. // - // If json_data is qpdf_sj_file, then the Pipeline ("p") and - // data_filename argument must be supplied. The value of - // data_filename is stored in the resulting json in the "datafile" - // key but is not otherwise use. The stream data itself (raw or - // filtered depending on decode level), is written to the pipeline - // via pipeStreamData(). + // If json_data is qpdf_sj_file, then the Pipeline ("p") and data_filename argument must be + // supplied. The value of data_filename is stored in the resulting json in the "datafile" key + // but is not otherwise use. The stream data itself (raw or filtered depending on decode level), + // is written to the pipeline via pipeStreamData(). // - // NOTE: When json_data is qpdf_sj_inline, the QPDF object from - // which the stream originates must remain valid until after the - // JSON object is written. + // NOTE: When json_data is qpdf_sj_inline, the QPDF object from which the stream originates must + // remain valid until after the JSON object is written. QPDF_DLL JSON getStreamJSON( int json_version, @@ -1438,11 +1224,9 @@ class QPDFObjectHandle Pipeline* p, std::string const& data_filename); - // Legacy helper methods for commonly performed operations on - // pages. Newer code should use QPDFPageObjectHelper instead. The - // specification and behavior of these methods are the same as the - // identically named methods in that class, but newer - // functionality will be added there. + // Legacy helper methods for commonly performed operations on pages. Newer code should use + // QPDFPageObjectHelper instead. The specification and behavior of these methods are the same as + // the identically named methods in that class, but newer functionality will be added there. QPDF_DLL std::map getPageImages(); QPDF_DLL @@ -1455,18 +1239,15 @@ class QPDFObjectHandle void coalesceContentStreams(); // End legacy page helpers - // Issue a warning about this object if possible. If the object - // has a description, a warning will be issued using the owning - // QPDF as context. Otherwise, a message will be written to the - // default logger's error stream, which is standard error if not - // overridden. Objects read normally from the file have - // descriptions. See comments on setObjectDescription for - // additional details. + // Issue a warning about this object if possible. If the object has a description, a warning + // will be issued using the owning QPDF as context. Otherwise, a message will be written to the + // default logger's error stream, which is standard error if not overridden. Objects read + // normally from the file have descriptions. See comments on setObjectDescription for additional + // details. QPDF_DLL void warnIfPossible(std::string const& warning); - // Provide access to specific classes for recursive - // disconnected(). + // Provide access to specific classes for recursive disconnected(). class DisconnectAccess { friend class QPDF_Dictionary; @@ -1480,9 +1261,8 @@ class QPDFObjectHandle } }; - // Convenience routine: Throws if the assumption is violated. Your - // code will be better if you call one of the isType methods and - // handle the case of the type being wrong, but these can be + // Convenience routine: Throws if the assumption is violated. Your code will be better if you + // call one of the isType methods and handle the case of the type being wrong, but these can be // convenient if you have already verified the type. QPDF_DLL void assertInitialized() const; @@ -1519,11 +1299,10 @@ class QPDFObjectHandle QPDF_DLL void assertNumber(); - // The isPageObject method checks the /Type key of the object. - // This is not completely reliable as there are some otherwise - // valid files whose /Type is wrong for page objects. qpdf is - // slightly more accepting but may still return false here when - // treating the object as a page would work. Use this sparingly. + // The isPageObject method checks the /Type key of the object. This is not completely reliable + // as there are some otherwise valid files whose /Type is wrong for page objects. qpdf is + // slightly more accepting but may still return false here when treating the object as a page + // would work. Use this sparingly. QPDF_DLL bool isPageObject(); QPDF_DLL @@ -1534,13 +1313,12 @@ class QPDFObjectHandle QPDF_DLL bool isFormXObject(); - // Indicate if this is an image. If exclude_imagemask is true, - // don't count image masks as images. + // Indicate if this is an image. If exclude_imagemask is true, don't count image masks as + // images. QPDF_DLL bool isImage(bool exclude_imagemask = true); - // The following methods do not form part of the public API and are for - // internal use only. + // The following methods do not form part of the public API and are for internal use only. QPDFObjectHandle(std::shared_ptr const& obj) : obj(obj) @@ -1600,9 +1378,8 @@ class QPDFObjectHandle static void warn(QPDF*, QPDFExc const&); void checkOwnership(QPDFObjectHandle const&) const; - // Moving members of QPDFObjectHandle into a smart pointer incurs - // a substantial performance penalty since QPDFObjectHandle - // objects are copied around so frequently. + // Moving members of QPDFObjectHandle into a smart pointer incurs a substantial performance + // penalty since QPDFObjectHandle objects are copied around so frequently. std::shared_ptr obj; }; @@ -1611,13 +1388,12 @@ class QPDFObjectHandle // auto oh = "<< /Key (value) >>"_qpdf; -// If this is causing problems in your code, define -// QPDF_NO_QPDF_STRING to prevent the declaration from being here. +// If this is causing problems in your code, define QPDF_NO_QPDF_STRING to prevent the declaration +// from being here. /* clang-format off */ -// Disable formatting for this declaration: emacs font-lock in cc-mode -// (as of 28.1) treats the rest of the file as a string if -// clang-format removes the space after "operator", and as of +// Disable formatting for this declaration: emacs font-lock in cc-mode (as of 28.1) treats the rest +// of the file as a string if clang-format removes the space after "operator", and as of // clang-format 15, there's no way to prevent it from doing so. QPDF_DLL QPDFObjectHandle operator ""_qpdf(char const* v, size_t len); @@ -1627,8 +1403,8 @@ QPDFObjectHandle operator ""_qpdf(char const* v, size_t len); class QPDFObjectHandle::QPDFDictItems { - // This class allows C++-style iteration, including range-for - // iteration, around dictionaries. You can write + // This class allows C++-style iteration, including range-for iteration, around dictionaries. + // You can write // for (auto iter: QPDFDictItems(dictionary_obj)) // { @@ -1636,8 +1412,7 @@ class QPDFObjectHandle::QPDFDictItems // // iter.second is a QPDFObjectHandle // } - // See examples/pdf-name-number-tree.cc for a demonstration of - // using this API. + // See examples/pdf-name-number-tree.cc for a demonstration of using this API. public: QPDF_DLL @@ -1727,16 +1502,15 @@ class QPDFObjectHandle::QPDFDictItems class QPDFObjectHandle::QPDFArrayItems { - // This class allows C++-style iteration, including range-for - // iteration, around arrays. You can write + // This class allows C++-style iteration, including range-for iteration, around arrays. You can + // write // for (auto iter: QPDFArrayItems(array_obj)) // { // // iter is a QPDFObjectHandle // } - // See examples/pdf-name-number-tree.cc for a demonstration of - // using this API. + // See examples/pdf-name-number-tree.cc for a demonstration of using this API. public: QPDF_DLL diff --git a/include/qpdf/QPDFPageObjectHelper.hh b/include/qpdf/QPDFPageObjectHelper.hh index 05a57b5c..98bb078e 100644 --- a/include/qpdf/QPDFPageObjectHelper.hh +++ b/include/qpdf/QPDFPageObjectHelper.hh @@ -2,22 +2,19 @@ // // This file is part of qpdf. // -// 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 +// 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. +// 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. // -// Versions of qpdf prior to version 7 were released under the terms -// of version 2.0 of the Artistic License. At your option, you may -// continue to consider qpdf to be licensed under those terms. Please -// see the manual for additional information. +// Versions of qpdf prior to version 7 were released under the terms of version 2.0 of the Artistic +// License. At your option, you may continue to consider qpdf to be licensed under those terms. +// Please see the manual for additional information. #ifndef QPDFPAGEOBJECTHELPER_HH #define QPDFPAGEOBJECTHELPER_HH @@ -35,9 +32,8 @@ class QPDFAcroFormDocumentHelper; class QPDFPageObjectHelper: public QPDFObjectHelper { - // This is a helper class for page objects, but as of qpdf 10.1, - // many of the methods also work for form XObjects. When this is - // the case, it is noted in the comment. + // This is a helper class for page objects, but as of qpdf 10.1, many of the methods also work + // for form XObjects. When this is the case, it is noted in the comment. public: QPDF_DLL @@ -47,35 +43,30 @@ class QPDFPageObjectHelper: public QPDFObjectHelper // PAGE ATTRIBUTES - // The getAttribute method works with pages and form XObjects. It - // return the value of the requested attribute from the page/form - // XObject's dictionary, taking inheritance from the pages tree - // into consideration. For pages, the attributes /MediaBox, - // /CropBox, /Resources, and /Rotate are inheritable, meaning that - // if they are not present directly on the page node, they may be - // inherited from ancestor nodes in the pages tree. + // The getAttribute method works with pages and form XObjects. It return the value of the + // requested attribute from the page/form XObject's dictionary, taking inheritance from the + // pages tree into consideration. For pages, the attributes /MediaBox, /CropBox, /Resources, and + // /Rotate are inheritable, meaning that if they are not present directly on the page node, they + // may be inherited from ancestor nodes in the pages tree. // // There are two ways that an attribute can be "shared": // - // * For inheritable attributes on pages, it may appear in a - // higher level node of the pages tree + // * For inheritable attributes on pages, it may appear in a higher level node of the pages tree // - // * For any attribute, the attribute may be an indirect object - // which may be referenced by more than one page/form XObject. + // * For any attribute, the attribute may be an indirect object which may be referenced by more + // than one page/form XObject. // - // If copy_if_shared is true, then this method will replace the - // attribute with a shallow copy if it is indirect or inherited - // and return the copy. You should do this if you are going to - // modify the returned object and want the modifications to apply - // to the current page/form XObject only. + // If copy_if_shared is true, then this method will replace the attribute with a shallow copy if + // it is indirect or inherited and return the copy. You should do this if you are going to + // modify the returned object and want the modifications to apply to the current page/form + // XObject only. QPDF_DLL QPDFObjectHandle getAttribute(std::string const& name, bool copy_if_shared); // PAGE BOXES // - // Pages have various types of boundary boxes. These are described - // in detail in the PDF specification (section 14.11.2 Page - // boundaries). They are, by key in the page dictionary: + // Pages have various types of boundary boxes. These are described in detail in the PDF + // specification (section 14.11.2 Page boundaries). They are, by key in the page dictionary: // // * /MediaBox -- boundaries of physical page // * /CropBox -- clipping region of what is displayed @@ -87,114 +78,90 @@ class QPDFPageObjectHelper: public QPDFObjectHelper // fallback value for /CropBox is /MediaBox, and the fallback // values for the other boxes are /CropBox. // - // As noted above (PAGE ATTRIBUTES), /MediaBox and /CropBox can be - // inherited from parent nodes in the pages tree. The other boxes - // can't be inherited. + // As noted above (PAGE ATTRIBUTES), /MediaBox and /CropBox can be inherited from parent nodes + // in the pages tree. The other boxes can't be inherited. // - // When the comments below refer to the "effective value" of an - // box, this takes into consideration both inheritance through the - // pages tree (in the case of /MediaBox and /CropBox) and fallback - // values for missing attributes (for all except /MediaBox). + // When the comments below refer to the "effective value" of an box, this takes into + // consideration both inheritance through the pages tree (in the case of /MediaBox and /CropBox) + // and fallback values for missing attributes (for all except /MediaBox). // - // For the methods below, copy_if_shared is passed to getAttribute - // and therefore refers only to indirect objects and values that - // are inherited through the pages tree. + // For the methods below, copy_if_shared is passed to getAttribute and therefore refers only to + // indirect objects and values that are inherited through the pages tree. // - // If copy_if_fallback is true, a copy is made if the object's - // value was obtained by falling back to a different box. + // If copy_if_fallback is true, a copy is made if the object's value was obtained by falling + // back to a different box. // - // The copy_if_shared and copy_if_fallback parameters carry across - // multiple layers. This is explained below. + // The copy_if_shared and copy_if_fallback parameters carry across multiple layers. This is + // explained below. // - // You should set copy_if_shared to true if you want to modify a - // bounding box for the current page without affecting other pages - // but you don't want to change the fallback behavior. For - // example, if you want to modify the /TrimBox for the current - // page only but have it continue to fall back to the value of - // /CropBox or /MediaBox if they are not defined, you could set + // You should set copy_if_shared to true if you want to modify a bounding box for the current + // page without affecting other pages but you don't want to change the fallback behavior. For + // example, if you want to modify the /TrimBox for the current page only but have it continue to + // fall back to the value of /CropBox or /MediaBox if they are not defined, you could set // copy_if_shared to true. // - // You should set copy_if_fallback to true if you want to modify a - // specific box as distinct from any other box. For example, if - // you want to make /TrimBox differ from /CropBox, then you should - // set copy_if_fallback to true. + // You should set copy_if_fallback to true if you want to modify a specific box as distinct from + // any other box. For example, if you want to make /TrimBox differ from /CropBox, then you + // should set copy_if_fallback to true. // // The copy_if_fallback flags were added in qpdf 11. // - // For example, suppose that neither /CropBox nor /TrimBox is - // present on a page but /CropBox is present in the page's parent - // node in the page tree. + // For example, suppose that neither /CropBox nor /TrimBox is present on a page but /CropBox is + // present in the page's parent node in the page tree. // - // * getTrimBox(false, false) would return the /CropBox from the - // parent node. + // * getTrimBox(false, false) would return the /CropBox from the parent node. // - // * getTrimBox(true, false) would make a shallow copy of the - // /CropBox from the parent node into the current node and - // return it. + // * getTrimBox(true, false) would make a shallow copy of the /CropBox from the parent node into + // the current node and return it. // - // * getTrimBox(false, true) would make a shallow copy of the - // /CropBox from the parent node into /TrimBox of the current - // node and return it. + // * getTrimBox(false, true) would make a shallow copy of the /CropBox from the parent node into + // /TrimBox of the current node and return it. // - // * getTrimBox(true, true) would make a shallow copy of the - // /CropBox from the parent node into the current node, then - // make a shallow copy of the resulting copy to /TrimBox of the - // current node, and then return that. + // * getTrimBox(true, true) would make a shallow copy of the /CropBox from the parent node into + // the current node, then make a shallow copy of the resulting copy to /TrimBox of the current + // node, and then return that. // - // To illustrate how these parameters carry across multiple - // layers, suppose that neither /MediaBox, /CropBox, nor /TrimBox - // is present on a page but /MediaBox is present on the parent. In - // this case: + // To illustrate how these parameters carry across multiple layers, suppose that neither + // /MediaBox, /CropBox, nor /TrimBox is present on a page but /MediaBox is present on the + // parent. In this case: // - // * getTrimBox(false, false) would return the value of /MediaBox - // from the parent node. + // * getTrimBox(false, false) would return the value of /MediaBox from the parent node. // - // * getTrimBox(true, false) would copy /MediaBox to the current - // node and return it. + // * getTrimBox(true, false) would copy /MediaBox to the current node and return it. // - // * getTrimBox(false, true) would first copy /MediaBox from the - // parent to /CropBox, then copy /CropBox to /TrimBox, and then - // return the result. + // * getTrimBox(false, true) would first copy /MediaBox from the parent to /CropBox, then copy + // /CropBox to /TrimBox, and then return the result. // - // * getTrimBox(true, true) would first copy /MediaBox from the - // parent to the current page, then copy it to /CropBox, then - // copy /CropBox to /TrimBox, and then return the result. + // * getTrimBox(true, true) would first copy /MediaBox from the parent to the current page, then + // copy it to /CropBox, then copy /CropBox to /TrimBox, and then return the result. // - // If you need different behavior, call getAttribute directly and - // take care of your own copying. + // If you need different behavior, call getAttribute directly and take care of your own copying. // Return the effective MediaBox QPDF_DLL QPDFObjectHandle getMediaBox(bool copy_if_shared = false); - // Return the effective CropBox. If not defined, fall back to - // MediaBox + // Return the effective CropBox. If not defined, fall back to MediaBox QPDF_DLL QPDFObjectHandle getCropBox(bool copy_if_shared = false, bool copy_if_fallback = false); - // Return the effective BleedBox. If not defined, fall back to - // CropBox. + // Return the effective BleedBox. If not defined, fall back to CropBox. QPDF_DLL QPDFObjectHandle getBleedBox(bool copy_if_shared = false, bool copy_if_fallback = false); - // Return the effective TrimBox. If not defined, fall back to - // CropBox. + // Return the effective TrimBox. If not defined, fall back to CropBox. QPDF_DLL QPDFObjectHandle getTrimBox(bool copy_if_shared = false, bool copy_if_fallback = false); - // Return the effective ArtBox. If not defined, fall back to - // CropBox. + // Return the effective ArtBox. If not defined, fall back to CropBox. QPDF_DLL QPDFObjectHandle getArtBox(bool copy_if_shared = false, bool copy_if_fallback = false); - // Iterate through XObjects, possibly recursing into form - // XObjects. This works with pages or form XObjects. Call action - // on each XObject for which selector, if specified, returns true. - // With no selector, calls action for every object. In addition to - // the object being passed to action, the containing XObject - // dictionary and key are passed in. Remember that the XObject - // dictionary may be shared, and the object may appear in multiple - // XObject dictionaries. + // Iterate through XObjects, possibly recursing into form XObjects. This works with pages or + // form XObjects. Call action on each XObject for which selector, if specified, returns true. + // With no selector, calls action for every object. In addition to the object being passed to + // action, the containing XObject dictionary and key are passed in. Remember that the XObject + // dictionary may be shared, and the object may appear in multiple XObject dictionaries. QPDF_DLL void forEachXObject( bool recursive, @@ -214,12 +181,10 @@ class QPDFPageObjectHelper: public QPDFObjectHelper std::function action); - // Returns an empty map if there are no images or no resources. - // Prior to qpdf 8.4.0, this function did not support inherited - // resources, but it does now. Return value is a map from XObject - // name to the image object, which is always a stream. Works with - // form XObjects as well as pages. This method does not recurse - // into nested form XObjects. For that, use forEachImage. + // Returns an empty map if there are no images or no resources. Prior to qpdf 8.4.0, this + // function did not support inherited resources, but it does now. Return value is a map from + // XObject name to the image object, which is always a stream. Works with form XObjects as well + // as pages. This method does not recurse into nested form XObjects. For that, use forEachImage. QPDF_DLL std::map getImages(); @@ -227,59 +192,48 @@ class QPDFPageObjectHelper: public QPDFObjectHelper QPDF_DLL std::map getPageImages(); - // Returns an empty map if there are no form XObjects or no - // resources. Otherwise, returns a map of keys to form XObjects - // directly referenced from this page or form XObjects. This does - // not recurse into nested form XObjects. For that, use - // forEachFormXObject. + // Returns an empty map if there are no form XObjects or no resources. Otherwise, returns a map + // of keys to form XObjects directly referenced from this page or form XObjects. This does not + // recurse into nested form XObjects. For that, use forEachFormXObject. QPDF_DLL std::map getFormXObjects(); - // Converts each inline image to an external (normal) image if the - // size is at least the specified number of bytes. This method - // works with pages or form XObjects. By default, it recursively - // processes nested form XObjects. Pass true as shallow to avoid - // this behavior. Prior to qpdf 10.1, form XObjects were ignored, - // but this was considered a bug. + // Converts each inline image to an external (normal) image if the size is at least the + // specified number of bytes. This method works with pages or form XObjects. By default, it + // recursively processes nested form XObjects. Pass true as shallow to avoid this behavior. + // Prior to qpdf 10.1, form XObjects were ignored, but this was considered a bug. QPDF_DLL void externalizeInlineImages(size_t min_size = 0, bool shallow = false); - // Return the annotations in the page's "/Annots" list, if any. If - // only_subtype is non-empty, only include annotations of the - // given subtype. + // Return the annotations in the page's "/Annots" list, if any. If only_subtype is non-empty, + // only include annotations of the given subtype. QPDF_DLL std::vector getAnnotations(std::string const& only_subtype = ""); - // Returns a vector of stream objects representing the content - // streams for the given page. This routine allows the caller to - // not care whether there are one or more than one content streams + // Returns a vector of stream objects representing the content streams for the given page. This + // routine allows the caller to not care whether there are one or more than one content streams // for a page. QPDF_DLL std::vector getPageContents(); - // Add the given object as a new content stream for this page. If - // parameter 'first' is true, add to the beginning. Otherwise, add - // to the end. This routine automatically converts the page - // contents to an array if it is a scalar, allowing the caller not - // to care what the initial structure is. You can call - // coalesceContentStreams() afterwards if you want to force it to - // be a single stream. + // Add the given object as a new content stream for this page. If parameter 'first' is true, add + // to the beginning. Otherwise, add to the end. This routine automatically converts the page + // contents to an array if it is a scalar, allowing the caller not to care what the initial + // structure is. You can call coalesceContentStreams() afterwards if you want to force it to be + // a single stream. QPDF_DLL void addPageContents(QPDFObjectHandle contents, bool first); - // Rotate a page. If relative is false, set the rotation of the - // page to angle. Otherwise, add angle to the rotation of the - // page. Angle must be a multiple of 90. Adding 90 to the rotation + // Rotate a page. If relative is false, set the rotation of the page to angle. Otherwise, add + // angle to the rotation of the page. Angle must be a multiple of 90. Adding 90 to the rotation // rotates clockwise by 90 degrees. QPDF_DLL void rotatePage(int angle, bool relative); - // Coalesce a page's content streams. A page's content may be a - // stream or an array of streams. If this page's content is an - // array, concatenate the streams into a single stream. This can - // be useful when working with files that split content streams in - // arbitrary spots, such as in the middle of a token, as that can - // confuse some software. You could also call this after calling + // Coalesce a page's content streams. A page's content may be a stream or an array of streams. + // If this page's content is an array, concatenate the streams into a single stream. This can be + // useful when working with files that split content streams in arbitrary spots, such as in the + // middle of a token, as that can confuse some software. You could also call this after calling // addPageContents. QPDF_DLL void coalesceContentStreams(); @@ -288,25 +242,21 @@ class QPDFPageObjectHelper: public QPDFObjectHelper // Content stream handling // - // Parse a page's contents through ParserCallbacks, described - // above. This method works whether the contents are a single - // stream or an array of streams. Call on a page object. Also - // works for form XObjects. + // Parse a page's contents through ParserCallbacks, described above. This method works whether + // the contents are a single stream or an array of streams. Call on a page object. Also works + // for form XObjects. QPDF_DLL void parseContents(QPDFObjectHandle::ParserCallbacks* callbacks); // Old name QPDF_DLL void parsePageContents(QPDFObjectHandle::ParserCallbacks* callbacks); - // Pass a page's or form XObject's contents through the given - // TokenFilter. If a pipeline is also provided, it will be the - // target of the write methods from the token filter. If a - // pipeline is not specified, any output generated by the token - // filter will be discarded. Use this interface if you need to - // pass a page's contents through filter for work purposes without - // having that filter automatically applied to the page's - // contents, as happens with addContentTokenFilter. See - // examples/pdf-count-strings.cc for an example. + // Pass a page's or form XObject's contents through the given TokenFilter. If a pipeline is also + // provided, it will be the target of the write methods from the token filter. If a pipeline is + // not specified, any output generated by the token filter will be discarded. Use this interface + // if you need to pass a page's contents through filter for work purposes without having that + // filter automatically applied to the page's contents, as happens with addContentTokenFilter. + // See examples/pdf-count-strings.cc for an example. QPDF_DLL void filterContents(QPDFObjectHandle::TokenFilter* filter, Pipeline* next = nullptr); @@ -314,95 +264,74 @@ class QPDFPageObjectHelper: public QPDFObjectHelper QPDF_DLL void filterPageContents(QPDFObjectHandle::TokenFilter* filter, Pipeline* next = nullptr); - // Pipe a page's contents through the given pipeline. This method - // works whether the contents are a single stream or an array of - // streams. Also works on form XObjects. + // Pipe a page's contents through the given pipeline. This method works whether the contents are + // a single stream or an array of streams. Also works on form XObjects. QPDF_DLL void pipeContents(Pipeline* p); // Old name QPDF_DLL void pipePageContents(Pipeline* p); - // Attach a token filter to a page's contents. If the page's - // contents is an array of streams, it is automatically coalesced. - // The token filter is applied to the page's contents as a single + // Attach a token filter to a page's contents. If the page's contents is an array of streams, it + // is automatically coalesced. The token filter is applied to the page's contents as a single // stream. Also works on form XObjects. QPDF_DLL void addContentTokenFilter(std::shared_ptr token_filter); - // A page's resources dictionary maps names to objects elsewhere - // in the file. This method walks through a page's contents and - // keeps tracks of which resources are referenced somewhere in the - // contents. Then it removes from the resources dictionary any - // object that is not referenced in the contents. This operation - // is most useful after calling - // QPDFPageDocumentHelper::pushInheritedAttributesToPage(). This - // method is used by page splitting code to avoid copying unused - // objects in files that used shared resource dictionaries across - // multiple pages. This method recurses into form XObjects and can - // be called with a form XObject as well as a page. + // A page's resources dictionary maps names to objects elsewhere in the file. This method walks + // through a page's contents and keeps tracks of which resources are referenced somewhere in the + // contents. Then it removes from the resources dictionary any object that is not referenced in + // the contents. This operation is most useful after calling + // QPDFPageDocumentHelper::pushInheritedAttributesToPage(). This method is used by page + // splitting code to avoid copying unused objects in files that used shared resource + // dictionaries across multiple pages. This method recurses into form XObjects and can be called + // with a form XObject as well as a page. QPDF_DLL void removeUnreferencedResources(); - // Return a new QPDFPageObjectHelper that is a duplicate of the - // page. The returned object is an indirect object that is ready - // to be inserted into the same or a different QPDF object using - // any of the addPage methods in QPDFPageDocumentHelper or QPDF. - // Without calling one of those methods, the page will not be - // added anywhere. The new page object shares all content streams - // and indirect object resources with the original page, so if you - // are going to modify the contents or other aspects of the page, - // you will need to handling copying of the component parts - // separately. + // Return a new QPDFPageObjectHelper that is a duplicate of the page. The returned object is an + // indirect object that is ready to be inserted into the same or a different QPDF object using + // any of the addPage methods in QPDFPageDocumentHelper or QPDF. Without calling one of those + // methods, the page will not be added anywhere. The new page object shares all content streams + // and indirect object resources with the original page, so if you are going to modify the + // contents or other aspects of the page, you will need to handling copying of the component + // parts separately. QPDF_DLL QPDFPageObjectHelper shallowCopyPage(); - // Return a transformation matrix whose effect is the same as the - // page's /Rotate and /UserUnit parameters. If invert is true, - // return a matrix whose effect is the opposite. The regular - // matrix is suitable for taking something from this page to put - // elsewhere, and the second one is suitable for putting something - // else onto this page. The page's TrimBox is used as the bounding - // box for purposes of computing the matrix. + // Return a transformation matrix whose effect is the same as the page's /Rotate and /UserUnit + // parameters. If invert is true, return a matrix whose effect is the opposite. The regular + // matrix is suitable for taking something from this page to put elsewhere, and the second one + // is suitable for putting something else onto this page. The page's TrimBox is used as the + // bounding box for purposes of computing the matrix. QPDF_DLL QPDFObjectHandle::Matrix getMatrixForTransformations(bool invert = false); - // Return a form XObject that draws this page. This is useful for - // n-up operations, underlay, overlay, thumbnail generation, or - // any other case in which it is useful to replicate the contents - // of a page in some other context. The dictionaries are shallow - // copies of the original page dictionary, and the contents are - // coalesced from the page's contents. The resulting object handle - // is not referenced anywhere. If handle_transformations is true, - // the resulting form XObject's /Matrix will be set to replicate - // rotation (/Rotate) and scaling (/UserUnit) in the page's - // dictionary. In this way, the page's transformations will be - // preserved when placing this object on another page. + // Return a form XObject that draws this page. This is useful for n-up operations, underlay, + // overlay, thumbnail generation, or any other case in which it is useful to replicate the + // contents of a page in some other context. The dictionaries are shallow copies of the original + // page dictionary, and the contents are coalesced from the page's contents. The resulting + // object handle is not referenced anywhere. If handle_transformations is true, the resulting + // form XObject's /Matrix will be set to replicate rotation (/Rotate) and scaling (/UserUnit) in + // the page's dictionary. In this way, the page's transformations will be preserved when placing + // this object on another page. QPDF_DLL QPDFObjectHandle getFormXObjectForPage(bool handle_transformations = true); - // Return content stream text that will place the given form - // XObject (fo) using the resource name "name" on this page - // centered within the given rectangle. If invert_transformations - // is true, the effect of any rotation (/Rotate) and scaling - // (/UserUnit) applied to the current page will be inverted in the - // form XObject placement. This will cause the form XObject's - // absolute orientation to be preserved. You could overlay one - // page on another by calling getFormXObjectForPage on the - // original page, QPDFObjectHandle::getUniqueResourceName on the - // destination page's Resources dictionary to generate a name for - // the resulting object, and calling placeFormXObject on the - // destination page. Then insert the new fo (or, if it comes from - // a different file, the result of calling copyForeignObject on - // it) into the resources dictionary using name, and append or - // prepend the content to the page's content streams. See the - // overlay/underlay code in qpdf.cc or - // examples/pdf-overlay-page.cc for an example. From qpdf 10.0.0, - // the allow_shrink and allow_expand parameters control whether - // the form XObject is allowed to be shrunk or expanded to stay - // within or maximally fill the destination rectangle. The default - // values are for backward compatibility with the pre-10.0.0 - // behavior. + // Return content stream text that will place the given form XObject (fo) using the resource + // name "name" on this page centered within the given rectangle. If invert_transformations is + // true, the effect of any rotation (/Rotate) and scaling (/UserUnit) applied to the current + // page will be inverted in the form XObject placement. This will cause the form XObject's + // absolute orientation to be preserved. You could overlay one page on another by calling + // getFormXObjectForPage on the original page, QPDFObjectHandle::getUniqueResourceName on the + // destination page's Resources dictionary to generate a name for the resulting object, and + // calling placeFormXObject on the destination page. Then insert the new fo (or, if it comes + // from a different file, the result of calling copyForeignObject on it) into the resources + // dictionary using name, and append or prepend the content to the page's content streams. See + // the overlay/underlay code in qpdf.cc or examples/pdf-overlay-page.cc for an example. From + // qpdf 10.0.0, the allow_shrink and allow_expand parameters control whether the form XObject is + // allowed to be shrunk or expanded to stay within or maximally fill the destination rectangle. + // The default values are for backward compatibility with the pre-10.0.0 behavior. QPDF_DLL std::string placeFormXObject( QPDFObjectHandle fo, @@ -412,8 +341,7 @@ class QPDFPageObjectHelper: public QPDFObjectHelper bool allow_shrink = true, bool allow_expand = false); - // Alternative version that also fills in the transformation - // matrix that was used. + // Alternative version that also fills in the transformation matrix that was used. QPDF_DLL std::string placeFormXObject( QPDFObjectHandle fo, @@ -424,10 +352,9 @@ class QPDFPageObjectHelper: public QPDFObjectHelper bool allow_shrink = true, bool allow_expand = false); - // Return the transformation matrix that translates from the given - // form XObject's coordinate system into the given rectangular - // region on the page. The parameters have the same meaning as for - // placeFormXObject. + // Return the transformation matrix that translates from the given form XObject's coordinate + // system into the given rectangular region on the page. The parameters have the same meaning as + // for placeFormXObject. QPDF_DLL QPDFMatrix getMatrixForFormXObjectPlacement( QPDFObjectHandle fo, @@ -436,43 +363,32 @@ class QPDFPageObjectHelper: public QPDFObjectHelper bool allow_shrink = true, bool allow_expand = false); - // If a page is rotated using /Rotate in the page's dictionary, - // instead rotate the page by the same amount by altering the - // contents and removing the /Rotate key. This method adjusts the - // various page bounding boxes (/MediaBox, etc.) so that the page - // will have the same semantics. This can be useful to work around - // problems with PDF applications that can't properly handle - // rotated pages. If a QPDFAcroFormDocumentHelper is provided, it - // will be used for resolving any form fields that have to be - // rotated. If not, one will be created inside the function, which + // If a page is rotated using /Rotate in the page's dictionary, instead rotate the page by the + // same amount by altering the contents and removing the /Rotate key. This method adjusts the + // various page bounding boxes (/MediaBox, etc.) so that the page will have the same semantics. + // This can be useful to work around problems with PDF applications that can't properly handle + // rotated pages. If a QPDFAcroFormDocumentHelper is provided, it will be used for resolving any + // form fields that have to be rotated. If not, one will be created inside the function, which // is less efficient. QPDF_DLL void flattenRotation(QPDFAcroFormDocumentHelper* afdh = nullptr); - // Copy annotations from another page into this page. The other - // page may be from the same QPDF or from a different QPDF. Each - // annotation's rectangle is transformed by the given matrix. If - // the annotation is a widget annotation that is associated with a - // form field, the form field is copied into this document's - // AcroForm dictionary as well. You can use this to copy - // annotations from a page that was converted to a form XObject - // and added to another page. For example of this, see - // examples/pdf-overlay-page.cc. This method calls - // QPDFAcroFormDocumentHelper::transformAnnotations, which will - // copy annotations and form fields so that you can copy - // annotations from a source page to any number of other pages, - // even with different matrices, and maintain independence from - // the original annotations. See also - // QPDFAcroFormDocumentHelper::fixCopiedAnnotations, which can be - // used if you copy a page and want to repair the annotations on - // the destination page to make them independent from the original - // page's annotations. + // Copy annotations from another page into this page. The other page may be from the same QPDF + // or from a different QPDF. Each annotation's rectangle is transformed by the given matrix. If + // the annotation is a widget annotation that is associated with a form field, the form field is + // copied into this document's AcroForm dictionary as well. You can use this to copy annotations + // from a page that was converted to a form XObject and added to another page. For example of + // this, see examples/pdf-overlay-page.cc. This method calls + // QPDFAcroFormDocumentHelper::transformAnnotations, which will copy annotations and form fields + // so that you can copy annotations from a source page to any number of other pages, even with + // different matrices, and maintain independence from the original annotations. See also + // QPDFAcroFormDocumentHelper::fixCopiedAnnotations, which can be used if you copy a page and + // want to repair the annotations on the destination page to make them independent from the + // original page's annotations. // - // If you pass in a QPDFAcroFormDocumentHelper*, the method will - // use that instead of creating one in the function. Creating - // QPDFAcroFormDocumentHelper objects is expensive, so if you're - // doing a lot of copying, it can be more efficient to create - // these outside and pass them in. + // If you pass in a QPDFAcroFormDocumentHelper*, the method will use that instead of creating + // one in the function. Creating QPDFAcroFormDocumentHelper objects is expensive, so if you're + // doing a lot of copying, it can be more efficient to create these outside and pass them in. QPDF_DLL void copyAnnotations( QPDFPageObjectHelper from_page, diff --git a/include/qpdf/QPDFTokenizer.hh b/include/qpdf/QPDFTokenizer.hh index b07b7c0b..d8bc43b6 100644 --- a/include/qpdf/QPDFTokenizer.hh +++ b/include/qpdf/QPDFTokenizer.hh @@ -2,22 +2,19 @@ // // This file is part of qpdf. // -// 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 +// 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. +// 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. // -// Versions of qpdf prior to version 7 were released under the terms -// of version 2.0 of the Artistic License. At your option, you may -// continue to consider qpdf to be licensed under those terms. Please -// see the manual for additional information. +// Versions of qpdf prior to version 7 were released under the terms of version 2.0 of the Artistic +// License. At your option, you may continue to consider qpdf to be licensed under those terms. +// Please see the manual for additional information. #ifndef QPDFTOKENIZER_HH #define QPDFTOKENIZER_HH @@ -34,9 +31,8 @@ class QPDFTokenizer { public: - // Token type tt_eof is only returned of allowEOF() is called on - // the tokenizer. tt_eof was introduced in QPDF version 4.1. - // tt_space, tt_comment, and tt_inline_image were added in QPDF + // Token type tt_eof is only returned of allowEOF() is called on the tokenizer. tt_eof was + // introduced in QPDF version 4.1. tt_space, tt_comment, and tt_inline_image were added in QPDF // version 8. enum token_type_e { tt_bad, @@ -132,72 +128,65 @@ class QPDFTokenizer QPDF_DLL QPDFTokenizer(); - // If called, treat EOF as a separate token type instead of an - // error. This was introduced in QPDF 4.1 to facilitate - // tokenizing content streams. + // If called, treat EOF as a separate token type instead of an error. This was introduced in + // QPDF 4.1 to facilitate tokenizing content streams. QPDF_DLL void allowEOF(); - // If called, readToken will return "ignorable" tokens for space - // and comments. This was added in QPDF 8. + // If called, readToken will return "ignorable" tokens for space and comments. This was added in + // QPDF 8. QPDF_DLL void includeIgnorable(); - // There are two modes of operation: push and pull. The pull - // method is easier but requires an input source. The push method - // is more complicated but can be used to tokenize a stream of + // There are two modes of operation: push and pull. The pull method is easier but requires an + // input source. The push method is more complicated but can be used to tokenize a stream of // incoming characters in a pipeline. // Push mode: - // Keep presenting characters with presentCharacter() and - // presentEOF() and calling getToken() until getToken() returns - // true. When it does, be sure to check unread_ch and to unread ch - // if it is true. + // Keep presenting characters with presentCharacter() and presentEOF() and calling getToken() + // until getToken() returns true. When it does, be sure to check unread_ch and to unread ch if + // it is true. - // It these are called when a token is available, an exception - // will be thrown. + // It these are called when a token is available, an exception will be thrown. QPDF_DLL void presentCharacter(char ch); QPDF_DLL void presentEOF(); - // If a token is available, return true and initialize token with - // the token, unread_char with whether or not we have to unread - // the last character, and if unread_char, ch with the character - // to unread. + // If a token is available, return true and initialize token with the token, unread_char with + // whether or not we have to unread the last character, and if unread_char, ch with the + // character to unread. QPDF_DLL bool getToken(Token& token, bool& unread_char, char& ch); - // This function returns true of the current character is between - // tokens (i.e., white space that is not part of a string) or is - // part of a comment. A tokenizing filter can call this to + // This function returns true of the current character is between tokens (i.e., white space that + // is not part of a string) or is part of a comment. A tokenizing filter can call this to // determine whether to output the character. QPDF_DLL bool betweenTokens(); // Pull mode: - // Read a token from an input source. Context describes the - // context in which the token is being read and is used in the - // exception thrown if there is an error. After a token is read, - // the position of the input source returned by input->tell() - // points to just after the token, and the input source's "last - // offset" as returned by input->getLastOffset() points to the + // Read a token from an input source. Context describes the context in which the token is being + // read and is used in the exception thrown if there is an error. After a token is read, the + // position of the input source returned by input->tell() points to just after the token, and + // the input source's "last offset" as returned by input->getLastOffset() points to the // beginning of the token. QPDF_DLL + Token readToken( + InputSource& input, std::string const& context, bool allow_bad = false, size_t max_len = 0); + QPDF_DLL Token readToken( std::shared_ptr input, std::string const& context, bool allow_bad = false, size_t max_len = 0); - // Calling this method puts the tokenizer in a state for reading - // inline images. You should call this method after reading the - // character following the ID operator. In that state, it will - // return all data up to BUT NOT INCLUDING the next EI token. - // After you call this method, the next call to readToken (or the - // token created next time getToken returns true) will either be + // Calling this method puts the tokenizer in a state for reading inline images. You should call + // this method after reading the character following the ID operator. In that state, it will + // return all data up to BUT NOT INCLUDING the next EI token. After you call this method, the + // next call to readToken (or the token created next time getToken returns true) will either be // tt_inline_image or tt_bad. This is the only way readToken // returns a tt_inline_image token. QPDF_DLL @@ -206,21 +195,18 @@ class QPDFTokenizer private: friend class QPDFParser; - // Read a token from an input source. Context describes the - // context in which the token is being read and is used in the - // exception thrown if there is an error. After a token is read, - // the position of the input source returned by input->tell() - // points to just after the token, and the input source's "last - // offset" as returned by input->getLastOffset() points to the - // beginning of the token. Returns false if the token is bad - // or if scanning produced an error message for any reason. + // Read a token from an input source. Context describes the context in which the token is being + // read and is used in the exception thrown if there is an error. After a token is read, the + // position of the input source returned by input->tell() points to just after the token, and + // the input source's "last offset" as returned by input->getLastOffset() points to the + // beginning of the token. Returns false if the token is bad or if scanning produced an error + // message for any reason. bool nextToken(InputSource& input, std::string const& context, size_t max_len = 0); - // The following methods are only valid after nextToken has been called - // and until another QPDFTokenizer method is called. They allow the results - // of calling nextToken to be accessed without creating a Token, thus - // avoiding copying information that may not be needed. + // The following methods are only valid after nextToken has been called and until another + // QPDFTokenizer method is called. They allow the results of calling nextToken to be accessed + // without creating a Token, thus avoiding copying information that may not be needed. inline token_type_e getType() const noexcept; inline std::string const& getValue() const noexcept; inline std::string const& getRawValue() const noexcept; -- cgit v1.2.3-54-g00ecf