diff --git a/BUILDING.md b/BUILDING.md index 51c3510b2c..d7e407adc3 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -1,3 +1,6 @@ + +# Building and testing **iText Community** + To build **iText Community**, you need to build `itextsharp/itextcore/iTextCore.sln`. To run tests, [Ghostscript][1] and [Imagemagick][2] must be installed. Some of the tests compare generated PDF files with template files that show the correct results, and these tools are used to @@ -14,5 +17,17 @@ environment variables. Examples of paths on Windows: If you have a new version of ImageMagick, then there is no compare.exe utility there, wrap the path to magick.exe in quotes and call compare command: ITEXT_MAGICK_COMPARE_EXEC=`"C:\Program Files\ImageMagick-7.0.9-Q16\magick.exe" compare` + +# Deploying iText + +When using **iText Community** in a project and want to deploy it you have to consider a few things for different deployments. + +- **FrameworkDependend**: No additional parameters are required. +- **SelfContained**: No additional parameters are required. +- **PublishSingleFile**: When using `-p:PublishSingleFile=true` you will also need to add `-p:IncludeAllContentForSelfExtract=true`. This is important when using `hyph` or `font-asian` modules. +- **AssemblyTrimming**: Using `-p:PublishTrimmed=true` is currently not supported. + + + [1]: https://www.ghostscript.com/ -[2]: https://www.imagemagick.org/ \ No newline at end of file +[2]: https://www.imagemagick.org/ diff --git a/README.md b/README.md index 012be9bbf9..63cb398705 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,8 @@ ![Nuget](https://img.shields.io/nuget/dt/itext7) ![GitHub commit activity (branch)](https://img.shields.io/github/commit-activity/m/itext/itext7-dotnet) -iText Core/Community **(previously known as iTextSharp)** is a high-performance, battle-tested library that allows you to create, adapt, +iText Core/Community **(previously known as iTextSharp)** is a high-performance, battle-tested library that allows you +to create, adapt, inspect and maintain PDF documents, allowing you to add PDF functionality to your software projects with ease. It is also available for [Java](https://github.com/itext/itext7). @@ -36,14 +37,16 @@ demo applications ready to use online! ### Getting started -The easiest way to get started is to use NuGet, just execute the following install command in the folder of your project: +The easiest way to get started is to use NuGet, just execute the following install command in the folder of your +project: ```shell -dotnet add package itext --version 8.0.2 -dotnet add package itext.bouncy-castle-adapter --version 8.0.2 +dotnet add package itext --version +dotnet add package itext.bouncy-castle-adapter --version ``` -For more advanced use cases, please refer to the [Installation guidelines](https://kb.itextpdf.com/home/it7kb/installation-guidelines). +For more advanced use cases, please refer to +the [Installation guidelines](https://kb.itextpdf.com/home/it7kb/installation-guidelines). You can also [build iText Community from source][building]. ### Hello PDF! @@ -67,64 +70,69 @@ namespace HelloPdf { ### Examples -For more advanced examples, refer to our [Knowledge Base](https://kb.itextpdf.com/home/it7kb/examples) or the main [Examples repo](https://github.com/itext/i7ns-samples). You can find C# equivalents to the Java [Signing examples](https://github.com/itext/i7js-signing-examples) [here](https://github.com/itext/i7ns-samples/tree/develop/itext/itext.publications), though the Java code is very similar since they have the same API. - +For more advanced examples, refer to our [Knowledge Base](https://kb.itextpdf.com/home/it7kb/examples) or the +main [Examples repo](https://github.com/itext/i7ns-samples). You can find C# equivalents to the +Java [Signing examples](https://github.com/itext/i7js-signing-examples) [here](https://github.com/itext/i7ns-samples/tree/develop/itext/itext.publications), +though the Java code is very similar since they have the same API. Some of the output PDF files will be incorrectly displayed by the GitHub previewer, so be sure to download them to see the correct results. -| Description | Link | -|--------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| **Basic layout** | | -| Change text properties | [C#](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/itext/samples/sandbox/layout/ParagraphTextWithStyle.cs), [PDF](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/cmpfiles/sandbox/layout/cmp_paragraphTextWithStyle.pdf) | -| Creating a simple table | [C#](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/itext/samples/sandbox/tables/SimpleTable9.cs), [PDF](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/cmpfiles/sandbox/tables/cmp_simple_table9.pdf) | -| Add an image to a PDF document | [C#](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/itext/samples/sandbox/images/MultipleImages.cs), [PDF](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/cmpfiles/sandbox/images/cmp_multiple_images.pdf) | -| Create a list | [C#](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/itext/samples/sandbox/objects/NestedLists.cs), [PDF](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/cmpfiles/sandbox/objects/cmp_nested_list.pdf) | -| Add a watermark | [C#](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/itext/samples/sandbox/events/Watermarking.cs), [PDF](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/cmpfiles/sandbox/events/cmp_watermarkings.pdf) | -| Add links to navigate within a document | [C#](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/itext/samples/sandbox/annotations/AddLinkAnnotation5.cs), [PDF](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/cmpfiles/sandbox/annotations/cmp_add_link_annotation5.pdf) | -| Create a popup annotation | [C#](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/itext/samples/sandbox/annotations/MovePopup.cs), [PDF](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/cmpfiles/sandbox/annotations/cmp_move_popup.pdf) | -| Change font | [C#](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/itext/samples/sandbox/layout/ParagraphTextWithStyle.cs) | -| Add form fields | [C#](https://kb.itextpdf.com/home/it7kb/examples/forms-in-itext-core-8-0-0) | -
| | -| **General document settings** | | -| Change page size and margin | [C#](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/itext/samples/sandbox/layout/PageSizeAndMargins.cs), [PDF](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/cmpfiles/sandbox/layout/cmp_pageSizeAndMargins.pdf) | -| Write PDF to byte array instead of to disk | [C#](https://stackoverflow.com/a/67411657/10015628) | -| Change page rotation | [C#](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/itext/samples/sandbox/events/PageRotation.cs), [PDF](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/cmpfiles/sandbox/events/cmp_page_rotation.pdf) | -| Add header and footer | [C#](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/itext/samples/sandbox/events/TextFooter.cs), [PDF](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/cmpfiles/sandbox/events/cmp_text_footer.pdf) | -| Merge documents | [C#](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/itext/samples/sandbox/merge/AddCover1.cs), [PDF](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/cmpfiles/sandbox/merge/cmp_add_cover.pdf) | -| Flatten annotations | [C#](https://kb.itextpdf.com/home/it7kb/examples/high-level-annotation-flattening) | -|
| | -| **PDF/UA, PDF/A** | | -| Create PDF/UA document | [C#](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/itext/samples/sandbox/pdfua/PdfUA.cs), [PDF](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/cmpfiles/sandbox/pdfua/cmp_pdf_ua.pdf) | -| Create PDF/A-3 document | [C#](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/itext/samples/sandbox/pdfa/PdfA3.cs) | -|
| | -| **FIPS** | | -| Enable FIPS | [C#](https://kb.itextpdf.com/home/it7kb/releases/release-itext-core-8-0-0/breaking-changes-for-itext-core-8-0-0/bouncy-castle-changes) | -| FIPS SHA3 example | [C#](https://kb.itextpdf.com/home/it7kb/examples/fips-sha3-examples-for-itext-core-8-0-0) | -|
| | -| **Convert HTML and CSS to PDF** | [Link to repo](https://github.com/itext/i7j-pdfhtml) | -| Convert simple HTML doc to PDF | [C#](https://kb.itextpdf.com/home/it7kb/ebooks/itext-7-converting-html-to-pdf-with-pdfhtml) | -|
| | -| **Secure redaction of content** | [Link to repo](https://github.com/itext/i7j-pdfsweep) | -| Redacting content | [C#](https://kb.itextpdf.com/home/it7kb/examples/removing-content-with-pdfsweep) | -| Redact based on regex | [C#](https://itextpdf.com/products/pdf-redaction-pdfsweep) | -|
| | -| **Support complex writing systems** | [Link to docs](https://itextpdf.com/products/pdfcalligraph) | +| Description | Link | +|--------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| **Basic layout** | | +| Change text properties | [C#](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/itext/samples/sandbox/layout/ParagraphTextWithStyle.cs), [PDF](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/cmpfiles/sandbox/layout/cmp_paragraphTextWithStyle.pdf) | +| Creating a simple table | [C#](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/itext/samples/sandbox/tables/SimpleTable9.cs), [PDF](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/cmpfiles/sandbox/tables/cmp_simple_table9.pdf) | +| Add an image to a PDF document | [C#](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/itext/samples/sandbox/images/MultipleImages.cs), [PDF](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/cmpfiles/sandbox/images/cmp_multiple_images.pdf) | +| Create a list | [C#](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/itext/samples/sandbox/objects/NestedLists.cs), [PDF](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/cmpfiles/sandbox/objects/cmp_nested_list.pdf) | +| Add a watermark | [C#](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/itext/samples/sandbox/events/Watermarking.cs), [PDF](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/cmpfiles/sandbox/events/cmp_watermarkings.pdf) | +| Add links to navigate within a document | [C#](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/itext/samples/sandbox/annotations/AddLinkAnnotation5.cs), [PDF](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/cmpfiles/sandbox/annotations/cmp_add_link_annotation5.pdf) | +| Create a popup annotation | [C#](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/itext/samples/sandbox/annotations/MovePopup.cs), [PDF](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/cmpfiles/sandbox/annotations/cmp_move_popup.pdf) | +| Change font | [C#](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/itext/samples/sandbox/layout/ParagraphTextWithStyle.cs) | +| Add form fields | [C#](https://kb.itextpdf.com/home/it7kb/examples/forms-in-itext-core-8-0-0) | +
| | +| **General document settings** | | +| Change page size and margin | [C#](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/itext/samples/sandbox/layout/PageSizeAndMargins.cs), [PDF](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/cmpfiles/sandbox/layout/cmp_pageSizeAndMargins.pdf) | +| Write PDF to byte array instead of to disk | [C#](https://stackoverflow.com/a/67411657/10015628) | +| Change page rotation | [C#](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/itext/samples/sandbox/events/PageRotation.cs), [PDF](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/cmpfiles/sandbox/events/cmp_page_rotation.pdf) | +| Add header and footer | [C#](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/itext/samples/sandbox/events/TextFooter.cs), [PDF](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/cmpfiles/sandbox/events/cmp_text_footer.pdf) | +| Merge documents | [C#](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/itext/samples/sandbox/merge/AddCover1.cs), [PDF](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/cmpfiles/sandbox/merge/cmp_add_cover.pdf) | +| Flatten annotations | [C#](https://kb.itextpdf.com/home/it7kb/examples/high-level-annotation-flattening) | +|
| | +| **PDF/UA, PDF/A** | | +| Create PDF/UA document | [C#](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/itext/samples/sandbox/pdfua/PdfUA.cs), [PDF](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/cmpfiles/sandbox/pdfua/cmp_pdf_ua.pdf) | +| Create PDF/A-3 document | [C#](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/itext/samples/sandbox/pdfa/PdfA3.cs) | +| Create PDF/A-4 document | [C#](https://github.com/itext/i7ns-samples/blob/develop/itext/itext.samples/itext/samples/sandbox/pdfa/PdfA4.cs) | +| Create Wtpdf document | [C#](https://github.com/itext/i7ns-samples/blob/develop/itext/itext.samples/itext/samples/sandbox/pdfua/Wtpdf.cs) | +|
| | +| **FIPS** | | +| Enable FIPS | [C#](https://kb.itextpdf.com/home/it7kb/releases/release-itext-core-8-0-0/breaking-changes-for-itext-core-8-0-0/bouncy-castle-changes) | +| FIPS SHA3 example | [C#](https://kb.itextpdf.com/home/it7kb/examples/fips-sha3-examples-for-itext-core-8-0-0) | +|
| | +| **Convert HTML and CSS to PDF** | [Link to repo](https://github.com/itext/i7j-pdfhtml) | +| Convert simple HTML doc to PDF | [C#](https://kb.itextpdf.com/home/it7kb/ebooks/itext-7-converting-html-to-pdf-with-pdfhtml) | +|
| | +| **Secure redaction of content** | [Link to repo](https://github.com/itext/i7j-pdfsweep) | +| Redacting content | [C#](https://kb.itextpdf.com/home/it7kb/examples/removing-content-with-pdfsweep) | +| Redact based on regex | [C#](https://itextpdf.com/products/pdf-redaction-pdfsweep) | +|
| | +| **Support complex writing systems** | [Link to docs](https://itextpdf.com/products/pdfcalligraph) | | Add Arabic text | [C#](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/itext/samples/sandbox/typography/arabic/ArabicWordSpacing.cs), [PDF](https://github.com/itext/i7ns-samples/blob/master/itext/itext.samples/cmpfiles/sandbox/typography/cmp_ArabicWordSpacing.pdf) | -|
| | -| **Optimizing PDFs** | [Link to docs](https://itextpdf.com/products/compress-pdf-pdfoptimizer) | -| Reduce size of PDF | [C#](https://itextpdf.com/products/compress-pdf-pdfoptimizer) | -|
| | -| **XFA flattening** | [Link to docs](https://itextpdf.com/products/flatten-pdf-pdfxfa) | -| Flatten an XFA document | [C#](https://itextpdf.com/products/flatten-pdf-pdfxfa) | -|
| | -| **RUPS** | [Link to repo](https://github.com/itext/i7j-rups) | -| Debug a PDF | [C#](https://github.com/itext/i7j-rups/releases/latest) | +|
| | +| **Optimizing PDFs** | [Link to docs](https://itextpdf.com/products/compress-pdf-pdfoptimizer) | +| Reduce size of PDF | [C#](https://itextpdf.com/products/compress-pdf-pdfoptimizer) | +|
| | +| **XFA flattening** | [Link to docs](https://itextpdf.com/products/flatten-pdf-pdfxfa) | +| Flatten an XFA document | [C#](https://itextpdf.com/products/flatten-pdf-pdfxfa) | +|
| | +| **RUPS** | [Link to repo](https://github.com/itext/i7j-rups) | +| Debug a PDF | [C#](https://github.com/itext/i7j-rups/releases/latest) | ### FAQs, tutorials, etc. ### -Check out the [iText Knowledge Base](https://kb.itextpdf.com) for the [iText Jump-start tutorial](https://kb.itextpdf.com/home/it7kb/ebooks/itext-jump-start-tutorial-for-net) and other +Check out the [iText Knowledge Base](https://kb.itextpdf.com) for +the [iText Jump-start tutorial](https://kb.itextpdf.com/home/it7kb/ebooks/itext-jump-start-tutorial-for-net) and other tutorials, [FAQs](https://kb.itextpdf.com/home/it7kb/faq) and more. For specific information and examples relating to digital signatures and iText, make sure to check the [Digital Signatures Hub](https://kb.itextpdf.com/home/it7kb/digital-signatures-hub). @@ -149,7 +157,9 @@ Please read our [Contribution Guidelines][contributing] for details on code subm AGPL is a free/open-source software license, however, this doesn't mean the software is [gratis][gratis]! -The AGPL is a copyleft license, which means that any derivative work must also be licensed under the same terms. If you’re using iText in software or a service which cannot comply with the AGPL terms, we have a commercial license available that exempts you from such obligations. +The AGPL is a copyleft license, which means that any derivative work must also be licensed under the same terms. If +you’re using iText in software or a service which cannot comply with the AGPL terms, we have a commercial license +available that exempts you from such obligations. Contact [Sales] for more info. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000000..7b6923f5f8 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,40 @@ +# iText Security Policy + +## Reporting a Vulnerability + +We are committed to maintaining the security of our software. If you discover a security vulnerability, we encourage you to report it to us as soon as possible. + +To report a vulnerability, please visit our [Vulnerability Reporting Page](https://itextpdf.com/report-vulnerability), or email [vulnerability@apryse.com](vulnerability@apryse.com). If you do not receive a response in 2 business days, please follow up as we may not have received your message. + +We follow the procedure of Coordinated Vulnerability Disclosure (CVD) and, to protect the ecosystem, we request that those reporting do the same. Please visit the above page for more information, and follow the steps below to ensure that your report is handled promptly and appropriately: + +1. **Do not disclose the vulnerability publicly** until we have had a chance to address it. +2. **Provide a detailed description** of the vulnerability, including steps to reproduce it, if possible. +3. **Include any relevant information** such as the version of iText Core you are using, your operating system, and any other pertinent details. + +## Security Updates and Patches + + When a vulnerability is reported, we will: + +1. **Investigate and verify** the vulnerability. +2. **Develop and test** a fix for the vulnerability. +3. **Release a patch** as soon as possible. + + +## Known Vulnerabilities + +The iText Knowledge Base has a page for known [Common Vulnerabilities and Exposures](https://kb.itextpdf.com/itext/cves) (CVEs), please check it to ensure your vulnerability has not already been disclosed or addressed. + +## Supported product lines + +See [Compatibility Matrix](https://kb.itextpdf.com/itext/compatibility-matrix) + +## Security Best Practices + +To help ensure the security of your applications using iText Core, we recommend the following best practices: + +1. **Keep iText Core up to date** by regularly checking for and applying updates. +2. **Review and follow** our security guidelines for secure usage. +3. **Monitor your applications** for any unusual activity and investigate any anomalies promptly. + +Thank you for helping us keep iText secure! diff --git a/doxyfile b/doxyfile index ce8091e8f4..b2bff379ec 100644 --- a/doxyfile +++ b/doxyfile @@ -32,7 +32,7 @@ DOXYFILE_ENCODING = UTF-8 # title of most generated pages and in a few other places. # The default value is: My Project. -PROJECT_NAME = "iText 8.0.5 API" +PROJECT_NAME = "iText 9.0.0 API" # The PROJECT_NUMBER tag can be used to enter a project or revision number. This # could be handy for archiving the generated documentation or if some version diff --git a/itext.nuspec b/itext.nuspec index 612e3787c8..426e0d5040 100644 --- a/itext.nuspec +++ b/itext.nuspec @@ -2,7 +2,7 @@ itext - 8.0.5 + 9.0.0 iText Community Apryse Software Apryse Software @@ -19,11 +19,11 @@ - + - + diff --git a/itext.tests/itext.barcodes.tests/Properties/AssemblyInfo.cs b/itext.tests/itext.barcodes.tests/Properties/AssemblyInfo.cs index ba7c43e7e9..568d1ca537 100644 --- a/itext.tests/itext.barcodes.tests/Properties/AssemblyInfo.cs +++ b/itext.tests/itext.barcodes.tests/Properties/AssemblyInfo.cs @@ -14,9 +14,9 @@ [assembly: Guid("d015a3aa-613c-45d9-b908-7d47c4b613af")] -[assembly: AssemblyVersion("8.0.5.0")] -[assembly: AssemblyFileVersion("8.0.5.0")] -[assembly: AssemblyInformationalVersion("8.0.5")] +[assembly: AssemblyVersion("9.0.0.0")] +[assembly: AssemblyFileVersion("9.0.0.0")] +[assembly: AssemblyInformationalVersion("9.0.0")] #if !NETSTANDARD2_0 [assembly: NUnit.Framework.Timeout(300000)] diff --git a/itext.tests/itext.commons.tests/Properties/AssemblyInfo.cs b/itext.tests/itext.commons.tests/Properties/AssemblyInfo.cs index b97a8d26dc..8f0439514b 100644 --- a/itext.tests/itext.commons.tests/Properties/AssemblyInfo.cs +++ b/itext.tests/itext.commons.tests/Properties/AssemblyInfo.cs @@ -15,9 +15,9 @@ [assembly: Guid("502eda37-c014-4822-8e5c-4e5d21b085e9")] -[assembly: AssemblyVersion("8.0.5.0")] -[assembly: AssemblyFileVersion("8.0.5.0")] -[assembly: AssemblyInformationalVersion("8.0.5")] +[assembly: AssemblyVersion("9.0.0.0")] +[assembly: AssemblyFileVersion("9.0.0.0")] +[assembly: AssemblyInformationalVersion("9.0.0")] #if !NETSTANDARD2_0 [assembly: NUnit.Framework.Timeout(300000)] diff --git a/itext.tests/itext.commons.tests/itext/commons/actions/AbstractProductITextEventTest.cs b/itext.tests/itext.commons.tests/itext/commons/actions/AbstractProductITextEventTest.cs index 617cae1a92..ce878fc2ef 100644 --- a/itext.tests/itext.commons.tests/itext/commons/actions/AbstractProductITextEventTest.cs +++ b/itext.tests/itext.commons.tests/itext/commons/actions/AbstractProductITextEventTest.cs @@ -29,13 +29,13 @@ namespace iText.Commons.Actions { public class AbstractProductITextEventTest : ExtendedITextTest { [NUnit.Framework.Test] public virtual void NullProductDataTest() { - Exception exception = NUnit.Framework.Assert.Catch(typeof(InvalidOperationException), () => new _AbstractProductITextEvent_36 + Exception exception = NUnit.Framework.Assert.Catch(typeof(InvalidOperationException), () => new _AbstractProductITextEvent_35 (null)); NUnit.Framework.Assert.AreEqual("ProductData shouldn't be null.", exception.Message); } - private sealed class _AbstractProductITextEvent_36 : AbstractProductITextEvent { - public _AbstractProductITextEvent_36(ProductData baseArg1) + private sealed class _AbstractProductITextEvent_35 : AbstractProductITextEvent { + public _AbstractProductITextEvent_35(ProductData baseArg1) : base(baseArg1) { } } diff --git a/itext.tests/itext.commons.tests/itext/commons/datastructures/portable/NullUnlimitedListTest.cs b/itext.tests/itext.commons.tests/itext/commons/datastructures/portable/NullUnlimitedListTest.cs new file mode 100644 index 0000000000..f4c28f15e4 --- /dev/null +++ b/itext.tests/itext.commons.tests/itext/commons/datastructures/portable/NullUnlimitedListTest.cs @@ -0,0 +1,213 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using System.Collections.Generic; +using iText.Commons.Datastructures; +using iText.Test; + +namespace iText.Commons.Datastructures.Portable { + [NUnit.Framework.Category("UnitTest")] + public class NullUnlimitedListTest : ExtendedITextTest { + [NUnit.Framework.Test] + public virtual void NullUnlimitedListAddTest() { + NullUnlimitedList list = new NullUnlimitedList(); + list.Add("hey"); + list.Add("bye"); + NUnit.Framework.Assert.AreEqual(2, list.Size()); + list.Add(-1, "hello"); + list.Add(3, "goodbye"); + NUnit.Framework.Assert.AreEqual(2, list.Size()); + } + + [NUnit.Framework.Test] + public virtual void NullUnlimitedListIndexOfTest() { + NullUnlimitedList list = new NullUnlimitedList(); + list.Add("hey"); + list.Add(null); + list.Add("bye"); + list.Add(null); + NUnit.Framework.Assert.AreEqual(4, list.Size()); + NUnit.Framework.Assert.AreEqual(1, list.IndexOf(null)); + } + + [NUnit.Framework.Test] + public virtual void NullUnlimitedListRemoveTest() { + NullUnlimitedList list = new NullUnlimitedList(); + list.Add("hey"); + list.Add("bye"); + NUnit.Framework.Assert.AreEqual(2, list.Size()); + list.Remove(-1); + list.Remove(2); + NUnit.Framework.Assert.AreEqual(2, list.Size()); + } + + [NUnit.Framework.Test] + public virtual void TestIsEmpty() { + NullUnlimitedList list = new NullUnlimitedList(); + NUnit.Framework.Assert.IsTrue(list.IsEmpty()); + list.Add("hey"); + NUnit.Framework.Assert.IsFalse(list.IsEmpty()); + } + + [NUnit.Framework.Test] + public virtual void TestSameBehaviour01() { + IList>> actionList = new List>>(); + actionList.Add((list) => list.Add("1")); + actionList.Add((list) => list.Add(null)); + actionList.Add((list) => list.Add("1")); + actionList.Add((list) => list.Add("1")); + actionList.Add((list) => NUnit.Framework.Assert.AreEqual(1, list.IndexOf(null))); + ExecuteActions(actionList); + } + + [NUnit.Framework.Test] + public virtual void TestSameBehaviour02() { + IList>> actionList = new List>>(); + actionList.Add((list) => list.Add("1")); + actionList.Add((list) => list.Add(null)); + actionList.Add((list) => list.Add("1")); + actionList.Add((list) => list.Add("1")); + actionList.Add((list) => NUnit.Framework.Assert.AreEqual(4, list.Size())); + ExecuteActions(actionList); + } + + [NUnit.Framework.Test] + public virtual void TestSameBehaviour03() { + IList>> actionList = new List>>(); + actionList.Add((list) => list.Add("1")); + actionList.Add((list) => list.Add(null)); + actionList.Add((list) => list.Add("1")); + actionList.Add((list) => list.Add("1")); + actionList.Add((list) => list.Add(null)); + actionList.Add((list) => list.Set(1, "4")); + actionList.Add((list) => NUnit.Framework.Assert.AreEqual(list.Get(1), "4")); + ExecuteActions(actionList); + } + + [NUnit.Framework.Test] + public virtual void TestSameBehaviour04() { + IList>> actionList = new List>>(); + actionList.Add((list) => list.Add("1")); + actionList.Add((list) => list.Add(null)); + actionList.Add((list) => list.Add("1")); + actionList.Add((list) => list.Add("1")); + actionList.Add((list) => list.Add(null)); + actionList.Add((list) => NUnit.Framework.Assert.AreEqual(1, list.IndexOf(null))); + ExecuteActions(actionList); + } + + [NUnit.Framework.Test] + public virtual void TestSameBehaviour05() { + IList>> actionList = new List>>(); + actionList.Add((list) => list.Add("1")); + actionList.Add((list) => list.Add("1")); + actionList.Add((list) => list.Add("1")); + actionList.Add((list) => list.Add("1")); + actionList.Add((list) => list.Add("1")); + actionList.Add((list) => NUnit.Framework.Assert.AreEqual(-1, list.IndexOf(null))); + ExecuteActions(actionList); + } + + [NUnit.Framework.Test] + public virtual void TestSameBehaviour06() { + IList>> actionList = new List>>(); + actionList.Add((list) => list.Add("1")); + actionList.Add((list) => list.Add("2")); + actionList.Add((list) => list.Add("3")); + actionList.Add((list) => list.Add("4")); + actionList.Add((list) => list.Add("5")); + actionList.Add((list) => NUnit.Framework.Assert.AreEqual(4, list.IndexOf("5"))); + ExecuteActions(actionList); + } + + [NUnit.Framework.Test] + public virtual void TestSameBehaviour07() { + IList>> actionList = new List>>(); + actionList.Add((list) => list.Add("1")); + actionList.Add((list) => list.Add("2")); + actionList.Add((list) => list.Add("3")); + actionList.Add((list) => list.Add("4")); + actionList.Add((list) => list.Add("5")); + actionList.Add((list) => NUnit.Framework.Assert.AreEqual(-1, list.IndexOf("6"))); + ExecuteActions(actionList); + } + + [NUnit.Framework.Test] + public virtual void TestSameBehaviour08() { + IList>> actionList = new List>>(); + actionList.Add((list) => list.Add("1")); + actionList.Add((list) => list.Add("2")); + actionList.Add((list) => list.Add("3")); + actionList.Add((list) => list.Add("4")); + actionList.Add((list) => list.Add(2, "5")); + actionList.Add((list) => NUnit.Framework.Assert.AreEqual(5, list.Size())); + ExecuteActions(actionList); + } + + [NUnit.Framework.Test] + public virtual void TestSameBehaviour09() { + IList>> actionList = new List>>(); + actionList.Add((list) => list.Add("1")); + actionList.Add((list) => list.Add("2")); + actionList.Add((list) => list.Add("3")); + actionList.Add((list) => list.Add("4")); + actionList.Add((list) => list.Set(2, null)); + actionList.Add((list) => NUnit.Framework.Assert.AreEqual(4, list.Size())); + ExecuteActions(actionList); + } + + [NUnit.Framework.Test] + public virtual void TestSameBehaviour10() { + IList>> actionList = new List>>(); + actionList.Add((list) => list.Add("1")); + actionList.Add((list) => list.Add("2")); + actionList.Add((list) => list.Add("3")); + actionList.Add((list) => list.Add("4")); + actionList.Add((list) => list.Remove(2)); + actionList.Add((list) => NUnit.Framework.Assert.AreEqual(3, list.Size())); + ExecuteActions(actionList); + } + + [NUnit.Framework.Test] + public virtual void TestSameBehaviour11() { + IList>> actionList = new List>>(); + actionList.Add((list) => NUnit.Framework.Assert.IsTrue(list.IsEmpty())); + actionList.Add((list) => list.Add("1")); + actionList.Add((list) => NUnit.Framework.Assert.IsFalse(list.IsEmpty())); + actionList.Add((list) => list.Add("2")); + actionList.Add((list) => list.Add("3")); + actionList.Add((list) => list.Add("4")); + actionList.Add((list) => NUnit.Framework.Assert.IsFalse(list.IsEmpty())); + ExecuteActions(actionList); + } + + public virtual void ExecuteActions(IList>> actionList) { + NullUnlimitedList list = new NullUnlimitedList(); + SimpleArrayList list2 = new SimpleArrayList(); + foreach (Action> action in actionList) { + action(list); + action(list2); + } + } + } +} diff --git a/itext.tests/itext.commons.tests/itext/commons/datastructures/portable/SimpleArrayListTest.cs b/itext.tests/itext.commons.tests/itext/commons/datastructures/portable/SimpleArrayListTest.cs new file mode 100644 index 0000000000..db0ea98d7b --- /dev/null +++ b/itext.tests/itext.commons.tests/itext/commons/datastructures/portable/SimpleArrayListTest.cs @@ -0,0 +1,109 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Commons.Datastructures; +using iText.Test; + +namespace iText.Commons.Datastructures.Portable { + [NUnit.Framework.Category("UnitTest")] + public class SimpleArrayListTest : ExtendedITextTest { + [NUnit.Framework.Test] + public virtual void Add01() { + SimpleArrayList list = new SimpleArrayList(); + list.Add(1); + list.Add(2); + list.Add(3); + NUnit.Framework.Assert.AreEqual(3, list.Size()); + NUnit.Framework.Assert.AreEqual(1, list.Get(0)); + NUnit.Framework.Assert.AreEqual(2, list.Get(1)); + NUnit.Framework.Assert.AreEqual(3, list.Get(2)); + } + + [NUnit.Framework.Test] + public virtual void Add02() { + SimpleArrayList list = new SimpleArrayList(); + list.Add(1); + list.Add(3); + list.Add(2, 2); + NUnit.Framework.Assert.AreEqual(3, list.Size()); + } + + [NUnit.Framework.Test] + public virtual void Set01() { + SimpleArrayList list = new SimpleArrayList(); + list.Add(1); + list.Add(2); + list.Add(3); + NUnit.Framework.Assert.AreEqual(2, list.Set(1, 4)); + NUnit.Framework.Assert.AreEqual(4, list.Get(1)); + } + + [NUnit.Framework.Test] + public virtual void IndexOf01() { + SimpleArrayList list = new SimpleArrayList(); + list.Add(1); + list.Add(2); + list.Add(3); + NUnit.Framework.Assert.AreEqual(0, list.IndexOf(1)); + NUnit.Framework.Assert.AreEqual(1, list.IndexOf(2)); + NUnit.Framework.Assert.AreEqual(2, list.IndexOf(3)); + } + + [NUnit.Framework.Test] + public virtual void Remove() { + SimpleArrayList list = new SimpleArrayList(); + list.Add(1); + list.Add(2); + list.Add(3); + list.Remove(1); + NUnit.Framework.Assert.AreEqual(2, list.Size()); + NUnit.Framework.Assert.AreEqual(1, list.Get(0)); + NUnit.Framework.Assert.AreEqual(3, list.Get(1)); + } + + [NUnit.Framework.Test] + public virtual void Size() { + SimpleArrayList list = new SimpleArrayList(); + list.Add(1); + list.Add(2); + list.Add(3); + NUnit.Framework.Assert.AreEqual(3, list.Size()); + } + + [NUnit.Framework.Test] + public virtual void InitializeWithCapacity() { + SimpleArrayList list = new SimpleArrayList(20); + list.Add(1); + list.Add(2); + list.Add(3); + NUnit.Framework.Assert.AreEqual(3, list.Size()); + } + + [NUnit.Framework.Test] + public virtual void IsEmpty() { + SimpleArrayList list = new SimpleArrayList(); + NUnit.Framework.Assert.IsTrue(list.IsEmpty()); + list.Add(1); + NUnit.Framework.Assert.IsFalse(list.IsEmpty()); + } + } +} diff --git a/itext.tests/itext.commons.tests/itext/commons/utils/FileUtilTest.cs b/itext.tests/itext.commons.tests/itext/commons/utils/FileUtilTest.cs new file mode 100644 index 0000000000..c600d607e0 --- /dev/null +++ b/itext.tests/itext.commons.tests/itext/commons/utils/FileUtilTest.cs @@ -0,0 +1,63 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using System.IO; +using iText.Test; + +namespace iText.Commons.Utils { + [NUnit.Framework.Category("UnitTest")] + public class FileUtilTest : ExtendedITextTest { + public static readonly String DESTINATION_FOLDER = NUnit.Framework.TestContext.CurrentContext.TestDirectory + + "/test/itext/commons/utils/FileUtilTest/"; + + [NUnit.Framework.OneTimeSetUp] + public static void BeforeClass() { + CreateOrClearDestinationFolder(DESTINATION_FOLDER); + } + + [NUnit.Framework.Test] + public virtual void GetBufferedOutputStreamTest() { + String filePath = DESTINATION_FOLDER + "bufferedOutput.txt"; + String text = "Hello world!"; + using (Stream @out = FileUtil.GetBufferedOutputStream(filePath)) { + @out.Write(text.GetBytes(System.Text.Encoding.UTF8)); + } + byte[] resultBytes = File.ReadAllBytes(System.IO.Path.Combine(filePath)); + NUnit.Framework.Assert.AreEqual(text, iText.Commons.Utils.JavaUtil.GetStringForBytes(resultBytes, System.Text.Encoding + .UTF8)); + } + + [NUnit.Framework.Test] + public virtual void GetFileOutputStreamTest() { + String filePath = DESTINATION_FOLDER + "fileOutput.txt"; + FileInfo file = new FileInfo(filePath); + String text = "Hello world!"; + using (Stream @out = FileUtil.GetFileOutputStream(file)) { + @out.Write(text.GetBytes(System.Text.Encoding.UTF8)); + } + byte[] resultBytes = File.ReadAllBytes(System.IO.Path.Combine(filePath)); + NUnit.Framework.Assert.AreEqual(text, iText.Commons.Utils.JavaUtil.GetStringForBytes(resultBytes, System.Text.Encoding + .UTF8)); + } + } +} diff --git a/itext.tests/itext.commons.tests/itext/commons/utils/MessageFormatUtilTest.cs b/itext.tests/itext.commons.tests/itext/commons/utils/MessageFormatUtilTest.cs index 6768496370..ebc7adaeaa 100644 --- a/itext.tests/itext.commons.tests/itext/commons/utils/MessageFormatUtilTest.cs +++ b/itext.tests/itext.commons.tests/itext/commons/utils/MessageFormatUtilTest.cs @@ -22,29 +22,11 @@ You should have received a copy of the GNU Affero General Public License */ using System; using System.Collections.Generic; -using System.Linq; using iText.Test; namespace iText.Commons.Utils { [NUnit.Framework.Category("UnitTest")] - [NUnit.Framework.TestFixtureSource("DataSourceTestFixtureData")] public class MessageFormatUtilTest : ExtendedITextTest { - private String expectedResult; - - private String pattern; - - private Object[] arguments; - - public MessageFormatUtilTest(Object expectedResult, Object pattern, Object arguments, Object name) { - this.expectedResult = (String)expectedResult; - this.pattern = (String)pattern; - this.arguments = (Object[])arguments; - } - - public MessageFormatUtilTest(Object[] array) - : this(array[0], array[1], array[2], array[3]) { - } - public static IEnumerable DataSource() { return JavaUtil.ArraysAsList(new Object[][] { new Object[] { "Plain message with params 1 test", "Plain message with params {0} {1}" , new Object[] { 1, "test" }, "test with simple params" }, new Object[] { "Message with 'single quotes'" @@ -61,12 +43,8 @@ public static IEnumerable DataSource() { } }); } - public static ICollection DataSourceTestFixtureData() { - return DataSource().Select(array => new NUnit.Framework.TestFixtureData(array)).ToList(); - } - - [NUnit.Framework.Test] - public virtual void TestFormatting() { + [NUnit.Framework.TestCaseSource("DataSource")] + public virtual void TestFormatting(String expectedResult, String pattern, Object[] arguments, String name) { NUnit.Framework.Assert.AreEqual(expectedResult, MessageFormatUtil.Format(pattern, arguments)); } } diff --git a/itext.tests/itext.forms.tests/Properties/AssemblyInfo.cs b/itext.tests/itext.forms.tests/Properties/AssemblyInfo.cs index b1ba8e85de..1412e69da2 100644 --- a/itext.tests/itext.forms.tests/Properties/AssemblyInfo.cs +++ b/itext.tests/itext.forms.tests/Properties/AssemblyInfo.cs @@ -14,9 +14,9 @@ [assembly: Guid("6fe2f714-6b3e-4b20-8c70-28bfce084ed2")] -[assembly: AssemblyVersion("8.0.5.0")] -[assembly: AssemblyFileVersion("8.0.5.0")] -[assembly: AssemblyInformationalVersion("8.0.5")] +[assembly: AssemblyVersion("9.0.0.0")] +[assembly: AssemblyFileVersion("9.0.0.0")] +[assembly: AssemblyInformationalVersion("9.0.0")] #if !NETSTANDARD2_0 [assembly: NUnit.Framework.Timeout(300000)] diff --git a/itext.tests/itext.forms.tests/itext/forms/FlatteningRotatedTest.cs b/itext.tests/itext.forms.tests/itext/forms/FlatteningRotatedTest.cs index 6e6e3580e8..05af0aac18 100644 --- a/itext.tests/itext.forms.tests/itext/forms/FlatteningRotatedTest.cs +++ b/itext.tests/itext.forms.tests/itext/forms/FlatteningRotatedTest.cs @@ -22,7 +22,6 @@ You should have received a copy of the GNU Affero General Public License */ using System; using System.Collections.Generic; -using System.Linq; using iText.Forms.Fields; using iText.Kernel.Colors; using iText.Kernel.Pdf; @@ -31,7 +30,6 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Forms { [NUnit.Framework.Category("IntegrationTest")] - [NUnit.Framework.TestFixtureSource("InputFileNamesTestFixtureData")] public class FlatteningRotatedTest : ExtendedITextTest { public static readonly String sourceFolder = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext .CurrentContext.TestDirectory) + "/resources/itext/forms/FlatteningRotatedTest/"; @@ -39,8 +37,6 @@ public class FlatteningRotatedTest : ExtendedITextTest { public static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory + "/test/itext/forms/FlatteningRotatedTest/"; - private readonly String inputPdfFileName; - public static ICollection InputFileNames() { IList inputFileNames = new List(); for (int pageRot = 0; pageRot < 360; pageRot += 90) { @@ -51,25 +47,13 @@ public static ICollection InputFileNames() { return inputFileNames; } - public static ICollection InputFileNamesTestFixtureData() { - return InputFileNames().Select(array => new NUnit.Framework.TestFixtureData(array)).ToList(); - } - - public FlatteningRotatedTest(Object inputPdfFileName) { - this.inputPdfFileName = (String)inputPdfFileName; - } - - public FlatteningRotatedTest(Object[] array) - : this(array[0]) { - } - [NUnit.Framework.OneTimeSetUp] public static void BeforeClass() { CreateOrClearDestinationFolder(destinationFolder); } - [NUnit.Framework.Test] - public virtual void FormFlatteningTest_DefaultAppearanceGeneration_Rot() { + [NUnit.Framework.TestCaseSource("InputFileNames")] + public virtual void FormFlatteningTest_DefaultAppearanceGeneration_Rot(String inputPdfFileName) { String src = sourceFolder + inputPdfFileName + ".pdf"; String dest = destinationFolder + inputPdfFileName + ".pdf"; String dest_flattened = destinationFolder + inputPdfFileName + "_flattened.pdf"; diff --git a/itext.tests/itext.forms.tests/itext/forms/PdfAcroFormIntegrationTest.cs b/itext.tests/itext.forms.tests/itext/forms/PdfAcroFormIntegrationTest.cs index e999323972..65aa3452de 100644 --- a/itext.tests/itext.forms.tests/itext/forms/PdfAcroFormIntegrationTest.cs +++ b/itext.tests/itext.forms.tests/itext/forms/PdfAcroFormIntegrationTest.cs @@ -52,6 +52,20 @@ public virtual void OrphanedNamelessFormFieldTest() { } } + [NUnit.Framework.Test] + public virtual void FormWithSameFieldReferencesTest() { + String srcFileName = SOURCE_FOLDER + "formWithSameFieldReferences.pdf"; + String cmpFileName = SOURCE_FOLDER + "cmp_formWithSameFieldReferences.pdf"; + String outFileName = DESTINATION_FOLDER + "formWithSameFieldReferences.pdf"; + using (PdfDocument sourceDoc = new PdfDocument(new PdfReader(srcFileName), new PdfWriter(outFileName))) { + PdfAcroForm acroForm = PdfFormCreator.GetAcroForm(sourceDoc, true); + NUnit.Framework.Assert.AreEqual(1, acroForm.GetFields().Size()); + NUnit.Framework.Assert.IsNull(acroForm.GetField("Field").GetKids()); + } + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER + , "diff_")); + } + [NUnit.Framework.Test] public virtual void MergeMergedFieldsWithTheSameNamesTest() { String srcFileName = SOURCE_FOLDER + "fieldMergedWithWidget.pdf"; diff --git a/itext.tests/itext.forms.tests/itext/forms/PdfChoiceFieldTest.cs b/itext.tests/itext.forms.tests/itext/forms/PdfChoiceFieldTest.cs index 48503e8d32..364383b52e 100644 --- a/itext.tests/itext.forms.tests/itext/forms/PdfChoiceFieldTest.cs +++ b/itext.tests/itext.forms.tests/itext/forms/PdfChoiceFieldTest.cs @@ -56,27 +56,27 @@ public virtual void ChoiceFieldsWithUnicodeTest() { pdfDoc.AddNewPage(); // 规 PdfFormField field = new ChoiceFormFieldBuilder(pdfDoc, "combo1").SetWidgetRectangle(new Rectangle(36, 666 - , 40, 80)).SetOptions(new String[] { "\u89c4", "\u89c9" }).SetGenericConformanceLevel(null).CreateComboBox - ().SetValue("\u89c4"); + , 40, 80)).SetOptions(new String[] { "\u89c4", "\u89c9" }).SetConformance(null).CreateComboBox().SetValue + ("\u89c4"); field.SetFont(font); field.GetFirstFormAnnotation().SetBorderColor(ColorConstants.BLACK); form.AddField(field); // 觉 field = new ChoiceFormFieldBuilder(pdfDoc, "combo2").SetWidgetRectangle(new Rectangle(136, 666, 40, 80)).SetOptions - (new String[] { "\u89c4", "\u89c9" }).SetGenericConformanceLevel(null).CreateComboBox(); + (new String[] { "\u89c4", "\u89c9" }).SetConformance(null).CreateComboBox(); field.SetValue("\u89c4").SetFont(font); field.SetValue("\u89c9"); field.GetFirstFormAnnotation().SetBorderColor(ColorConstants.BLACK); form.AddField(field); // 规 field = new ChoiceFormFieldBuilder(pdfDoc, "list1").SetWidgetRectangle(new Rectangle(236, 666, 50, 80)).SetOptions - (new String[] { "\u89c4", "\u89c9" }).SetGenericConformanceLevel(null).CreateList().SetValue("\u89c4"); + (new String[] { "\u89c4", "\u89c9" }).SetConformance(null).CreateList().SetValue("\u89c4"); field.SetFont(font); field.GetFirstFormAnnotation().SetBorderColor(ColorConstants.BLACK); form.AddField(field); // 觉 field = new ChoiceFormFieldBuilder(pdfDoc, "list2").SetWidgetRectangle(new Rectangle(336, 666, 50, 80)).SetOptions - (new String[] { "\u89c4", "\u89c9" }).SetGenericConformanceLevel(null).CreateList(); + (new String[] { "\u89c4", "\u89c9" }).SetConformance(null).CreateList(); field.SetValue("\u89c4").SetFont(font); field.SetValue("\u89c9"); field.GetFirstFormAnnotation().SetBorderColor(ColorConstants.BLACK); @@ -146,7 +146,7 @@ public virtual void MultiSelectByValueTest() { document.AddNewPage(); PdfAcroForm form = PdfFormCreator.GetAcroForm(document, true); PdfChoiceFormField choice = (PdfChoiceFormField)new ChoiceFormFieldBuilder(document, "choice").SetWidgetRectangle - (new Rectangle(336, 666, 50, 80)).SetOptions(new String[] { "one", "two", "three", "four" }).SetGenericConformanceLevel + (new Rectangle(336, 666, 50, 80)).SetOptions(new String[] { "one", "two", "three", "four" }).SetConformance (null).CreateList().SetValue("two").SetFont(null); choice.GetFirstFormAnnotation().SetBorderColor(ColorConstants.BLACK); choice.SetMultiSelect(true); diff --git a/itext.tests/itext.forms.tests/itext/forms/PdfFormFieldTest.cs b/itext.tests/itext.forms.tests/itext/forms/PdfFormFieldTest.cs index b570abe7dd..d297f34141 100644 --- a/itext.tests/itext.forms.tests/itext/forms/PdfFormFieldTest.cs +++ b/itext.tests/itext.forms.tests/itext/forms/PdfFormFieldTest.cs @@ -38,7 +38,6 @@ You should have received a copy of the GNU Affero General Public License using iText.Kernel.Utils; using iText.Layout; using iText.Layout.Element; -using iText.Layout.Logs; using iText.Layout.Properties; using iText.Test; using iText.Test.Attributes; @@ -978,10 +977,13 @@ public virtual void PdfWithDifferentFieldsTest() { // list PdfChoiceFormField f = new ChoiceFormFieldBuilder(pdfDoc, "combo").SetWidgetRectangle(new Rectangle(36, 556 , 50, 100)).SetOptions(new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }).CreateList(); + f.DisableFieldRegeneration(); f.SetValue("9", true); f.SetValue("4"); f.SetTopIndex(2); f.SetListSelected(new String[] { "3", "5" }); + f.SetMultiSelect(true); + f.EnableFieldRegeneration(); form.AddField(f); // push button form.AddField(new PushButtonFormFieldBuilder(pdfDoc, "push button").SetWidgetRectangle(new Rectangle(36, 526 @@ -1139,7 +1141,6 @@ public virtual void SetFont2Ways() { [NUnit.Framework.Test] // Acrobat removes /NeedAppearances flag when document is opened and suggests to resave the document at once. - [LogMessage(LayoutLogMessageConstant.ELEMENT_DOES_NOT_FIT_AREA)] [LogMessage(FormsLogMessageConstants.INPUT_FIELD_DOES_NOT_FIT)] public virtual void AppendModeAppearance() { String inputFile = "appendModeAppearance.pdf"; diff --git a/itext.tests/itext.forms.tests/itext/forms/fields/CheckBoxFormFieldBuilderTest.cs b/itext.tests/itext.forms.tests/itext/forms/fields/CheckBoxFormFieldBuilderTest.cs index 866e800a67..83ed6992b7 100644 --- a/itext.tests/itext.forms.tests/itext/forms/fields/CheckBoxFormFieldBuilderTest.cs +++ b/itext.tests/itext.forms.tests/itext/forms/fields/CheckBoxFormFieldBuilderTest.cs @@ -70,7 +70,7 @@ public virtual void CreateCheckBoxWithoutWidgetTest() { [NUnit.Framework.Test] public virtual void CreateCheckBoxWithConformanceLevelTest() { PdfButtonFormField checkBoxFormField = new CheckBoxFormFieldBuilder(DUMMY_DOCUMENT, DUMMY_NAME).SetWidgetRectangle - (DUMMY_RECTANGLE).SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_1A).CreateCheckBox(); + (DUMMY_RECTANGLE).SetConformance(PdfConformance.PDF_A_1A).CreateCheckBox(); CompareCheckBoxes(checkBoxFormField, true); } diff --git a/itext.tests/itext.forms.tests/itext/forms/fields/ChoiceFormFieldBuilderTest.cs b/itext.tests/itext.forms.tests/itext/forms/fields/ChoiceFormFieldBuilderTest.cs index 48545d6313..6a34255c23 100644 --- a/itext.tests/itext.forms.tests/itext/forms/fields/ChoiceFormFieldBuilderTest.cs +++ b/itext.tests/itext.forms.tests/itext/forms/fields/ChoiceFormFieldBuilderTest.cs @@ -110,7 +110,7 @@ public virtual void CreateComboBoxWithoutWidgetTest() { [NUnit.Framework.Test] public virtual void CreateComboBoxWithConformanceLevelTest() { PdfChoiceFormField choiceFormField = new ChoiceFormFieldBuilder(DUMMY_DOCUMENT, DUMMY_NAME).SetWidgetRectangle - (DUMMY_RECTANGLE).SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_1A).CreateComboBox(); + (DUMMY_RECTANGLE).SetConformance(PdfConformance.PDF_A_1A).CreateComboBox(); CompareChoices(new PdfDictionary(), choiceFormField, true); } @@ -150,7 +150,7 @@ public virtual void CreateListWithoutWidgetTest() { [NUnit.Framework.Test] public virtual void CreateListWithConformanceLevelTest() { PdfChoiceFormField choiceFormField = new ChoiceFormFieldBuilder(DUMMY_DOCUMENT, DUMMY_NAME).SetWidgetRectangle - (DUMMY_RECTANGLE).SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_1A).CreateList(); + (DUMMY_RECTANGLE).SetConformance(PdfConformance.PDF_A_1A).CreateList(); PdfDictionary expectedDictionary = new PdfDictionary(); expectedDictionary.Put(PdfName.Ff, new PdfNumber(0)); CompareChoices(expectedDictionary, choiceFormField, true); diff --git a/itext.tests/itext.forms.tests/itext/forms/fields/FieldsRotationTest.cs b/itext.tests/itext.forms.tests/itext/forms/fields/FieldsRotationTest.cs index 2eb042634a..c3f2863c73 100644 --- a/itext.tests/itext.forms.tests/itext/forms/fields/FieldsRotationTest.cs +++ b/itext.tests/itext.forms.tests/itext/forms/fields/FieldsRotationTest.cs @@ -22,7 +22,6 @@ You should have received a copy of the GNU Affero General Public License */ using System; using System.Collections.Generic; -using System.Linq; using iText.Commons.Utils; using iText.Forms; using iText.Forms.Form.Element; @@ -35,7 +34,6 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Forms.Fields { [NUnit.Framework.Category("IntegrationTest")] - [NUnit.Framework.TestFixtureSource("RotationRelatedPropertiesTestFixtureData")] public class FieldsRotationTest : ExtendedITextTest { public static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext .CurrentContext.TestDirectory) + "/resources/itext/forms/fields/FieldsRotationTest/"; @@ -43,31 +41,11 @@ public class FieldsRotationTest : ExtendedITextTest { public static readonly String DESTINATION_FOLDER = NUnit.Framework.TestContext.CurrentContext.TestDirectory + "/test/itext/forms/fields/FieldsRotationTest/"; - private readonly int[] pageRotation; - - private readonly int[] fieldRotation; - - private readonly bool ignorePageRotation; - - private readonly String testName; - [NUnit.Framework.OneTimeSetUp] public static void BeforeClass() { CreateDestinationFolder(DESTINATION_FOLDER); } - public FieldsRotationTest(Object pageRotation, Object fieldRotation, Object ignorePageRotation, Object testName - ) { - this.pageRotation = (int[])pageRotation; - this.fieldRotation = (int[])fieldRotation; - this.ignorePageRotation = (bool)ignorePageRotation; - this.testName = (String)testName; - } - - public FieldsRotationTest(Object[] array) - : this(array[0], array[1], array[2], array[3]) { - } - public static IEnumerable RotationRelatedProperties() { return JavaUtil.ArraysAsList(new Object[][] { new Object[] { new int[] { 360, 90, 180, 270 }, new int[] { 0, 0, 0, 0 }, true, "fieldsOnRotatedPagesDefault" }, new Object[] { new int[] { 360, 90, 180, 270 }, new @@ -80,20 +58,17 @@ public static IEnumerable RotationRelatedProperties() { } }); } - public static ICollection RotationRelatedPropertiesTestFixtureData() { - return RotationRelatedProperties().Select(array => new NUnit.Framework.TestFixtureData(array)).ToList(); - } - - [NUnit.Framework.Test] - public virtual void FieldRotationTest() { + [NUnit.Framework.TestCaseSource("RotationRelatedProperties")] + public virtual void FieldRotationTest(int[] pageRotation, int[] fieldRotation, bool ignorePageRotation, String + testName) { String outFileName = DESTINATION_FOLDER + testName + ".pdf"; String cmpFileName = SOURCE_FOLDER + "cmp_" + testName + ".pdf"; - FillForm(outFileName); + FillForm(pageRotation, fieldRotation, ignorePageRotation, outFileName); NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } - private void FillForm(String outPdf) { + private void FillForm(int[] pageRotation, int[] fieldRotation, bool ignorePageRotation, String outPdf) { using (Document document = new Document(new PdfDocument(new PdfWriter(outPdf)))) { PdfAcroForm form = PdfFormCreator.GetAcroForm(document.GetPdfDocument(), true); for (int i = 1; i < 5; ++i) { diff --git a/itext.tests/itext.forms.tests/itext/forms/fields/FormFieldBuilderTest.cs b/itext.tests/itext.forms.tests/itext/forms/fields/FormFieldBuilderTest.cs index 1d812424c9..8802b8d47b 100644 --- a/itext.tests/itext.forms.tests/itext/forms/fields/FormFieldBuilderTest.cs +++ b/itext.tests/itext.forms.tests/itext/forms/fields/FormFieldBuilderTest.cs @@ -44,24 +44,16 @@ public virtual void ConstructorTest() { public virtual void GetSetConformanceLevelTest() { FormFieldBuilderTest.TestBuilder builder = new FormFieldBuilderTest.TestBuilder(DUMMY_DOCUMENT, DUMMY_NAME ); - builder.SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_1A); - NUnit.Framework.Assert.AreSame(PdfAConformanceLevel.PDF_A_1A, builder.GetGenericConformanceLevel()); + builder.SetConformance(PdfConformance.PDF_A_1A); + NUnit.Framework.Assert.AreSame(PdfAConformance.PDF_A_1A, builder.GetConformance().GetAConformance()); } [NUnit.Framework.Test] - public virtual void GetSetConformanceLevelDepreceatedTest() { + public virtual void GetSetConformanceLevelPdfUATest() { FormFieldBuilderTest.TestBuilder builder = new FormFieldBuilderTest.TestBuilder(DUMMY_DOCUMENT, DUMMY_NAME ); - builder.SetConformanceLevel(PdfAConformanceLevel.PDF_A_1A); - NUnit.Framework.Assert.AreSame(PdfAConformanceLevel.PDF_A_1A, builder.GetConformanceLevel()); - } - - [NUnit.Framework.Test] - public virtual void GetSetConformanceLevelDifferentTest() { - FormFieldBuilderTest.TestBuilder builder = new FormFieldBuilderTest.TestBuilder(DUMMY_DOCUMENT, DUMMY_NAME - ); - builder.SetGenericConformanceLevel(PdfUAConformanceLevel.PDFUA_1); - NUnit.Framework.Assert.IsNull(builder.GetConformanceLevel()); + builder.SetConformance(PdfConformance.PDF_UA_1); + NUnit.Framework.Assert.AreSame(PdfUAConformance.PDF_UA_1, builder.GetConformance().GetUAConformance()); } private class TestBuilder : FormFieldBuilder { diff --git a/itext.tests/itext.forms.tests/itext/forms/fields/FormsMetaInfoStaticContainerTest.cs b/itext.tests/itext.forms.tests/itext/forms/fields/FormsMetaInfoStaticContainerTest.cs index df9d926c5b..acb2170551 100644 --- a/itext.tests/itext.forms.tests/itext/forms/fields/FormsMetaInfoStaticContainerTest.cs +++ b/itext.tests/itext.forms.tests/itext/forms/fields/FormsMetaInfoStaticContainerTest.cs @@ -31,8 +31,8 @@ namespace iText.Forms.Fields { public class FormsMetaInfoStaticContainerTest : ExtendedITextTest { [NUnit.Framework.Test] public virtual void UseMetaInfoDuringTheActionOneThreadTest() { - MetaInfoContainer metaInfo1 = new MetaInfoContainer(new _IMetaInfo_38()); - MetaInfoContainer metaInfo2 = new MetaInfoContainer(new _IMetaInfo_39()); + MetaInfoContainer metaInfo1 = new MetaInfoContainer(new _IMetaInfo_37()); + MetaInfoContainer metaInfo2 = new MetaInfoContainer(new _IMetaInfo_38()); FormsMetaInfoStaticContainer.UseMetaInfoDuringTheAction(metaInfo1, () => { NUnit.Framework.Assert.AreSame(metaInfo1, FormsMetaInfoStaticContainer.GetMetaInfoForLayout()); FormsMetaInfoStaticContainer.UseMetaInfoDuringTheAction(metaInfo2, () => NUnit.Framework.Assert.AreSame(metaInfo2 @@ -43,13 +43,13 @@ public virtual void UseMetaInfoDuringTheActionOneThreadTest() { NUnit.Framework.Assert.IsNull(FormsMetaInfoStaticContainer.GetMetaInfoForLayout()); } - private sealed class _IMetaInfo_38 : IMetaInfo { - public _IMetaInfo_38() { + private sealed class _IMetaInfo_37 : IMetaInfo { + public _IMetaInfo_37() { } } - private sealed class _IMetaInfo_39 : IMetaInfo { - public _IMetaInfo_39() { + private sealed class _IMetaInfo_38 : IMetaInfo { + public _IMetaInfo_38() { } } @@ -79,7 +79,7 @@ public MetaInfoCheckClass(FormsMetaInfoStaticContainerTest.MetaInfoCheckClass me } public virtual void CheckMetaInfo() { - MetaInfoContainer metaInfo = new MetaInfoContainer(new _IMetaInfo_78()); + MetaInfoContainer metaInfo = new MetaInfoContainer(new _IMetaInfo_77()); FormsMetaInfoStaticContainer.UseMetaInfoDuringTheAction(metaInfo, () => { if (metaInfoCheckClass != null) { Thread thread = new Thread(() => metaInfoCheckClass.CheckMetaInfo()); @@ -97,8 +97,8 @@ public virtual void CheckMetaInfo() { checkFailed |= FormsMetaInfoStaticContainer.GetMetaInfoForLayout() != null; } - private sealed class _IMetaInfo_78 : IMetaInfo { - public _IMetaInfo_78() { + private sealed class _IMetaInfo_77 : IMetaInfo { + public _IMetaInfo_77() { } } diff --git a/itext.tests/itext.forms.tests/itext/forms/fields/PdfFormCreatorTest.cs b/itext.tests/itext.forms.tests/itext/forms/fields/PdfFormCreatorTest.cs index e3f4b1f087..2474d61746 100644 --- a/itext.tests/itext.forms.tests/itext/forms/fields/PdfFormCreatorTest.cs +++ b/itext.tests/itext.forms.tests/itext/forms/fields/PdfFormCreatorTest.cs @@ -33,7 +33,7 @@ namespace iText.Forms.Fields { public class PdfFormCreatorTest : ExtendedITextTest { [NUnit.Framework.Test] public virtual void GetAcroFormTest() { - PdfFormFactory customFactory = new _PdfFormFactory_43(); + PdfFormFactory customFactory = new _PdfFormFactory_42(); // Never create new acroform. PdfFormCreator.SetFactory(customFactory); try { @@ -47,8 +47,8 @@ public virtual void GetAcroFormTest() { } } - private sealed class _PdfFormFactory_43 : PdfFormFactory { - public _PdfFormFactory_43() { + private sealed class _PdfFormFactory_42 : PdfFormFactory { + public _PdfFormFactory_42() { } public override PdfAcroForm GetAcroForm(PdfDocument document, bool createIfNotExist) { @@ -58,7 +58,7 @@ public override PdfAcroForm GetAcroForm(PdfDocument document, bool createIfNotEx [NUnit.Framework.Test] public virtual void CreateTextFormFieldTest() { - PdfFormFactory customFactory = new _PdfFormFactory_63(); + PdfFormFactory customFactory = new _PdfFormFactory_62(); // All text is read by default. PdfFormCreator.SetFactory(customFactory); try { @@ -73,8 +73,8 @@ public virtual void CreateTextFormFieldTest() { } } - private sealed class _PdfFormFactory_63 : PdfFormFactory { - public _PdfFormFactory_63() { + private sealed class _PdfFormFactory_62 : PdfFormFactory { + public _PdfFormFactory_62() { } public override PdfTextFormField CreateTextFormField(PdfWidgetAnnotation widgetAnnotation, PdfDocument document diff --git a/itext.tests/itext.forms.tests/itext/forms/fields/PdfFormFieldUnitTest.cs b/itext.tests/itext.forms.tests/itext/forms/fields/PdfFormFieldUnitTest.cs index 6a3eeb06b7..dddc2f8804 100644 --- a/itext.tests/itext.forms.tests/itext/forms/fields/PdfFormFieldUnitTest.cs +++ b/itext.tests/itext.forms.tests/itext/forms/fields/PdfFormFieldUnitTest.cs @@ -43,15 +43,15 @@ public virtual void CannotGetRectangleIfKidsIsNullTest() { [NUnit.Framework.Test] public virtual void SetMetaInfoToCanvasMetaInfoUsedTest() { Canvas canvas = CreateCanvas(); - MetaInfoContainer metaInfoContainer = new MetaInfoContainer(new _IMetaInfo_56()); + MetaInfoContainer metaInfoContainer = new MetaInfoContainer(new _IMetaInfo_55()); FormsMetaInfoStaticContainer.UseMetaInfoDuringTheAction(metaInfoContainer, () => PdfFormAnnotation.SetMetaInfoToCanvas (canvas)); NUnit.Framework.Assert.AreSame(metaInfoContainer, canvas.GetProperty(Property.META_INFO )); } - private sealed class _IMetaInfo_56 : IMetaInfo { - public _IMetaInfo_56() { + private sealed class _IMetaInfo_55 : IMetaInfo { + public _IMetaInfo_55() { } } diff --git a/itext.tests/itext.forms.tests/itext/forms/fields/PushButtonFormFieldBuilderTest.cs b/itext.tests/itext.forms.tests/itext/forms/fields/PushButtonFormFieldBuilderTest.cs index 35ae7f70e2..547338a8e6 100644 --- a/itext.tests/itext.forms.tests/itext/forms/fields/PushButtonFormFieldBuilderTest.cs +++ b/itext.tests/itext.forms.tests/itext/forms/fields/PushButtonFormFieldBuilderTest.cs @@ -69,7 +69,7 @@ public virtual void CreatePushButtonWithoutWidgetTest() { [NUnit.Framework.Test] public virtual void CreatePushButtonWithConformanceLevelTest() { PdfButtonFormField pushButtonFormField = new PushButtonFormFieldBuilder(DUMMY_DOCUMENT, DUMMY_NAME).SetWidgetRectangle - (DUMMY_RECTANGLE).SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_1A).CreatePushButton(); + (DUMMY_RECTANGLE).SetConformance(PdfConformance.PDF_A_1A).CreatePushButton(); ComparePushButtons(pushButtonFormField, true); } diff --git a/itext.tests/itext.forms.tests/itext/forms/fields/RadioFormFieldBuilderTest.cs b/itext.tests/itext.forms.tests/itext/forms/fields/RadioFormFieldBuilderTest.cs index 79ae6ba082..1fa7e95018 100644 --- a/itext.tests/itext.forms.tests/itext/forms/fields/RadioFormFieldBuilderTest.cs +++ b/itext.tests/itext.forms.tests/itext/forms/fields/RadioFormFieldBuilderTest.cs @@ -149,8 +149,8 @@ public virtual void CreateRadioButtonWithoutWidgetThrowsExceptionTest() { public virtual void CreateRadioButtonWithConformanceLevelTest() { RadioFormFieldBuilder builder = new RadioFormFieldBuilder(DUMMY_DOCUMENT, DUMMY_NAME); PdfButtonFormField radioGroup = builder.CreateRadioGroup(); - PdfFormAnnotation radioAnnotation = builder.SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_1A).CreateRadioButton - (DUMMY_APPEARANCE_NAME, DUMMY_RECTANGLE); + PdfFormAnnotation radioAnnotation = builder.SetConformance(PdfConformance.PDF_A_1A).CreateRadioButton(DUMMY_APPEARANCE_NAME + , DUMMY_RECTANGLE); CompareRadioButtons(radioAnnotation, radioGroup, false); } @@ -158,8 +158,8 @@ public virtual void CreateRadioButtonWithConformanceLevelTest() { public virtual void CreateRadioButtonWithConformanceLevelAddedToGroupTest() { RadioFormFieldBuilder builder = new RadioFormFieldBuilder(DUMMY_DOCUMENT, DUMMY_NAME); PdfButtonFormField radioGroup = builder.CreateRadioGroup(); - PdfFormAnnotation radioAnnotation = builder.SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_1A).CreateRadioButton - (DUMMY_APPEARANCE_NAME, DUMMY_RECTANGLE); + PdfFormAnnotation radioAnnotation = builder.SetConformance(PdfConformance.PDF_A_1A).CreateRadioButton(DUMMY_APPEARANCE_NAME + , DUMMY_RECTANGLE); radioGroup.AddKid(radioAnnotation); CompareRadioButtons(radioAnnotation, radioGroup, true); } @@ -235,7 +235,7 @@ private static void CompareRadioButtons(PdfFormAnnotation radioButtonFormField, )); } } - if (radioButtonFormField.pdfConformanceLevel != null) { + if (radioButtonFormField.pdfConformance != null && radioButtonFormField.pdfConformance.IsPdfAOrUa()) { PutIfAbsent(expectedDictionary, PdfName.F, new PdfNumber(PdfAnnotation.PRINT)); } // for the AS key if it's added to the group we expect it to be off or the value if the radiogroup was selected diff --git a/itext.tests/itext.forms.tests/itext/forms/fields/SignatureFormFieldBuilderTest.cs b/itext.tests/itext.forms.tests/itext/forms/fields/SignatureFormFieldBuilderTest.cs index eaa6e2e1c9..a0fb0b6f52 100644 --- a/itext.tests/itext.forms.tests/itext/forms/fields/SignatureFormFieldBuilderTest.cs +++ b/itext.tests/itext.forms.tests/itext/forms/fields/SignatureFormFieldBuilderTest.cs @@ -62,7 +62,7 @@ public virtual void CreateSignatureWithoutWidgetTest() { [NUnit.Framework.Test] public virtual void CreateSignatureWithConformanceLevelTest() { PdfSignatureFormField signatureFormField = new SignatureFormFieldBuilder(DUMMY_DOCUMENT, DUMMY_NAME).SetWidgetRectangle - (DUMMY_RECTANGLE).SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_1A).CreateSignature(); + (DUMMY_RECTANGLE).SetConformance(PdfConformance.PDF_A_1A).CreateSignature(); CompareSignatures(signatureFormField, true); } diff --git a/itext.tests/itext.forms.tests/itext/forms/fields/TerminalFormFieldBuilderTest.cs b/itext.tests/itext.forms.tests/itext/forms/fields/TerminalFormFieldBuilderTest.cs index 240924a2a3..473b3332fb 100644 --- a/itext.tests/itext.forms.tests/itext/forms/fields/TerminalFormFieldBuilderTest.cs +++ b/itext.tests/itext.forms.tests/itext/forms/fields/TerminalFormFieldBuilderTest.cs @@ -67,14 +67,14 @@ public virtual void SetPageToFieldTest() { TerminalFormFieldBuilderTest.TestBuilder builder = new TerminalFormFieldBuilderTest.TestBuilder(DUMMY_DOCUMENT , DUMMY_NAME); builder.SetPage(5); - PdfFormAnnotation formFieldAnnot = new _PdfFormAnnotation_79((PdfDictionary)new PdfDictionary().MakeIndirect + PdfFormAnnotation formFieldAnnot = new _PdfFormAnnotation_77((PdfDictionary)new PdfDictionary().MakeIndirect (DUMMY_DOCUMENT)); PdfFormField formField = PdfFormCreator.CreateFormField(DUMMY_DOCUMENT).AddKid(formFieldAnnot); builder.SetPageToField(formField); } - private sealed class _PdfFormAnnotation_79 : PdfFormAnnotation { - public _PdfFormAnnotation_79(PdfDictionary baseArg1) + private sealed class _PdfFormAnnotation_77 : PdfFormAnnotation { + public _PdfFormAnnotation_77(PdfDictionary baseArg1) : base(baseArg1) { } diff --git a/itext.tests/itext.forms.tests/itext/forms/fields/TextFormFieldBuilderTest.cs b/itext.tests/itext.forms.tests/itext/forms/fields/TextFormFieldBuilderTest.cs index a08c61d08a..ff9655fa67 100644 --- a/itext.tests/itext.forms.tests/itext/forms/fields/TextFormFieldBuilderTest.cs +++ b/itext.tests/itext.forms.tests/itext/forms/fields/TextFormFieldBuilderTest.cs @@ -65,7 +65,7 @@ public virtual void CreateTextWithoutWidgetTest() { [NUnit.Framework.Test] public virtual void CreateTextWithConformanceLevelTest() { PdfTextFormField textFormField = new TextFormFieldBuilder(DUMMY_DOCUMENT, DUMMY_NAME).SetWidgetRectangle(DUMMY_RECTANGLE - ).SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_1A).CreateText(); + ).SetConformance(PdfConformance.PDF_A_1A).CreateText(); PdfDictionary expectedDictionary = new PdfDictionary(); expectedDictionary.Put(PdfName.Ff, new PdfNumber(0)); CompareTexts(expectedDictionary, textFormField, true); @@ -92,7 +92,7 @@ public virtual void CreateMultilineTextWithoutWidgetTest() { [NUnit.Framework.Test] public virtual void CreateMultilineTextWithConformanceLevelTest() { PdfTextFormField textFormField = new TextFormFieldBuilder(DUMMY_DOCUMENT, DUMMY_NAME).SetWidgetRectangle(DUMMY_RECTANGLE - ).SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_1A).CreateMultilineText(); + ).SetConformance(PdfConformance.PDF_A_1A).CreateMultilineText(); PdfDictionary expectedDictionary = new PdfDictionary(); expectedDictionary.Put(PdfName.Ff, new PdfNumber(PdfTextFormField.FF_MULTILINE)); CompareTexts(expectedDictionary, textFormField, true); diff --git a/itext.tests/itext.forms.tests/itext/forms/fields/merging/OnDuplicateFormFieldNameStrategyTest.cs b/itext.tests/itext.forms.tests/itext/forms/fields/merging/OnDuplicateFormFieldNameStrategyTest.cs index 4d265ea122..dfbe17ab8c 100644 --- a/itext.tests/itext.forms.tests/itext/forms/fields/merging/OnDuplicateFormFieldNameStrategyTest.cs +++ b/itext.tests/itext.forms.tests/itext/forms/fields/merging/OnDuplicateFormFieldNameStrategyTest.cs @@ -226,7 +226,7 @@ public virtual void FlattenReadOnlyAddIndexTo() { [NUnit.Framework.Test] public virtual void AddIndexStrategySeparatesTheFields() { try { - PdfFormCreator.SetFactory(new _PdfFormFactory_269()); + PdfFormCreator.SetFactory(new _PdfFormFactory_268()); using (PdfDocument pdfInnerDoc = new PdfDocument(new PdfWriter(DESTINATION_FOLDER + "add_index.pdf"))) { Document doc = new Document(pdfInnerDoc); doc.Add(new CheckBox("test1").SetBorder(new SolidBorder(ColorConstants.RED, 1))); @@ -242,8 +242,8 @@ public virtual void AddIndexStrategySeparatesTheFields() { } } - private sealed class _PdfFormFactory_269 : PdfFormFactory { - public _PdfFormFactory_269() { + private sealed class _PdfFormFactory_268 : PdfFormFactory { + public _PdfFormFactory_268() { } public override PdfAcroForm GetAcroForm(PdfDocument document, bool createIfNotExist) { diff --git a/itext.tests/itext.forms.tests/itext/forms/form/element/AccessibleElementTest.cs b/itext.tests/itext.forms.tests/itext/forms/form/element/AccessibleElementTest.cs index c78c16240d..a089c76462 100644 --- a/itext.tests/itext.forms.tests/itext/forms/form/element/AccessibleElementTest.cs +++ b/itext.tests/itext.forms.tests/itext/forms/form/element/AccessibleElementTest.cs @@ -22,8 +22,6 @@ You should have received a copy of the GNU Affero General Public License */ using System; using System.Collections.Generic; -using System.Linq; -using iText.Forms.Form; using iText.IO.Source; using iText.Kernel.Pdf; using iText.Kernel.Pdf.Tagging; @@ -34,18 +32,7 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Forms.Form.Element { [NUnit.Framework.Category("IntegrationTest")] - [NUnit.Framework.TestFixtureSource("GetDataTestFixtureDataTestFixtureData")] public class AccessibleElementTest : ExtendedITextTest { - private readonly AccessibleElementTest.TestContainer testContainer; - - public AccessibleElementTest(AccessibleElementTest.TestContainer index) { - this.testContainer = index; - } - - public AccessibleElementTest(AccessibleElementTest.TestContainer[] array) - : this(array[0]) { - } - public static ICollection GetDataTestFixtureData() { int amountOfEntries = 8; IList data = new List(); @@ -55,10 +42,6 @@ public static ICollection GetDataTestFixtureData() { return data; } - public static ICollection GetDataTestFixtureDataTestFixtureData() { - return GetDataTestFixtureData().Select(array => new NUnit.Framework.TestFixtureData(array)).ToList(); - } - private Func GetDataToTest(int index) { switch (index) { case 0: { @@ -105,8 +88,8 @@ private Func GetDataToTest(int index) { } } - [NUnit.Framework.Test] - public virtual void TestInteractive() { + [NUnit.Framework.TestCaseSource("GetDataTestFixtureData")] + public virtual void TestInteractive(AccessibleElementTest.TestContainer testContainer) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfDocument pdfDocument = new PdfDocument(new PdfWriter(baos)); pdfDocument.SetTagged(); @@ -128,8 +111,8 @@ public virtual void TestInteractive() { pdfDocument.Close(); } - [NUnit.Framework.Test] - public virtual void TestNonInteractive() { + [NUnit.Framework.TestCaseSource("GetDataTestFixtureData")] + public virtual void TestNonInteractive(AccessibleElementTest.TestContainer testContainer) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfDocument pdfDocument = new PdfDocument(new PdfWriter(baos)); pdfDocument.SetTagged(); @@ -150,16 +133,17 @@ public virtual void TestNonInteractive() { pdfDocument.Close(); } - [NUnit.Framework.Test] - public virtual void TestInteractiveProperty() { + [NUnit.Framework.TestCaseSource("GetDataTestFixtureData")] + public virtual void TestInteractiveProperty(AccessibleElementTest.TestContainer testContainer) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfDocument pdfDocument = new PdfDocument(new PdfWriter(baos)); pdfDocument.SetTagged(); Document document = new Document(pdfDocument); IFormField element = GetDataToTest(testContainer.index)(); - element.SetProperty(FormProperty.FORM_ACCESSIBILITY_LANGUAGE, "en"); IFormField formField = (IFormField)element; formField.SetInteractive(true); + IAccessibleElement accessibleElement = (IAccessibleElement)formField; + accessibleElement.GetAccessibilityProperties().SetLanguage("en"); document.Add((IBlockElement)element); PdfStructTreeRoot root = pdfDocument.GetStructTreeRoot(); IStructureNode documentStruct = root.GetKids()[0]; diff --git a/itext.tests/itext.forms.tests/itext/forms/form/element/CheckBoxTest.cs b/itext.tests/itext.forms.tests/itext/forms/form/element/CheckBoxTest.cs index a50ce4c684..1b302c7fc6 100644 --- a/itext.tests/itext.forms.tests/itext/forms/form/element/CheckBoxTest.cs +++ b/itext.tests/itext.forms.tests/itext/forms/form/element/CheckBoxTest.cs @@ -113,7 +113,7 @@ public virtual void CreateCheckBoxFactoryDefaultPdfTest() { [NUnit.Framework.Test] public virtual void CreateCheckBoxFactoryPdfATest() { CheckBox checkBox = new CheckBox("test"); - checkBox.SetPdfAConformanceLevel(PdfAConformanceLevel.PDF_A_1B); + checkBox.SetPdfConformance(PdfConformance.PDF_A_1B); CheckBoxRenderer renderer = (CheckBoxRenderer)checkBox.GetRenderer(); ICheckBoxRenderingStrategy strategy = renderer.CreateCheckBoxRenderStrategy(); NUnit.Framework.Assert.IsTrue(strategy is PdfACheckBoxRenderingStrategy); @@ -132,25 +132,12 @@ public virtual void CreateCheckBoxFactoryHtmlTest() { public virtual void CreateCheckBoxFactoryHtmlWithPdfATest() { CheckBox checkBox = new CheckBox("test"); checkBox.SetProperty(Property.RENDERING_MODE, RenderingMode.HTML_MODE); - checkBox.SetPdfAConformanceLevel(PdfAConformanceLevel.PDF_A_1B); + checkBox.SetPdfConformance(PdfConformance.PDF_A_1B); CheckBoxRenderer renderer = (CheckBoxRenderer)checkBox.GetRenderer(); ICheckBoxRenderingStrategy strategy = renderer.CreateCheckBoxRenderStrategy(); NUnit.Framework.Assert.IsTrue(strategy is HtmlCheckBoxRenderingStrategy); } - [NUnit.Framework.Test] - public virtual void IsPdfATest() { - CheckBox checkBox = new CheckBox("test"); - CheckBoxRenderer rendererPdf2 = (CheckBoxRenderer)checkBox.GetRenderer(); - NUnit.Framework.Assert.IsFalse(rendererPdf2.IsPdfA()); - checkBox.SetPdfAConformanceLevel(PdfAConformanceLevel.PDF_A_1B); - CheckBoxRenderer rendererPdf = (CheckBoxRenderer)checkBox.GetRenderer(); - NUnit.Framework.Assert.IsTrue(rendererPdf.IsPdfA()); - checkBox.SetPdfAConformanceLevel(null); - CheckBoxRenderer rendererPdf1 = (CheckBoxRenderer)checkBox.GetRenderer(); - NUnit.Framework.Assert.IsFalse(rendererPdf1.IsPdfA()); - } - [NUnit.Framework.Test] public virtual void CheckBoxInHtmlModeKeeps1on1RatioAndTakesMaxValue() { CheckBox checkBox = new CheckBox("test"); @@ -228,17 +215,15 @@ public virtual void BasicCheckBoxDrawingTestPdfAMode() { String cmpPdf = SOURCE_FOLDER + "cmp_basicCheckBoxPdfA.pdf"; using (Document document = new Document(new PdfDocument(new PdfWriter(outPdf)))) { //should be invisble because there is no default border - CheckBox checkBoxUnset = new CheckBox("test").SetPdfAConformanceLevel(PdfAConformanceLevel.PDF_A_1B); + CheckBox checkBoxUnset = new CheckBox("test").SetPdfConformance(PdfConformance.PDF_A_1B); document.Add(checkBoxUnset); - CheckBox checkBoxset = new CheckBox("test").SetPdfAConformanceLevel(PdfAConformanceLevel.PDF_A_1B); + CheckBox checkBoxset = new CheckBox("test").SetPdfConformance(PdfConformance.PDF_A_1B); checkBoxset.SetChecked(true); document.Add(checkBoxset); - CheckBox checkBoxUnsetInteractive = new CheckBox("test1").SetPdfAConformanceLevel(PdfAConformanceLevel.PDF_A_1B - ); + CheckBox checkBoxUnsetInteractive = new CheckBox("test1").SetPdfConformance(PdfConformance.PDF_A_1B); checkBoxUnsetInteractive.SetInteractive(true); document.Add(checkBoxUnsetInteractive); - CheckBox checkBoxsetInteractive = new CheckBox("test2").SetPdfAConformanceLevel(PdfAConformanceLevel.PDF_A_1B - ); + CheckBox checkBoxsetInteractive = new CheckBox("test2").SetPdfConformance(PdfConformance.PDF_A_1B); checkBoxsetInteractive.SetInteractive(true); checkBoxsetInteractive.SetChecked(true); document.Add(checkBoxsetInteractive); @@ -352,7 +337,7 @@ public virtual void CheckBoxSetCheckTypes() { } ); GenerateCheckBoxes(document, (checkBox) => { - checkBox.SetPdfAConformanceLevel(PdfAConformanceLevel.PDF_A_1B); + checkBox.SetPdfConformance(PdfConformance.PDF_A_1B); checkBox.SetCheckBoxType(enumConstant); } ); @@ -369,7 +354,7 @@ public virtual void SetPdfAConformanceLevel() { foreach (CheckBoxType enumConstant in EnumUtil.GetAllValuesOfEnum()) { GenerateCheckBoxes(document, (checkBox) => { checkBox.SetSize(20); - checkBox.SetPdfAConformanceLevel(PdfAConformanceLevel.PDF_A_3B); + checkBox.SetPdfConformance(PdfConformance.PDF_A_3B); checkBox.SetCheckBoxType(enumConstant); } ); @@ -515,7 +500,7 @@ private void GenerateCheckBoxesForAllRenderingModes(Document document, Action { checkBox.SetProperty(Property.RENDERING_MODE, RenderingMode.DEFAULT_LAYOUT_MODE); - checkBox.SetPdfAConformanceLevel(PdfAConformanceLevel.PDF_A_1B); + checkBox.SetPdfConformance(PdfConformance.PDF_A_1B); alterFunction(checkBox); } ); @@ -543,6 +528,39 @@ public virtual void BasicCheckBoxTagged() { NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, DESTINATION_FOLDER)); } + [NUnit.Framework.Test] + public virtual void SetBordersTest() { + String outPdf = DESTINATION_FOLDER + "checkBoxSetBorders.pdf"; + String cmpPdf = SOURCE_FOLDER + "cmp_checkBoxSetBorders.pdf"; + using (Document document = new Document(new PdfDocument(new PdfWriter(outPdf)))) { + float?[] i = new float?[] { .1f, .2f, .3f, .4f }; + document.Add(new Paragraph("Test different borders")); + for (int j = 0; j < 30; j++) { + i[0] += .03f; + i[1] += .05f; + i[2] += .07f; + i[3] += .09f; + CheckBox checkBox = new CheckBox("test" + j); + checkBox.SetChecked(true); + checkBox.SetSize(20); + if (j % 2 == 0) { + checkBox.SetBorderRight(new SolidBorder(ColorConstants.GREEN, (float)i[0])); + } + if (j % 3 == 0) { + checkBox.SetBorderLeft(new SolidBorder(ColorConstants.PINK, (float)i[1])); + } + if (j % 5 == 0 || j == 1 || j == 13 || j == 19 || j == 29) { + checkBox.SetBorderTop(new SolidBorder(ColorConstants.CYAN, (float)i[2])); + } + if (j % 7 == 0 || j == 11 || j == 17 || j == 23) { + checkBox.SetBorderBottom(new SolidBorder(ColorConstants.YELLOW, (float)i[3])); + } + document.Add(checkBox); + } + } + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, DESTINATION_FOLDER)); + } + private IList GenerateCheckBoxes(Document document, Action alterFunction) { IList checkBoxList = new List(); CheckBox formCheckbox = new CheckBox("checkbox_interactive_off_" + this.counter); diff --git a/itext.tests/itext.forms.tests/itext/forms/form/element/ComboBoxFieldTest.cs b/itext.tests/itext.forms.tests/itext/forms/form/element/ComboBoxFieldTest.cs index 8171c4511c..19034b1d86 100644 --- a/itext.tests/itext.forms.tests/itext/forms/form/element/ComboBoxFieldTest.cs +++ b/itext.tests/itext.forms.tests/itext/forms/form/element/ComboBoxFieldTest.cs @@ -272,8 +272,7 @@ public virtual void ComboBoxFieldWithLangTest() { flattenComboBoxField.AddOption(new SelectFieldItem("option 1")); flattenComboBoxField.AddOption(new SelectFieldItem("option 2")); flattenComboBoxField.SetSelected("option 1"); - //TODO DEVSIX-8205 Use setLanguage method from AccessibilityProperties - flattenComboBoxField.SetProperty(FormProperty.FORM_ACCESSIBILITY_LANGUAGE, "random_lang"); + flattenComboBoxField.GetAccessibilityProperties().SetLanguage("random_lang"); document.Add(flattenComboBoxField); } NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, DESTINATION_FOLDER)); @@ -459,7 +458,7 @@ public virtual void AddingOptionsWithSameExportValuesLogsWarningTest() { ComboBoxField comboBoxField = new ComboBoxField("test"); comboBoxField.AddOption(new SelectFieldItem("option 1", "1")); comboBoxField.AddOption(new SelectFieldItem("option 1", "2")); - NUnit.Framework.Assert.AreEqual(2, comboBoxField.GetItems().Count); + NUnit.Framework.Assert.AreEqual(2, comboBoxField.GetOptions().Count); } [NUnit.Framework.Test] @@ -467,7 +466,7 @@ public virtual void AddingWithDuplicateDisplayValueTest() { ComboBoxField comboBoxField = new ComboBoxField("test"); comboBoxField.AddOption(new SelectFieldItem("option 1", "1")); comboBoxField.AddOption(new SelectFieldItem("option 2", "1")); - NUnit.Framework.Assert.AreEqual(2, comboBoxField.GetItems().Count); + NUnit.Framework.Assert.AreEqual(2, comboBoxField.GetOptions().Count); } [NUnit.Framework.Test] diff --git a/itext.tests/itext.forms.tests/itext/forms/form/element/InputFieldTest.cs b/itext.tests/itext.forms.tests/itext/forms/form/element/InputFieldTest.cs index 45b6252d63..54d685afb3 100644 --- a/itext.tests/itext.forms.tests/itext/forms/form/element/InputFieldTest.cs +++ b/itext.tests/itext.forms.tests/itext/forms/form/element/InputFieldTest.cs @@ -76,7 +76,7 @@ public virtual void NoValueInputFieldTest() { InputField flattenInputField = new InputField("no value input field"); flattenInputField.SetProperty(FormProperty.FORM_FIELD_FLATTEN, null); flattenInputField.SetProperty(FormProperty.FORM_FIELD_VALUE, null); - flattenInputField.SetProperty(Property.BORDER, new SolidBorder(2f)); + flattenInputField.SetBorder(new SolidBorder(2f)); document.Add(flattenInputField); } NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, DESTINATION_FOLDER)); @@ -95,7 +95,7 @@ public virtual void InputFieldDoesNotFitTest() { InputField flattenInputField = new InputField("input field does not fit"); flattenInputField.SetProperty(FormProperty.FORM_FIELD_FLATTEN, true); flattenInputField.SetProperty(FormProperty.FORM_FIELD_VALUE, "input field does not fit"); - flattenInputField.SetProperty(Property.BORDER, new SolidBorder(2f)); + flattenInputField.SetBorder(new SolidBorder(2f)); document.Add(flattenInputField); } NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, DESTINATION_FOLDER)); @@ -110,8 +110,8 @@ public virtual void InputFieldWithLangTest() { InputField flattenInputField = new InputField("input field with lang"); flattenInputField.SetProperty(FormProperty.FORM_FIELD_FLATTEN, false); flattenInputField.SetProperty(FormProperty.FORM_FIELD_VALUE, "input field with lang"); - flattenInputField.SetProperty(FormProperty.FORM_ACCESSIBILITY_LANGUAGE, "random_lang"); - flattenInputField.SetProperty(Property.BORDER, new SolidBorder(2f)); + flattenInputField.GetAccessibilityProperties().SetLanguage("random_lang"); + flattenInputField.SetBorder(new SolidBorder(2f)); document.Add(flattenInputField); } NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, DESTINATION_FOLDER)); @@ -126,8 +126,8 @@ public virtual void InputFieldWithNullLangTest() { InputField flattenInputField = new InputField("input field with null lang"); flattenInputField.SetProperty(FormProperty.FORM_FIELD_FLATTEN, false); flattenInputField.SetProperty(FormProperty.FORM_FIELD_VALUE, "input field with null lang"); - flattenInputField.SetProperty(FormProperty.FORM_ACCESSIBILITY_LANGUAGE, null); - flattenInputField.SetProperty(Property.BORDER, new SolidBorder(2f)); + flattenInputField.GetAccessibilityProperties().SetLanguage(null); + flattenInputField.SetBorder(new SolidBorder(2f)); document.Add(flattenInputField); } NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, DESTINATION_FOLDER)); @@ -141,13 +141,13 @@ public virtual void InputFieldWithPasswordTest() { InputField formInputField = new InputField("form input field with password"); formInputField.SetProperty(FormProperty.FORM_FIELD_FLATTEN, false); formInputField.SetProperty(FormProperty.FORM_FIELD_VALUE, "form input field with password"); - formInputField.SetProperty(Property.BORDER, new SolidBorder(2f)); + formInputField.SetBorder(new SolidBorder(2f)); formInputField.SetProperty(FormProperty.FORM_FIELD_PASSWORD_FLAG, true); document.Add(formInputField); InputField flattenInputField = new InputField("flatten input field with password"); flattenInputField.SetProperty(FormProperty.FORM_FIELD_FLATTEN, true); flattenInputField.SetProperty(FormProperty.FORM_FIELD_VALUE, "flatten input field with password"); - flattenInputField.SetProperty(Property.BORDER, new SolidBorder(2f)); + flattenInputField.SetBorder(new SolidBorder(2f)); flattenInputField.SetProperty(FormProperty.FORM_FIELD_PASSWORD_FLAG, true); document.Add(flattenInputField); } @@ -163,7 +163,7 @@ public virtual void HeightInputFieldTest() { flattenInputField.SetProperty(FormProperty.FORM_FIELD_FLATTEN, true); flattenInputField.SetProperty(FormProperty.FORM_FIELD_VALUE, "flatten input field with height"); flattenInputField.SetProperty(Property.HEIGHT, new UnitValue(UnitValue.POINT, 100)); - flattenInputField.SetProperty(Property.BORDER, new SolidBorder(2f)); + flattenInputField.SetBorder(new SolidBorder(2f)); document.Add(flattenInputField); } NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, DESTINATION_FOLDER)); @@ -178,7 +178,7 @@ public virtual void MinHeightInputFieldTest() { flattenInputField.SetProperty(FormProperty.FORM_FIELD_FLATTEN, true); flattenInputField.SetProperty(FormProperty.FORM_FIELD_VALUE, "flatten input field with height"); flattenInputField.SetProperty(Property.MIN_HEIGHT, new UnitValue(UnitValue.POINT, 100)); - flattenInputField.SetProperty(Property.BORDER, new SolidBorder(2f)); + flattenInputField.SetBorder(new SolidBorder(2f)); document.Add(flattenInputField); } NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, DESTINATION_FOLDER)); @@ -193,7 +193,7 @@ public virtual void MaxHeightInputFieldTest() { flattenInputField.SetProperty(FormProperty.FORM_FIELD_FLATTEN, true); flattenInputField.SetProperty(FormProperty.FORM_FIELD_VALUE, "flatten input field with height"); flattenInputField.SetProperty(Property.MAX_HEIGHT, new UnitValue(UnitValue.POINT, 10)); - flattenInputField.SetProperty(Property.BORDER, new SolidBorder(2f)); + flattenInputField.SetBorder(new SolidBorder(2f)); document.Add(flattenInputField); } NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, DESTINATION_FOLDER)); diff --git a/itext.tests/itext.forms.tests/itext/forms/form/element/ListBoxFieldTest.cs b/itext.tests/itext.forms.tests/itext/forms/form/element/ListBoxFieldTest.cs index 38141dea15..398fdcf251 100644 --- a/itext.tests/itext.forms.tests/itext/forms/form/element/ListBoxFieldTest.cs +++ b/itext.tests/itext.forms.tests/itext/forms/form/element/ListBoxFieldTest.cs @@ -91,7 +91,7 @@ public virtual void BasicListBoxFieldTest() { flattenListBoxFieldWithMultipleSelection.SetInteractive(false); flattenListBoxFieldWithMultipleSelection.AddOption("option 1", false); flattenListBoxFieldWithMultipleSelection.AddOption("option 2", true); - flattenListBoxFieldWithMultipleSelection.AddOption(option3); + flattenListBoxFieldWithMultipleSelection.AddOption(new SelectFieldItem("option 3", option3)); document.Add(flattenListBoxFieldWithMultipleSelection); } NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, DESTINATION_FOLDER)); @@ -149,8 +149,8 @@ public virtual void ListBoxFieldWithMarginsTest() { ListBoxField listBoxField = new ListBoxField("list box field with margins", 1, false); listBoxField.SetInteractive(false); listBoxField.SetBackgroundColor(ColorConstants.RED); - listBoxField.AddOption(option1); - listBoxField.AddOption(option2); + listBoxField.AddOption(new SelectFieldItem("option 1", option1)); + listBoxField.AddOption(new SelectFieldItem("option 2", option2)); document.Add(listBoxField); document.Add(new Paragraph("line break")); document.Add(listBoxField); @@ -250,8 +250,8 @@ public virtual void ListBoxFieldCannotFitByWidthTest() { listBoxField.SetBackgroundColor(ColorConstants.RED); listBoxField.SetProperty(Property.WIDTH, UnitValue.CreatePointValue(600)); listBoxField.SetBorder(new SolidBorder(20)); - listBoxField.AddOption(option1); - listBoxField.AddOption(option2); + listBoxField.AddOption(new SelectFieldItem("option 1", option1)); + listBoxField.AddOption(new SelectFieldItem("option 2", option2)); document.Add(listBoxField); document.Add(new Paragraph("Line break")); document.Add(listBoxField.SetInteractive(true)); @@ -270,7 +270,7 @@ public virtual void ListBoxFieldWithLangTest() { listBoxField.SetBackgroundColor(ColorConstants.RED); listBoxField.AddOption("option 1"); listBoxField.AddOption("option 2"); - listBoxField.SetProperty(FormProperty.FORM_ACCESSIBILITY_LANGUAGE, "random_lang"); + listBoxField.GetAccessibilityProperties().SetLanguage("random_lang"); document.Add(listBoxField); document.Add(new Paragraph("Line break")); document.Add(listBoxField.SetInteractive(true)); diff --git a/itext.tests/itext.forms.tests/itext/forms/form/element/SignatureFieldAppearanceTest.cs b/itext.tests/itext.forms.tests/itext/forms/form/element/SignatureFieldAppearanceTest.cs index 122865e9dc..0c6ea92e59 100644 --- a/itext.tests/itext.forms.tests/itext/forms/form/element/SignatureFieldAppearanceTest.cs +++ b/itext.tests/itext.forms.tests/itext/forms/form/element/SignatureFieldAppearanceTest.cs @@ -124,6 +124,38 @@ public virtual void CustomizedSigFieldTest() { NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, DESTINATION_FOLDER)); } + [NUnit.Framework.Test] + public virtual void EmptySigFieldAppearanceTest() { + String outPdf = DESTINATION_FOLDER + "emptySigFieldAppearance.pdf"; + String cmpPdf = SOURCE_FOLDER + "cmp_emptySigFieldAppearance.pdf"; + using (Document document = new Document(new PdfDocument(new PdfWriter(outPdf)))) { + SignedAppearanceText description = new SignedAppearanceText().SetSignedBy(null).SetLocationLine(null).SetReasonLine + (null); + SignatureFieldAppearance formSigField = new SignatureFieldAppearance("Signature1").SetContent(description); + formSigField.SetBackgroundColor(ColorConstants.LIGHT_GRAY); + formSigField.SetBorder(new SolidBorder(ColorConstants.GREEN, 2)); + formSigField.SetHeight(100).SetWidth(200); + document.Add(formSigField); + } + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, DESTINATION_FOLDER)); + } + + [NUnit.Framework.Test] + public virtual void IgnoreSignDateAndReasonInAppearanceTest() { + String outPdf = DESTINATION_FOLDER + "ignoreSignDateAndReasonInAppearance.pdf"; + String cmpPdf = SOURCE_FOLDER + "cmp_ignoreSignDateAndReasonInAppearance.pdf"; + using (Document document = new Document(new PdfDocument(new PdfWriter(outPdf)))) { + SignedAppearanceText description = new SignedAppearanceText().SetSignedBy("Signer Name").SetLocationLine("Test Location" + ).SetReasonLine(null); + SignatureFieldAppearance formSigField = new SignatureFieldAppearance("Signature1").SetContent(description); + formSigField.SetBackgroundColor(ColorConstants.LIGHT_GRAY); + formSigField.SetBorder(new SolidBorder(ColorConstants.GREEN, 2)); + formSigField.SetHeight(100).SetWidth(200); + document.Add(formSigField); + } + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, DESTINATION_FOLDER)); + } + [NUnit.Framework.Test] [LogMessage(iText.IO.Logs.IoLogMessageConstant.CLIP_ELEMENT)] public virtual void SignatureFieldVerticalAlignmentTest() { @@ -341,7 +373,7 @@ public virtual void FontSizeTest() { [NUnit.Framework.Test] public virtual void FontNullCustomCheck() { String outPdf = DESTINATION_FOLDER + "fontNullCustomCheck.pdf"; - PdfDocument pdfDoc = new _PdfDocument_413(new PdfWriter(outPdf)); + PdfDocument pdfDoc = new _PdfDocument_450(new PdfWriter(outPdf)); Document document = new Document(pdfDoc); SignatureFieldAppearance sigField = new SignatureFieldAppearance("SigField"); sigField.SetContent("test"); @@ -352,8 +384,8 @@ public virtual void FontNullCustomCheck() { NUnit.Framework.Assert.AreEqual(LayoutExceptionMessageConstant.INVALID_FONT_PROPERTY_VALUE, e.Message); } - private sealed class _PdfDocument_413 : PdfDocument { - public _PdfDocument_413(PdfWriter baseArg1) + private sealed class _PdfDocument_450 : PdfDocument { + public _PdfDocument_450(PdfWriter baseArg1) : base(baseArg1) { } diff --git a/itext.tests/itext.forms.tests/itext/forms/form/element/TextAreaTest.cs b/itext.tests/itext.forms.tests/itext/forms/form/element/TextAreaTest.cs index 3fcef2dcad..7f3a5eed58 100644 --- a/itext.tests/itext.forms.tests/itext/forms/form/element/TextAreaTest.cs +++ b/itext.tests/itext.forms.tests/itext/forms/form/element/TextAreaTest.cs @@ -92,7 +92,7 @@ public virtual void HeightTextAreaTest() { flattenTextArea.SetProperty(FormProperty.FORM_FIELD_FLATTEN, true); flattenTextArea.SetProperty(FormProperty.FORM_FIELD_VALUE, "flatten\ntext area\nwith height"); flattenTextArea.SetProperty(Property.HEIGHT, new UnitValue(UnitValue.POINT, 100)); - flattenTextArea.SetProperty(Property.BORDER, new SolidBorder(2f)); + flattenTextArea.SetBorder(new SolidBorder(2f)); document.Add(flattenTextArea); } NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, DESTINATION_FOLDER)); @@ -107,7 +107,7 @@ public virtual void MinHeightTextAreaTest() { flattenTextArea.SetProperty(FormProperty.FORM_FIELD_FLATTEN, true); flattenTextArea.SetProperty(FormProperty.FORM_FIELD_VALUE, "flatten\ntext area\nwith height"); flattenTextArea.SetProperty(Property.MIN_HEIGHT, new UnitValue(UnitValue.POINT, 100)); - flattenTextArea.SetProperty(Property.BORDER, new SolidBorder(2f)); + flattenTextArea.SetBorder(new SolidBorder(2f)); document.Add(flattenTextArea); } NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, DESTINATION_FOLDER)); @@ -163,7 +163,7 @@ public virtual void TextAreaDoesNotFitTest() { textArea.SetProperty(FormProperty.FORM_FIELD_VALUE, "some text to not\nbe able to fit in on the page\nmore text just text\nreally big height" ); textArea.SetHeight(50); - textArea.SetProperty(Property.BORDER, new SolidBorder(2f)); + textArea.SetBorder(new SolidBorder(2f)); document.Add(textArea); } NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, DESTINATION_FOLDER)); @@ -179,7 +179,7 @@ public virtual void TextAreaWith0FontSizeDoesNotFitTest() { textArea.SetInteractive(true); textArea.SetProperty(FormProperty.FORM_FIELD_VALUE, "Font\n size \nof this\nText Area will \nbe approximated\nbased on the content" ); - textArea.SetProperty(Property.BORDER, new SolidBorder(1f)); + textArea.SetBorder(new SolidBorder(1f)); textArea.SetFontSize(0); textArea.SetHeight(75); document.Add(textArea); @@ -188,7 +188,7 @@ public virtual void TextAreaWith0FontSizeDoesNotFitTest() { flattenTextArea.SetInteractive(false); flattenTextArea.SetProperty(FormProperty.FORM_FIELD_VALUE, "Font\n size \nof this\nText Area will \nbe approximated\nbased on the content" ); - flattenTextArea.SetProperty(Property.BORDER, new SolidBorder(1f)); + flattenTextArea.SetBorder(new SolidBorder(1f)); flattenTextArea.SetFontSize(0); flattenTextArea.SetHeight(75); document.Add(flattenTextArea); @@ -205,7 +205,7 @@ public virtual void TextAreaWith0FontSizeFitsTest() { textArea.SetInteractive(true); textArea.SetProperty(FormProperty.FORM_FIELD_VALUE, "Font\n size \nof this\nText Area will \nbe approximated\nbased on the content" ); - textArea.SetProperty(Property.BORDER, new SolidBorder(1f)); + textArea.SetBorder(new SolidBorder(1f)); textArea.SetFontSize(0); textArea.SetHeight(75); document.Add(textArea); @@ -213,7 +213,7 @@ public virtual void TextAreaWith0FontSizeFitsTest() { flattenTextArea.SetInteractive(false); flattenTextArea.SetProperty(FormProperty.FORM_FIELD_VALUE, "Font\n size \nof this\nText Area will \nbe approximated\nbased on the content" ); - flattenTextArea.SetProperty(Property.BORDER, new SolidBorder(1f)); + flattenTextArea.SetBorder(new SolidBorder(1f)); flattenTextArea.SetFontSize(0); flattenTextArea.SetHeight(75); document.Add(flattenTextArea); @@ -230,14 +230,14 @@ public virtual void TextAreaWith0FontSizeWithoutHeightTest() { textArea.SetInteractive(true); textArea.SetProperty(FormProperty.FORM_FIELD_VALUE, "Font\n size \nof this\nText Area will not " + "\nbe approximated\nbased on the content\nbecause height is not set" ); - textArea.SetProperty(Property.BORDER, new SolidBorder(1f)); + textArea.SetBorder(new SolidBorder(1f)); textArea.SetFontSize(0); document.Add(textArea); TextArea flattenTextArea = new TextArea("text area"); flattenTextArea.SetInteractive(false); flattenTextArea.SetProperty(FormProperty.FORM_FIELD_VALUE, "Font\n size \nof this\nText Area will not " + "\nbe approximated\nbased on the content\nbecause height is not set"); - flattenTextArea.SetProperty(Property.BORDER, new SolidBorder(1f)); + flattenTextArea.SetBorder(new SolidBorder(1f)); flattenTextArea.SetFontSize(0); document.Add(flattenTextArea); } @@ -253,7 +253,7 @@ public virtual void TextAreaWithBorderLessThan1Test() { textArea.SetInteractive(true); textArea.SetProperty(FormProperty.FORM_FIELD_VALUE, "Is border visible?\nAnd after clicking on the field?\nIt should be by the way" ); - textArea.SetProperty(Property.BORDER, new SolidBorder(0.5f)); + textArea.SetBorder(new SolidBorder(0.5f)); document.Add(textArea); } NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, DESTINATION_FOLDER)); @@ -307,7 +307,7 @@ public virtual void MaxHeightTextAreaTest() { flattenTextArea.SetProperty(FormProperty.FORM_FIELD_FLATTEN, true); flattenTextArea.SetProperty(FormProperty.FORM_FIELD_VALUE, "flatten\ntext area\nwith height"); flattenTextArea.SetProperty(Property.MAX_HEIGHT, new UnitValue(UnitValue.POINT, 28)); - flattenTextArea.SetProperty(Property.BORDER, new SolidBorder(2f)); + flattenTextArea.SetBorder(new SolidBorder(2f)); document.Add(flattenTextArea); } NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, DESTINATION_FOLDER)); diff --git a/itext.tests/itext.forms.tests/itext/forms/form/renderer/InputFieldRendererTest.cs b/itext.tests/itext.forms.tests/itext/forms/form/renderer/InputFieldRendererTest.cs index ffcf1820ae..0201c47731 100644 --- a/itext.tests/itext.forms.tests/itext/forms/form/renderer/InputFieldRendererTest.cs +++ b/itext.tests/itext.forms.tests/itext/forms/form/renderer/InputFieldRendererTest.cs @@ -87,23 +87,24 @@ public virtual void SetMinMaxWidthBasedOnFixedWidthWithoutAbsoluteWidthOnElement [NUnit.Framework.Test] public virtual void PdfAConformanceLevelTest() { InputFieldRenderer inputFieldRenderer = new InputFieldRenderer(new InputField("")); - NUnit.Framework.Assert.IsNull(inputFieldRenderer.GetGenericConformanceLevel(null)); + NUnit.Framework.Assert.IsNull(inputFieldRenderer.GetConformance(null)); } [NUnit.Framework.Test] public virtual void PdfAConformanceLevelWithDocumentTest() { PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new ByteArrayOutputStream())); InputFieldRenderer inputFieldRenderer = new InputFieldRenderer(new InputField("")); - NUnit.Framework.Assert.IsNull(inputFieldRenderer.GetGenericConformanceLevel(pdfDocument)); + NUnit.Framework.Assert.IsNotNull(inputFieldRenderer.GetConformance(pdfDocument)); + NUnit.Framework.Assert.IsFalse(inputFieldRenderer.GetConformance(pdfDocument).IsPdfAOrUa()); } [NUnit.Framework.Test] public virtual void PdfAConformanceLevelWithConformanceLevelTest() { PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new ByteArrayOutputStream())); InputFieldRenderer inputFieldRenderer = new InputFieldRenderer(new InputField("")); - inputFieldRenderer.SetProperty(FormProperty.FORM_CONFORMANCE_LEVEL, PdfAConformanceLevel.PDF_A_1B); - NUnit.Framework.Assert.AreEqual(PdfAConformanceLevel.PDF_A_1B, inputFieldRenderer.GetGenericConformanceLevel - (pdfDocument)); + inputFieldRenderer.SetProperty(FormProperty.FORM_CONFORMANCE_LEVEL, PdfConformance.PDF_A_1B); + NUnit.Framework.Assert.AreEqual(PdfAConformance.PDF_A_1B, inputFieldRenderer.GetConformance(pdfDocument).GetAConformance + ()); } [NUnit.Framework.Test] @@ -112,21 +113,21 @@ public virtual void CreateParagraphRendererTest() { IRenderer paragraphRender = inputFieldRendererWithoutPlaceholder.CreateParagraphRenderer(""); NUnit.Framework.Assert.IsTrue(paragraphRender is ParagraphRenderer); InputField inputFieldWithEmptyPlaceholder = new InputField(""); - inputFieldWithEmptyPlaceholder.SetPlaceholder(new _Paragraph_130()); + inputFieldWithEmptyPlaceholder.SetPlaceholder(new _Paragraph_131()); InputFieldRenderer inputFieldRendererWithEmptyPlaceholder = new InputFieldRenderer(inputFieldWithEmptyPlaceholder ); paragraphRender = inputFieldRendererWithEmptyPlaceholder.CreateParagraphRenderer(""); NUnit.Framework.Assert.IsTrue(paragraphRender is ParagraphRenderer); NUnit.Framework.Assert.IsFalse(paragraphRender is InputFieldRendererTest.CustomParagraphRenderer); InputField inputFieldWithPlaceholder = new InputField(""); - inputFieldWithPlaceholder.SetPlaceholder(new _Paragraph_143()); + inputFieldWithPlaceholder.SetPlaceholder(new _Paragraph_144()); InputFieldRenderer inputFieldRendererWithPlaceholder = new InputFieldRenderer(inputFieldWithPlaceholder); paragraphRender = inputFieldRendererWithPlaceholder.CreateParagraphRenderer(""); NUnit.Framework.Assert.IsTrue(paragraphRender is InputFieldRendererTest.CustomParagraphRenderer); } - private sealed class _Paragraph_130 : Paragraph { - public _Paragraph_130() { + private sealed class _Paragraph_131 : Paragraph { + public _Paragraph_131() { } public override IRenderer CreateRendererSubTree() { @@ -134,8 +135,8 @@ public override IRenderer CreateRendererSubTree() { } } - private sealed class _Paragraph_143 : Paragraph { - public _Paragraph_143() { + private sealed class _Paragraph_144 : Paragraph { + public _Paragraph_144() { } public override bool IsEmpty() { diff --git a/itext.tests/itext.forms.tests/itext/forms/form/renderer/SelectFieldListBoxRendererTest.cs b/itext.tests/itext.forms.tests/itext/forms/form/renderer/SelectFieldListBoxRendererTest.cs index 114086a795..db92f8be42 100644 --- a/itext.tests/itext.forms.tests/itext/forms/form/renderer/SelectFieldListBoxRendererTest.cs +++ b/itext.tests/itext.forms.tests/itext/forms/form/renderer/SelectFieldListBoxRendererTest.cs @@ -49,23 +49,23 @@ public virtual void AllowLastYLineRecursiveExtractionTest() { [NUnit.Framework.Test] public virtual void PdfAConformanceLevelTest() { SelectFieldListBoxRenderer renderer = new SelectFieldListBoxRenderer(new ListBoxField("", 1, false)); - NUnit.Framework.Assert.IsNull(renderer.GetGenericConformanceLevel(null)); + NUnit.Framework.Assert.IsNull(renderer.GetConformance(null)); } [NUnit.Framework.Test] public virtual void PdfAConformanceLevelWithDocumentTest() { PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new ByteArrayOutputStream())); SelectFieldListBoxRenderer renderer = new SelectFieldListBoxRenderer(new ListBoxField("", 1, false)); - NUnit.Framework.Assert.IsNull(renderer.GetGenericConformanceLevel(pdfDocument)); + NUnit.Framework.Assert.IsNotNull(renderer.GetConformance(pdfDocument)); + NUnit.Framework.Assert.IsFalse(renderer.GetConformance(pdfDocument).IsPdfAOrUa()); } [NUnit.Framework.Test] public virtual void PdfAConformanceLevelWithConformanceLevelTest() { PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new ByteArrayOutputStream())); SelectFieldListBoxRenderer renderer = new SelectFieldListBoxRenderer(new ListBoxField("", 1, false)); - renderer.SetProperty(FormProperty.FORM_CONFORMANCE_LEVEL, PdfAConformanceLevel.PDF_A_1B); - NUnit.Framework.Assert.AreEqual(PdfAConformanceLevel.PDF_A_1B, renderer.GetGenericConformanceLevel(pdfDocument - )); + renderer.SetProperty(FormProperty.FORM_CONFORMANCE_LEVEL, PdfConformance.PDF_A_1B); + NUnit.Framework.Assert.AreEqual(PdfConformance.PDF_A_1B, renderer.GetConformance(pdfDocument)); } private class CustomSelectFieldListBoxRenderer : SelectFieldListBoxRenderer { diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/FormFieldAppendTest/Form_Filled.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/FormFieldAppendTest/Form_Filled.pdf deleted file mode 100644 index c6dfa036c8..0000000000 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/FormFieldAppendTest/Form_Filled.pdf and /dev/null differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfAcroFormIntegrationTest/cmp_formWithSameFieldReferences.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfAcroFormIntegrationTest/cmp_formWithSameFieldReferences.pdf new file mode 100644 index 0000000000..ea4260551c Binary files /dev/null and b/itext.tests/itext.forms.tests/resources/itext/forms/PdfAcroFormIntegrationTest/cmp_formWithSameFieldReferences.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfAcroFormIntegrationTest/formWithSameFieldReferences.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfAcroFormIntegrationTest/formWithSameFieldReferences.pdf new file mode 100644 index 0000000000..045ce2d8e0 Binary files /dev/null and b/itext.tests/itext.forms.tests/resources/itext/forms/PdfAcroFormIntegrationTest/formWithSameFieldReferences.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_choiceFieldsSetValueTest.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_choiceFieldsSetValueTest.pdf index e486ae965c..504a2fbb96 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_choiceFieldsSetValueTest.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_choiceFieldsSetValueTest.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_choiceFieldsWithUnicodeTest.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_choiceFieldsWithUnicodeTest.pdf index 12aebb8013..9f87d03e36 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_choiceFieldsWithUnicodeTest.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_choiceFieldsWithUnicodeTest.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_comboNoHighlightCenteredTextOfChosenFirstItemTest.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_comboNoHighlightCenteredTextOfChosenFirstItemTest.pdf index a38e49cc5d..234af1ce9a 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_comboNoHighlightCenteredTextOfChosenFirstItemTest.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_comboNoHighlightCenteredTextOfChosenFirstItemTest.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_corruptedOptAndValueSetToNullTest.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_corruptedOptAndValueSetToNullTest.pdf index 955b6ff46c..b2d908e99e 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_corruptedOptAndValueSetToNullTest.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_corruptedOptAndValueSetToNullTest.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_longOptionWrappedIntoTwoLinesTest.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_longOptionWrappedIntoTwoLinesTest.pdf index f77abb317a..5fdd28ee68 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_longOptionWrappedIntoTwoLinesTest.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_longOptionWrappedIntoTwoLinesTest.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_multiSelectByIndexOutOfBoundsTest.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_multiSelectByIndexOutOfBoundsTest.pdf index 45e7b2be1d..610912e700 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_multiSelectByIndexOutOfBoundsTest.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_multiSelectByIndexOutOfBoundsTest.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_multiSelectByValueTest.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_multiSelectByValueTest.pdf index ffc4015922..df10ca14dd 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_multiSelectByValueTest.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_multiSelectByValueTest.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_noWarningOnValueNotOfOptComboEditTest.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_noWarningOnValueNotOfOptComboEditTest.pdf index 48b01bb850..5722b654e8 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_noWarningOnValueNotOfOptComboEditTest.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_noWarningOnValueNotOfOptComboEditTest.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_notInstanceOfPdfChoiceFormFieldTest.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_notInstanceOfPdfChoiceFormFieldTest.pdf index 959b0cf421..523c29b0b1 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_notInstanceOfPdfChoiceFormFieldTest.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_notInstanceOfPdfChoiceFormFieldTest.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_selectByValueRemoveIKeyTest.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_selectByValueRemoveIKeyTest.pdf index ddcb212d4e..fdc407fd3a 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_selectByValueRemoveIKeyTest.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_selectByValueRemoveIKeyTest.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_topIndexTest.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_topIndexTest.pdf index 88f28dc0a5..127407f80b 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_topIndexTest.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/PdfChoiceFieldTest/cmp_topIndexTest.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfEncryptionTest/cmp_encryptAes256Pdf2PermissionsTest01.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfEncryptionTest/cmp_encryptAes256Pdf2PermissionsTest01.pdf index ba3567db40..5635669094 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfEncryptionTest/cmp_encryptAes256Pdf2PermissionsTest01.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/PdfEncryptionTest/cmp_encryptAes256Pdf2PermissionsTest01.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfEncryptionTest/cmp_encryptAes256Pdf2PermissionsTest02.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfEncryptionTest/cmp_encryptAes256Pdf2PermissionsTest02.pdf index 6da4cf233f..e554cbc19f 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfEncryptionTest/cmp_encryptAes256Pdf2PermissionsTest02.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/PdfEncryptionTest/cmp_encryptAes256Pdf2PermissionsTest02.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormCopyTest/cmp_copyFields08.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormCopyTest/cmp_copyFields08.pdf deleted file mode 100644 index fb0e612306..0000000000 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormCopyTest/cmp_copyFields08.pdf and /dev/null differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormCopyTest/copyFields12.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormCopyTest/copyFields12.pdf deleted file mode 100644 index 1da7d68446..0000000000 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormCopyTest/copyFields12.pdf and /dev/null differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/FreeSans.ttf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/FreeSans.ttf deleted file mode 100644 index 4b06bd7822..0000000000 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/FreeSans.ttf and /dev/null differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/blank.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/blank.pdf deleted file mode 100644 index 9bce695a05..0000000000 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/blank.pdf and /dev/null differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_choiceFieldAutoSize01Test.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_choiceFieldAutoSize01Test.pdf index 7af2298409..9f66295c44 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_choiceFieldAutoSize01Test.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_choiceFieldAutoSize01Test.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_choiceFieldAutoSize02Test.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_choiceFieldAutoSize02Test.pdf index e6b295a72e..5fa41700d9 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_choiceFieldAutoSize02Test.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_choiceFieldAutoSize02Test.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_choiceFieldTest01.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_choiceFieldTest01.pdf index fd731e932b..62aa5fd424 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_choiceFieldTest01.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_choiceFieldTest01.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_formFieldWithFloatBorder.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_formFieldWithFloatBorder.pdf index eda29e9c8e..4c51a6e25d 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_formFieldWithFloatBorder.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_formFieldWithFloatBorder.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_maxLenColoredTest.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_maxLenColoredTest.pdf index 9be43336d5..294e248d67 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_maxLenColoredTest.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_maxLenColoredTest.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_maxLenDeepInheritanceTest.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_maxLenDeepInheritanceTest.pdf index 2a078731f2..762f7f115f 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_maxLenDeepInheritanceTest.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_maxLenDeepInheritanceTest.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_maxLenInheritanceTest.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_maxLenInheritanceTest.pdf index 1044150545..35a9ef00da 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_maxLenInheritanceTest.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_maxLenInheritanceTest.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_maxLenWithSetCombFlagAppearanceTest.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_maxLenWithSetCombFlagAppearanceTest.pdf index 2eaf41080a..5a36797ec4 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_maxLenWithSetCombFlagAppearanceTest.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_maxLenWithSetCombFlagAppearanceTest.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_noMaxLenWithSetCombFlagTest.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_noMaxLenWithSetCombFlagTest.pdf index 7918f1b2ff..0034cbe7a4 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_noMaxLenWithSetCombFlagTest.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_noMaxLenWithSetCombFlagTest.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_pdfWithDifferentFieldsTest.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_pdfWithDifferentFieldsTest.pdf index 47b9dc46e2..6a15677748 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_pdfWithDifferentFieldsTest.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_pdfWithDifferentFieldsTest.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_regenerateMaxLenCombTest.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_regenerateMaxLenCombTest.pdf index ff9d7db8c3..950c609c82 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_regenerateMaxLenCombTest.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_regenerateMaxLenCombTest.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_setNeedAppearancesInAppendModeTest.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_setNeedAppearancesInAppendModeTest.pdf deleted file mode 100644 index 3a2f4c8a26..0000000000 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_setNeedAppearancesInAppendModeTest.pdf and /dev/null differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_setSignatureFlagsInAppendModeTest.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_setSignatureFlagsInAppendModeTest.pdf deleted file mode 100644 index 9cd116a644..0000000000 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_setSignatureFlagsInAppendModeTest.pdf and /dev/null differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_setValueWithDisplayTest.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_setValueWithDisplayTest.pdf index 7a456b4fe4..845d123400 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_setValueWithDisplayTest.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/cmp_setValueWithDisplayTest.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/fontAutoSizeButtonFieldTest.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/fontAutoSizeButtonFieldTest.pdf deleted file mode 100644 index 7e83cedfb9..0000000000 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/PdfFormFieldTest/fontAutoSizeButtonFieldTest.pdf and /dev/null differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfReaderTest/cmp_xfdfDropDown.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/XfdfReaderTest/cmp_xfdfDropDown.pdf index 0218a7c84b..c57e22b437 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfReaderTest/cmp_xfdfDropDown.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/XfdfReaderTest/cmp_xfdfDropDown.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfReaderTest/cmp_xfdfList.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/XfdfReaderTest/cmp_xfdfList.pdf index db29b7fb5f..27637b7755 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfReaderTest/cmp_xfdfList.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/XfdfReaderTest/cmp_xfdfList.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfReaderTest/data.xfdf b/itext.tests/itext.forms.tests/resources/itext/forms/XfdfReaderTest/data.xfdf deleted file mode 100644 index 02c346fcb5..0000000000 --- a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfReaderTest/data.xfdf +++ /dev/null @@ -1,13 +0,0 @@ - - - -Santaaimonce -Developer -Alphabet Street -Minneapolis -Minnesota -Use iText to fill out interactive form using data stored in XFDF file. -If you are a C# developer, use iTextSharp. - - - \ No newline at end of file diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfReaderTest/list_register.xfdf b/itext.tests/itext.forms.tests/resources/itext/forms/XfdfReaderTest/list_register.xfdf deleted file mode 100644 index 5e26322aa0..0000000000 --- a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfReaderTest/list_register.xfdf +++ /dev/null @@ -1,19 +0,0 @@ - - - - -Bruno Lowagie - - -Baeyensstraat 121, -Sint-Amandsberg - - -9040 - - -bruno@lowagie.com - - - - \ No newline at end of file diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfReaderTest/pdf_without_data.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/XfdfReaderTest/pdf_without_data.pdf deleted file mode 100644 index 0324e8cfa2..0000000000 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfReaderTest/pdf_without_data.pdf and /dev/null differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfReaderTest/register.xfdf b/itext.tests/itext.forms.tests/resources/itext/forms/XfdfReaderTest/register.xfdf deleted file mode 100644 index f38e5f4251..0000000000 --- a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfReaderTest/register.xfdf +++ /dev/null @@ -1,18 +0,0 @@ - - - - -Bruno Lowagie - - -Baeyensstraat 121, Sint-Amandsberg - - -9040 - - -bruno@lowagie.com - - - - \ No newline at end of file diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfReaderTest/submit_me_form_book_9.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/XfdfReaderTest/submit_me_form_book_9.pdf deleted file mode 100644 index 8cb3ca99e9..0000000000 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfReaderTest/submit_me_form_book_9.pdf and /dev/null differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfReaderTest/submit_me_form_book_9.xfdf b/itext.tests/itext.forms.tests/resources/itext/forms/XfdfReaderTest/submit_me_form_book_9.xfdf deleted file mode 100644 index ebef9e06f4..0000000000 --- a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfReaderTest/submit_me_form_book_9.xfdf +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - -blowagie - - -Bruno Lowagie - - - -I like to wathc movies! - - - - - \ No newline at end of file diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/Requisition_Fillable.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/Requisition_Fillable.pdf deleted file mode 100644 index 0324e8cfa2..0000000000 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/Requisition_Fillable.pdf and /dev/null differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/cmp_fieldEmptyValueTest.xfdf b/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/cmp_fieldEmptyValueTest.xfdf deleted file mode 100644 index d99d49a607..0000000000 --- a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/cmp_fieldEmptyValueTest.xfdf +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/cmp_fieldNullValueTest.xfdf b/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/cmp_fieldNullValueTest.xfdf deleted file mode 100644 index d99d49a607..0000000000 --- a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/cmp_fieldNullValueTest.xfdf +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/cmp_formFieldTest.xfdf b/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/cmp_formFieldTest.xfdf deleted file mode 100644 index db5ba5fc59..0000000000 --- a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/cmp_formFieldTest.xfdf +++ /dev/null @@ -1,20 +0,0 @@ - - - - - -Да - - -some value in courier font - - - TestField - - - aa - - - - \ No newline at end of file diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/cmp_xfdfHighlightedText_preprocessed.xfdf b/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/cmp_xfdfHighlightedText_preprocessed.xfdf deleted file mode 100644 index b982c13b7b..0000000000 --- a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/cmp_xfdfHighlightedText_preprocessed.xfdf +++ /dev/null @@ -1 +0,0 @@ -Marked set by AlexAnnotation 1 \ No newline at end of file diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/data.xfdf b/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/data.xfdf deleted file mode 100644 index 02c346fcb5..0000000000 --- a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/data.xfdf +++ /dev/null @@ -1,13 +0,0 @@ - - - -Santaaimonce -Developer -Alphabet Street -Minneapolis -Minnesota -Use iText to fill out interactive form using data stored in XFDF file. -If you are a C# developer, use iTextSharp. - - - \ No newline at end of file diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/formFieldTest04_data.xfdf b/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/formFieldTest04_data.xfdf deleted file mode 100644 index 7c261caa8e..0000000000 --- a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/formFieldTest04_data.xfdf +++ /dev/null @@ -1,24 +0,0 @@ - -Даsome value in courier fontTestFieldaa \ No newline at end of file diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/hierarchy_fields.xfdf b/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/hierarchy_fields.xfdf deleted file mode 100644 index ef517adee4..0000000000 --- a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/hierarchy_fields.xfdf +++ /dev/null @@ -1,22 +0,0 @@ - -test - - -some other value - - - \ No newline at end of file diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/myout.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/myout.pdf deleted file mode 100644 index 6e56cfa3d2..0000000000 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/myout.pdf and /dev/null differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/simpleFormWithOneField_data.xfdf b/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/simpleFormWithOneField_data.xfdf deleted file mode 100644 index 0bcea6479a..0000000000 --- a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/simpleFormWithOneField_data.xfdf +++ /dev/null @@ -1,12 +0,0 @@ - -中学生 \ No newline at end of file diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/submit_me_form_book_9.xfdf b/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/submit_me_form_book_9.xfdf deleted file mode 100644 index 275ce5113c..0000000000 --- a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/submit_me_form_book_9.xfdf +++ /dev/null @@ -1,19 +0,0 @@ - - - - - -blowagie - - -Bruno Lowagie - - -I like to wathc movies! - - - - - \ No newline at end of file diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/xfdfFormsFieldParams.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/xfdfFormsFieldParams.pdf deleted file mode 100644 index f19c7fbe19..0000000000 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/xfdfFormsFieldParams.pdf and /dev/null differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/xfdfHighlightedTexttestforannotation.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/xfdfHighlightedTexttestforannotation.pdf deleted file mode 100644 index 7d638083ba..0000000000 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/XfdfWriterTest/xfdfHighlightedTexttestforannotation.pdf and /dev/null differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/CheckBoxTest/cmp_checkBoxSetBorders.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/CheckBoxTest/cmp_checkBoxSetBorders.pdf new file mode 100644 index 0000000000..a3d49ee6a3 Binary files /dev/null and b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/CheckBoxTest/cmp_checkBoxSetBorders.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/CheckBoxTest/cmp_checkBox_setSmallBorder.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/CheckBoxTest/cmp_checkBox_setSmallBorder.pdf index bb04a15862..acde402c8e 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/CheckBoxTest/cmp_checkBox_setSmallBorder.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/CheckBoxTest/cmp_checkBox_setSmallBorder.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/CheckBoxTest/cmp_setBorder.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/CheckBoxTest/cmp_setBorder.pdf index 03ac13d6b9..67618f771c 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/CheckBoxTest/cmp_setBorder.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/CheckBoxTest/cmp_setBorder.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/CheckBoxTest/setSize_CheckBox_checked.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/CheckBoxTest/setSize_CheckBox_checked.pdf deleted file mode 100644 index 896b3ecce9..0000000000 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/CheckBoxTest/setSize_CheckBox_checked.pdf and /dev/null differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ComboBoxFieldTest/cmp_basicComboBoxBorderTest.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ComboBoxFieldTest/cmp_basicComboBoxBorderTest.pdf index 73bee9d725..734e493aad 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ComboBoxFieldTest/cmp_basicComboBoxBorderTest.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ComboBoxFieldTest/cmp_basicComboBoxBorderTest.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_basicListBoxField.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_basicListBoxField.pdf index f3d1ce83cf..ad543c9f93 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_basicListBoxField.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_basicListBoxField.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_colorsBorders.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_colorsBorders.pdf index 59e98de8e6..1f683ffd8f 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_colorsBorders.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_colorsBorders.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_exportValue.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_exportValue.pdf index 7ab9e1885f..23596f7f12 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_exportValue.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_exportValue.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_justification.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_justification.pdf index 6de476c24e..7da2d6ce5c 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_justification.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_justification.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_listBoxFieldCannotFit.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_listBoxFieldCannotFit.pdf index b0747fe97a..938d787215 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_listBoxFieldCannotFit.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_listBoxFieldCannotFit.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_listBoxFieldCannotFitByWidth.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_listBoxFieldCannotFitByWidth.pdf index b1729f065a..876f01f603 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_listBoxFieldCannotFitByWidth.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_listBoxFieldCannotFitByWidth.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_listBoxFieldWithHeight.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_listBoxFieldWithHeight.pdf index e02d5b1b4b..c0ae115524 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_listBoxFieldWithHeight.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_listBoxFieldWithHeight.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_listBoxFieldWithLang.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_listBoxFieldWithLang.pdf index 4d83d96e23..19d7aea156 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_listBoxFieldWithLang.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_listBoxFieldWithLang.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_listBoxFieldWithMargins.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_listBoxFieldWithMargins.pdf index df56acf0b0..f9de9bd764 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_listBoxFieldWithMargins.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_listBoxFieldWithMargins.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_listBoxFieldWithMaxHeight.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_listBoxFieldWithMaxHeight.pdf index 470ad0c7ba..14ef2bc145 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_listBoxFieldWithMaxHeight.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_listBoxFieldWithMaxHeight.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_listBoxFieldWithMinHeight.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_listBoxFieldWithMinHeight.pdf index a23c786345..88ac402017 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_listBoxFieldWithMinHeight.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_listBoxFieldWithMinHeight.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_longList.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_longList.pdf index c2e67df2dd..ca8ab0d367 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_longList.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/ListBoxFieldTest/cmp_longList.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/SignatureFieldAppearanceTest/cmp_emptySigFieldAppearance.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/SignatureFieldAppearanceTest/cmp_emptySigFieldAppearance.pdf new file mode 100644 index 0000000000..9110617e77 Binary files /dev/null and b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/SignatureFieldAppearanceTest/cmp_emptySigFieldAppearance.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/SignatureFieldAppearanceTest/cmp_ignoreSignDateAndReasonInAppearance.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/SignatureFieldAppearanceTest/cmp_ignoreSignDateAndReasonInAppearance.pdf new file mode 100644 index 0000000000..8b781d8589 Binary files /dev/null and b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/SignatureFieldAppearanceTest/cmp_ignoreSignDateAndReasonInAppearance.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/SignatureFieldAppearanceTest/cmp_sigFieldWithNameAndDescriptionMode.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/SignatureFieldAppearanceTest/cmp_sigFieldWithNameAndDescriptionMode.pdf deleted file mode 100644 index 36d47ba91f..0000000000 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/SignatureFieldAppearanceTest/cmp_sigFieldWithNameAndDescriptionMode.pdf and /dev/null differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/TextAreaTest/cmp_textAreaWithBorderLessThan1.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/TextAreaTest/cmp_textAreaWithBorderLessThan1.pdf index 2798fb5ec1..3aaf1c7af1 100644 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/form/element/TextAreaTest/cmp_textAreaWithBorderLessThan1.pdf and b/itext.tests/itext.forms.tests/resources/itext/forms/form/element/TextAreaTest/cmp_textAreaWithBorderLessThan1.pdf differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/widget/AppearanceCharacteristicsTest/changeBorderStyle.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/widget/AppearanceCharacteristicsTest/changeBorderStyle.pdf deleted file mode 100644 index 9f6e63ec36..0000000000 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/widget/AppearanceCharacteristicsTest/changeBorderStyle.pdf and /dev/null differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/widget/AppearanceCharacteristicsTest/cmp_updatingDocumentWithUnderlineFieldBorder.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/widget/AppearanceCharacteristicsTest/cmp_updatingDocumentWithUnderlineFieldBorder.pdf deleted file mode 100644 index d4c3da3e44..0000000000 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/widget/AppearanceCharacteristicsTest/cmp_updatingDocumentWithUnderlineFieldBorder.pdf and /dev/null differ diff --git a/itext.tests/itext.forms.tests/resources/itext/forms/widget/AppearanceCharacteristicsTest/documentWithUnderlineFieldBorder.pdf b/itext.tests/itext.forms.tests/resources/itext/forms/widget/AppearanceCharacteristicsTest/documentWithUnderlineFieldBorder.pdf deleted file mode 100644 index cd6e1f0111..0000000000 Binary files a/itext.tests/itext.forms.tests/resources/itext/forms/widget/AppearanceCharacteristicsTest/documentWithUnderlineFieldBorder.pdf and /dev/null differ diff --git a/itext.tests/itext.io.tests/Properties/AssemblyInfo.cs b/itext.tests/itext.io.tests/Properties/AssemblyInfo.cs index e0899795a2..f77aee36ce 100644 --- a/itext.tests/itext.io.tests/Properties/AssemblyInfo.cs +++ b/itext.tests/itext.io.tests/Properties/AssemblyInfo.cs @@ -15,9 +15,9 @@ [assembly: Guid("a53a5dd3-787b-4563-8778-1d76bdad57ba")] -[assembly: AssemblyVersion("8.0.5.0")] -[assembly: AssemblyFileVersion("8.0.5.0")] -[assembly: AssemblyInformationalVersion("8.0.5")] +[assembly: AssemblyVersion("9.0.0.0")] +[assembly: AssemblyFileVersion("9.0.0.0")] +[assembly: AssemblyInformationalVersion("9.0.0")] #if !NETSTANDARD2_0 [assembly: NUnit.Framework.Timeout(300000)] diff --git a/itext.tests/itext.io.tests/itext/io/font/CFFFontSubsetIntegrationTest.cs b/itext.tests/itext.io.tests/itext/io/font/CFFFontSubsetIntegrationTest.cs index 596cce5093..18be4a5f8a 100644 --- a/itext.tests/itext.io.tests/itext/io/font/CFFFontSubsetIntegrationTest.cs +++ b/itext.tests/itext.io.tests/itext/io/font/CFFFontSubsetIntegrationTest.cs @@ -104,7 +104,7 @@ public virtual void SubsetNonCidCFFFontRangeCheck() { CFFFont result = new CFFFont(cffSubsetBytes); int expectedCharsetLength = 255; // skip over the format ID (1 byte) and the first SID (2 bytes) - result.Seek(result.fonts[0].charsetOffset + 3); + result.Seek(result.fonts[0].GetCharsetOffset() + 3); NUnit.Framework.Assert.AreEqual(expectedCharsetLength - 2, result.GetCard16()); } diff --git a/itext.tests/itext.io.tests/itext/io/font/LoadAllAsianFontsTest.cs b/itext.tests/itext.io.tests/itext/io/font/LoadAllAsianFontsTest.cs new file mode 100644 index 0000000000..32a72ad17a --- /dev/null +++ b/itext.tests/itext.io.tests/itext/io/font/LoadAllAsianFontsTest.cs @@ -0,0 +1,239 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using System.Collections.Generic; +using iText.IO.Font.Cmap; +using iText.Test; +using iText.Test.Attributes; + +namespace iText.IO.Font { + [NUnit.Framework.Category("IntegrationTest")] + public class LoadAllAsianFontsTest : ExtendedITextTest { + [NUnit.Framework.TestCaseSource("Data")] + // TODO DEVSIX-8619 All cmap parsing errors should be fixed and this logging should then be removed + [LogMessage(iText.IO.Logs.IoLogMessageConstant.UNKNOWN_ERROR_WHILE_PROCESSING_CMAP, Ignore = true)] + public virtual void TestAsianFonts(String cmapName, String ordering) { + CheckFontAsianCmap(cmapName, ordering); + } + + public static ICollection Data() { + IList result = new List(); + result.Add(new Object[] { "78-EUC-H", "Japan1" }); + result.Add(new Object[] { "78-EUC-V", "Japan1" }); + result.Add(new Object[] { "78-H", "Japan1" }); + result.Add(new Object[] { "78-RKSJ-H", "Japan1" }); + result.Add(new Object[] { "78-RKSJ-V", "Japan1" }); + result.Add(new Object[] { "78-V", "Japan1" }); + result.Add(new Object[] { "78ms-RKSJ-H", "Japan1" }); + result.Add(new Object[] { "78ms-RKSJ-V", "Japan1" }); + result.Add(new Object[] { "83pv-RKSJ-H", "Japan1" }); + result.Add(new Object[] { "90ms-RKSJ-H", "Japan1" }); + result.Add(new Object[] { "90ms-RKSJ-V", "Japan1" }); + result.Add(new Object[] { "90msp-RKSJ-H", "Japan1" }); + result.Add(new Object[] { "90msp-RKSJ-V", "Japan1" }); + result.Add(new Object[] { "90pv-RKSJ-H", "Japan1" }); + result.Add(new Object[] { "90pv-RKSJ-V", "Japan1" }); + result.Add(new Object[] { "Add-H", "Japan1" }); + result.Add(new Object[] { "Add-RKSJ-H", "Japan1" }); + result.Add(new Object[] { "Add-RKSJ-V", "Japan1" }); + result.Add(new Object[] { "Add-V", "Japan1" }); + result.Add(new Object[] { "Adobe-CNS1-0", "CNS1" }); + result.Add(new Object[] { "Adobe-CNS1-1", "CNS1" }); + result.Add(new Object[] { "Adobe-CNS1-2", "CNS1" }); + result.Add(new Object[] { "Adobe-CNS1-3", "CNS1" }); + result.Add(new Object[] { "Adobe-CNS1-4", "CNS1" }); + result.Add(new Object[] { "Adobe-CNS1-5", "CNS1" }); + result.Add(new Object[] { "Adobe-CNS1-6", "CNS1" }); + result.Add(new Object[] { "Adobe-CNS1-7", "CNS1" }); + result.Add(new Object[] { "Adobe-GB1-0", "GB1" }); + result.Add(new Object[] { "Adobe-GB1-1", "GB1" }); + result.Add(new Object[] { "Adobe-GB1-2", "GB1" }); + result.Add(new Object[] { "Adobe-GB1-3", "GB1" }); + result.Add(new Object[] { "Adobe-GB1-4", "GB1" }); + result.Add(new Object[] { "Adobe-GB1-5", "GB1" }); + result.Add(new Object[] { "Adobe-Japan1-0", "Japan1" }); + result.Add(new Object[] { "Adobe-Japan1-1", "Japan1" }); + result.Add(new Object[] { "Adobe-Japan1-2", "Japan1" }); + result.Add(new Object[] { "Adobe-Japan1-3", "Japan1" }); + result.Add(new Object[] { "Adobe-Japan1-4", "Japan1" }); + result.Add(new Object[] { "Adobe-Japan1-5", "Japan1" }); + result.Add(new Object[] { "Adobe-Japan1-6", "Japan1" }); + result.Add(new Object[] { "Adobe-Japan1-7", "Japan1" }); + result.Add(new Object[] { "Adobe-Korea1-0", "Korea1" }); + result.Add(new Object[] { "Adobe-Korea1-1", "Korea1" }); + result.Add(new Object[] { "Adobe-Korea1-2", "Korea1" }); + result.Add(new Object[] { "Adobe-KR-0", "KR" }); + result.Add(new Object[] { "Adobe-KR-1", "KR" }); + result.Add(new Object[] { "Adobe-KR-2", "KR" }); + result.Add(new Object[] { "Adobe-KR-3", "KR" }); + result.Add(new Object[] { "Adobe-KR-4", "KR" }); + result.Add(new Object[] { "Adobe-KR-5", "KR" }); + result.Add(new Object[] { "Adobe-KR-6", "KR" }); + result.Add(new Object[] { "Adobe-KR-7", "KR" }); + result.Add(new Object[] { "Adobe-KR-8", "KR" }); + result.Add(new Object[] { "Adobe-KR-9", "KR" }); + result.Add(new Object[] { "B5-H", "CNS1" }); + result.Add(new Object[] { "B5-V", "CNS1" }); + result.Add(new Object[] { "B5pc-H", "CNS1" }); + result.Add(new Object[] { "B5pc-V", "CNS1" }); + result.Add(new Object[] { "CNS1-H", "CNS1" }); + result.Add(new Object[] { "CNS1-V", "CNS1" }); + result.Add(new Object[] { "CNS2-H", "CNS1" }); + result.Add(new Object[] { "CNS2-V", "CNS1" }); + result.Add(new Object[] { "CNS-EUC-H", "CNS1" }); + result.Add(new Object[] { "CNS-EUC-V", "CNS1" }); + result.Add(new Object[] { "ETen-B5-H", "CNS1" }); + result.Add(new Object[] { "ETen-B5-V", "CNS1" }); + result.Add(new Object[] { "ETenms-B5-H", "CNS1" }); + result.Add(new Object[] { "ETenms-B5-V", "CNS1" }); + result.Add(new Object[] { "ETHK-B5-H", "CNS1" }); + result.Add(new Object[] { "ETHK-B5-V", "CNS1" }); + result.Add(new Object[] { "EUC-H", "Japan1" }); + result.Add(new Object[] { "EUC-V", "Japan1" }); + result.Add(new Object[] { "Ext-H", "Japan1" }); + result.Add(new Object[] { "Ext-RKSJ-H", "Japan1" }); + result.Add(new Object[] { "Ext-RKSJ-V", "Japan1" }); + result.Add(new Object[] { "Ext-V", "Japan1" }); + result.Add(new Object[] { "GB-EUC-H", "GB1" }); + result.Add(new Object[] { "GB-EUC-V", "GB1" }); + result.Add(new Object[] { "GBK2K-H", "GB1" }); + result.Add(new Object[] { "GBK2K-V", "GB1" }); + result.Add(new Object[] { "GBK-EUC-H", "GB1" }); + result.Add(new Object[] { "GBK-EUC-V", "GB1" }); + result.Add(new Object[] { "GBKp-EUC-H", "GB1" }); + result.Add(new Object[] { "GBKp-EUC-V", "GB1" }); + result.Add(new Object[] { "GBpc-EUC-H", "GB1" }); + result.Add(new Object[] { "GBpc-EUC-V", "GB1" }); + result.Add(new Object[] { "GBT-EUC-H", "GB1" }); + result.Add(new Object[] { "GBT-EUC-V", "GB1" }); + result.Add(new Object[] { "GBT-H", "GB1" }); + result.Add(new Object[] { "GBT-V", "GB1" }); + result.Add(new Object[] { "GBTpc-EUC-H", "GB1" }); + result.Add(new Object[] { "GBTpc-EUC-V", "GB1" }); + result.Add(new Object[] { "H", "Japan1" }); + result.Add(new Object[] { "Hankaku", "Japan1" }); + result.Add(new Object[] { "Hiragana", "Japan1" }); + result.Add(new Object[] { "HKdla-B5-H", "CNS1" }); + result.Add(new Object[] { "HKdla-B5-V", "CNS1" }); + result.Add(new Object[] { "HKdlb-B5-H", "CNS1" }); + result.Add(new Object[] { "HKdlb-B5-V", "CNS1" }); + result.Add(new Object[] { "HKgccs-B5-H", "CNS1" }); + result.Add(new Object[] { "HKgccs-B5-V", "CNS1" }); + result.Add(new Object[] { "HKm314-B5-H", "CNS1" }); + result.Add(new Object[] { "HKm314-B5-V", "CNS1" }); + result.Add(new Object[] { "HKm471-B5-H", "CNS1" }); + result.Add(new Object[] { "HKm471-B5-V", "CNS1" }); + result.Add(new Object[] { "HKscs-B5-H", "CNS1" }); + result.Add(new Object[] { "HKscs-B5-V", "CNS1" }); + result.Add(new Object[] { "Identity-H", "Identity" }); + result.Add(new Object[] { "Identity-V", "Identity" }); + result.Add(new Object[] { "Katakana", "Japan1" }); + result.Add(new Object[] { "KSC-EUC-H", "Korea1" }); + result.Add(new Object[] { "KSC-EUC-V", "Korea1" }); + result.Add(new Object[] { "KSC-H", "Korea1" }); + result.Add(new Object[] { "KSC-Johab-H", "Korea1" }); + result.Add(new Object[] { "KSC-Johab-V", "Korea1" }); + result.Add(new Object[] { "KSC-V", "Korea1" }); + result.Add(new Object[] { "KSCms-UHC-H", "Korea1" }); + result.Add(new Object[] { "KSCms-UHC-HW-H", "Korea1" }); + result.Add(new Object[] { "KSCms-UHC-HW-V", "Korea1" }); + result.Add(new Object[] { "KSCms-UHC-V", "Korea1" }); + result.Add(new Object[] { "KSCpc-EUC-H", "Korea1" }); + result.Add(new Object[] { "KSCpc-EUC-V", "Korea1" }); + result.Add(new Object[] { "NWP-H", "Japan1" }); + result.Add(new Object[] { "NWP-V", "Japan1" }); + result.Add(new Object[] { "RKSJ-H", "Japan1" }); + result.Add(new Object[] { "RKSJ-V", "Japan1" }); + result.Add(new Object[] { "Roman", "Japan1" }); + result.Add(new Object[] { "UniAKR-UTF8-H", "KR" }); + result.Add(new Object[] { "UniAKR-UTF16-H", "KR" }); + result.Add(new Object[] { "UniAKR-UTF32-H", "KR" }); + result.Add(new Object[] { "UniCNS-UCS2-H", "CNS1" }); + result.Add(new Object[] { "UniCNS-UCS2-V", "CNS1" }); + result.Add(new Object[] { "UniCNS-UTF8-H", "CNS1" }); + result.Add(new Object[] { "UniCNS-UTF8-V", "CNS1" }); + result.Add(new Object[] { "UniCNS-UTF16-H", "CNS1" }); + result.Add(new Object[] { "UniCNS-UTF16-V", "CNS1" }); + result.Add(new Object[] { "UniCNS-UTF32-H", "CNS1" }); + result.Add(new Object[] { "UniCNS-UTF32-V", "CNS1" }); + result.Add(new Object[] { "UniGB-UCS2-H", "GB1" }); + result.Add(new Object[] { "UniGB-UCS2-V", "GB1" }); + result.Add(new Object[] { "UniGB-UTF8-H", "GB1" }); + result.Add(new Object[] { "UniGB-UTF8-V", "GB1" }); + result.Add(new Object[] { "UniGB-UTF16-H", "GB1" }); + result.Add(new Object[] { "UniGB-UTF16-V", "GB1" }); + result.Add(new Object[] { "UniGB-UTF32-H", "GB1" }); + result.Add(new Object[] { "UniGB-UTF32-V", "GB1" }); + result.Add(new Object[] { "UniJIS2004-UTF8-H", "Japan1" }); + result.Add(new Object[] { "UniJIS2004-UTF8-V", "Japan1" }); + result.Add(new Object[] { "UniJIS2004-UTF16-H", "Japan1" }); + result.Add(new Object[] { "UniJIS2004-UTF16-V", "Japan1" }); + result.Add(new Object[] { "UniJIS2004-UTF32-H", "Japan1" }); + result.Add(new Object[] { "UniJIS2004-UTF32-V", "Japan1" }); + result.Add(new Object[] { "UniJIS-UCS2-H", "Japan1" }); + result.Add(new Object[] { "UniJIS-UCS2-HW-H", "Japan1" }); + result.Add(new Object[] { "UniJIS-UCS2-HW-V", "Japan1" }); + result.Add(new Object[] { "UniJIS-UCS2-V", "Japan1" }); + result.Add(new Object[] { "UniJIS-UTF8-H", "Japan1" }); + result.Add(new Object[] { "UniJIS-UTF8-V", "Japan1" }); + result.Add(new Object[] { "UniJIS-UTF16-H", "Japan1" }); + result.Add(new Object[] { "UniJIS-UTF16-V", "Japan1" }); + result.Add(new Object[] { "UniJIS-UTF32-H", "Japan1" }); + result.Add(new Object[] { "UniJIS-UTF32-V", "Japan1" }); + result.Add(new Object[] { "UniJISPro-UCS2-HW-V", "Japan1" }); + result.Add(new Object[] { "UniJISPro-UCS2-V", "Japan1" }); + result.Add(new Object[] { "UniJISPro-UTF8-V", "Japan1" }); + result.Add(new Object[] { "UniJISX0213-UTF32-H", "Japan1" }); + result.Add(new Object[] { "UniJISX0213-UTF32-V", "Japan1" }); + result.Add(new Object[] { "UniJISX02132004-UTF32-H", "Japan1" }); + result.Add(new Object[] { "UniJISX02132004-UTF32-V", "Japan1" }); + result.Add(new Object[] { "UniKS-UCS2-H", "Korea1" }); + result.Add(new Object[] { "UniKS-UCS2-V", "Korea1" }); + result.Add(new Object[] { "UniKS-UTF8-H", "Korea1" }); + result.Add(new Object[] { "UniKS-UTF8-V", "Korea1" }); + result.Add(new Object[] { "UniKS-UTF16-H", "Korea1" }); + result.Add(new Object[] { "UniKS-UTF16-V", "Korea1" }); + result.Add(new Object[] { "UniKS-UTF32-H", "Korea1" }); + result.Add(new Object[] { "UniKS-UTF32-V", "Korea1" }); + result.Add(new Object[] { "V", "Japan1" }); + result.Add(new Object[] { "WP-Symbol", "Japan1" }); + result.Add(new Object[] { ResourceTestUtil.NormalizeResourceName("toUnicode/Adobe-CNS1-UCS2"), "Adobe_CNS1_UCS2" + }); + result.Add(new Object[] { ResourceTestUtil.NormalizeResourceName("toUnicode/Adobe-GB1-UCS2"), "Adobe_GB1_UCS2" + }); + result.Add(new Object[] { ResourceTestUtil.NormalizeResourceName("toUnicode/Adobe-Japan1-UCS2"), "Adobe_Japan1_UCS2" + }); + result.Add(new Object[] { ResourceTestUtil.NormalizeResourceName("toUnicode/Adobe-Korea1-UCS2"), "Adobe_Korea1_UCS2" + }); + result.Add(new Object[] { ResourceTestUtil.NormalizeResourceName("toUnicode/Adobe-KR-UCS2"), "Adobe_KR_UCS2" + }); + return result; + } + + private void CheckFontAsianCmap(String cmapName, String ordering) { + AbstractCMap cmap = CjkResourceLoader.GetUni2CidCmap(cmapName); + NUnit.Framework.Assert.IsTrue(cmapName.EndsWith(cmap.GetName())); + NUnit.Framework.Assert.AreEqual(ordering, cmap.GetOrdering()); + } + } +} diff --git a/itext.tests/itext.io.tests/itext/io/font/ResourceTestUtil.cs b/itext.tests/itext.io.tests/itext/io/font/ResourceTestUtil.cs new file mode 100644 index 0000000000..62e1078442 --- /dev/null +++ b/itext.tests/itext.io.tests/itext/io/font/ResourceTestUtil.cs @@ -0,0 +1,34 @@ +/* + This file is part of the iText (R) project. + Copyright (c) 1998-2024 Apryse Group NV + Authors: Apryse Software. + + This program is offered under a commercial and under the AGPL license. + For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + + AGPL licensing: + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + */ +using System; + +namespace iText.IO.Font { +//\cond DO_NOT_DOCUMENT + internal class ResourceTestUtil { + public static String NormalizeResourceName(String resourceName) { + string result = resourceName.Replace("toUnicode/", "ToUnicode."); + return result; + } + } +//\endcond +} diff --git a/itext.tests/itext.io.tests/itext/io/font/TrueTypeFontTest.cs b/itext.tests/itext.io.tests/itext/io/font/TrueTypeFontTest.cs index 92292c0839..9635c7f5b1 100644 --- a/itext.tests/itext.io.tests/itext/io/font/TrueTypeFontTest.cs +++ b/itext.tests/itext.io.tests/itext/io/font/TrueTypeFontTest.cs @@ -79,5 +79,25 @@ public virtual void NotoSansScMapGlyphsCidsToGidsTest() { NUnit.Framework.Assert.AreEqual(1, actualResult.Count); NUnit.Framework.Assert.IsTrue(actualResult.Contains(charGidInFont)); } + + [NUnit.Framework.Test] + public virtual void CmapPlatform0PlatEnc3Format4Test() { + FontProgram fontProgram = FontProgramFactory.CreateFont(SOURCE_FOLDER + "glyphs.ttf"); + CheckCmapTableEntry(fontProgram, 'f', 2); + CheckCmapTableEntry(fontProgram, 'i', 3); + } + + [NUnit.Framework.Test] + public virtual void CmapPlatform0PlatEnc3Format6Test() { + FontProgram fontProgram = FontProgramFactory.CreateFont(SOURCE_FOLDER + "glyphs-fmt-6.ttf"); + CheckCmapTableEntry(fontProgram, 'f', 2); + CheckCmapTableEntry(fontProgram, 'i', 3); + } + + private void CheckCmapTableEntry(FontProgram fontProgram, char uniChar, int expectedGlyphId) { + Glyph glyph = fontProgram.GetGlyph(uniChar); + NUnit.Framework.Assert.AreEqual(expectedGlyphId, glyph.GetCode()); + NUnit.Framework.Assert.AreEqual(new char[] { uniChar }, glyph.GetUnicodeChars()); + } } } diff --git a/itext/itext.kernel/itext/kernel/pdf/IConformanceLevel.cs b/itext.tests/itext.io.tests/itext/io/font/cmap/CMapToUnicodeTest.cs similarity index 66% rename from itext/itext.kernel/itext/kernel/pdf/IConformanceLevel.cs rename to itext.tests/itext.io.tests/itext/io/font/cmap/CMapToUnicodeTest.cs index 85515e8689..ae6de29c43 100644 --- a/itext/itext.kernel/itext/kernel/pdf/IConformanceLevel.cs +++ b/itext.tests/itext.io.tests/itext/io/font/cmap/CMapToUnicodeTest.cs @@ -20,15 +20,16 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ -namespace iText.Kernel.Pdf { - /// Interface for PDF conformance level. - /// - /// Interface for PDF conformance level. - /// - /// Conformance levels are extended PDF specifications that define subsets of PDF - /// functionality. An example of a conformance level is PDF/A, which is used for long-term archiving - /// and PDF/UA, which is used for accessible documents. - /// - public interface IConformanceLevel { +using iText.Test; + +namespace iText.IO.Font.Cmap { + [NUnit.Framework.Category("UnitTest")] + public class CMapToUnicodeTest : ExtendedITextTest { + [NUnit.Framework.Test] + public virtual void EmptyCmapVarTest() { + NUnit.Framework.Assert.IsNotNull(CMapToUnicode.EMPTY_CMAP); + NUnit.Framework.Assert.IsFalse(CMapToUnicode.EMPTY_CMAP.HasByteMappings(), "Cmap has no two byte mappings" + ); + } } } diff --git a/itext.tests/itext.io.tests/itext/io/font/otf/ActualTextIteratorTest.cs b/itext.tests/itext.io.tests/itext/io/font/otf/ActualTextIteratorTest.cs index 86d23cc879..e94e996756 100644 --- a/itext.tests/itext.io.tests/itext/io/font/otf/ActualTextIteratorTest.cs +++ b/itext.tests/itext.io.tests/itext/io/font/otf/ActualTextIteratorTest.cs @@ -34,7 +34,50 @@ public virtual void TestActualTestParts() { ActualTextIterator actualTextIterator = new ActualTextIterator(glyphLine); GlyphLine.GlyphLinePart part = actualTextIterator.Next(); // When actual text is the same as the result by text extraction, we should omit redundant actual text in the content stream - NUnit.Framework.Assert.IsNull(part.actualText); + NUnit.Framework.Assert.IsNull(part.GetActualText()); + } + + [NUnit.Framework.Test] + public virtual void NextCurrentResNullTest() { + Glyph glyph = new Glyph(200, 200, '\u002d'); + GlyphLine glyphLine = new GlyphLine(JavaUtil.ArraysAsList(glyph, null, glyph)); + glyphLine.SetActualText(0, 1, "\u002d"); + ActualTextIterator actualTextIterator = new ActualTextIterator(glyphLine); + actualTextIterator.Next(); + GlyphLine.GlyphLinePart secondNext = actualTextIterator.Next(); + NUnit.Framework.Assert.IsNull(secondNext); + } + + [NUnit.Framework.Test] + public virtual void NextIterationTest() { + Glyph glyph = new Glyph(200, 200, '\u002d'); + GlyphLine glyphLine = new GlyphLine(JavaUtil.ArraysAsList(glyph, glyph, glyph)); + glyphLine.SetActualText(0, 1, "\u002d"); + ActualTextIterator actualTextIterator = new ActualTextIterator(glyphLine); + GlyphLine.GlyphLinePart next = actualTextIterator.Next(); + NUnit.Framework.Assert.AreEqual(3, next.GetEnd()); + } + + [NUnit.Framework.Test] + public virtual void NextWithNegativeEndTest() { + Glyph glyph = new Glyph(200, 200, '\u002d'); + GlyphLine glyphLine = new GlyphLine(JavaUtil.ArraysAsList(glyph, glyph, glyph)); + glyphLine.SetActualText(0, 1, "\u002d"); + glyphLine.SetEnd(-1); + ActualTextIterator actualTextIterator = new ActualTextIterator(glyphLine); + GlyphLine.GlyphLinePart next = actualTextIterator.Next(); + NUnit.Framework.Assert.IsNull(next); + } + + [NUnit.Framework.Test] + public virtual void NextWithInvalidUnicodeTest() { + Glyph glyph = new Glyph(200, 200, 0); + Glyph glyphinvalid = new Glyph(200, 200, null); + GlyphLine glyphLine = new GlyphLine(JavaUtil.ArraysAsList(glyph, glyphinvalid)); + glyphLine.SetActualText(1, 2, "X"); + ActualTextIterator actualTextIterator = new ActualTextIterator(glyphLine); + GlyphLine.GlyphLinePart next = actualTextIterator.Next(); + NUnit.Framework.Assert.IsNull(next.GetActualText()); } } } diff --git a/itext/itext.kernel/itext/kernel/events/IEventHandler.cs b/itext.tests/itext.io.tests/itext/io/font/otf/GlyphLinePartTest.cs similarity index 58% rename from itext/itext.kernel/itext/kernel/events/IEventHandler.cs rename to itext.tests/itext.io.tests/itext/io/font/otf/GlyphLinePartTest.cs index e7b21b85fc..c5af958300 100644 --- a/itext/itext.kernel/itext/kernel/events/IEventHandler.cs +++ b/itext.tests/itext.io.tests/itext/io/font/otf/GlyphLinePartTest.cs @@ -20,19 +20,20 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ -namespace iText.Kernel.Events { - /// Interface for handling events. - /// - /// Interface for handling events. EventHandlers are added to the - /// . - /// - public interface IEventHandler { - /// Hook for handling events. - /// - /// Hook for handling events. Implementations can access the PdfDocument instance - /// associated to the specified Event or, if available, the PdfPage instance. - /// - /// the Event that needs to be processed - void HandleEvent(Event @event); +using iText.Test; + +namespace iText.IO.Font.Otf { + [NUnit.Framework.Category("UnitTest")] + public class GlyphLinePartTest : ExtendedITextTest { + [NUnit.Framework.Test] + public virtual void CustomGlyphLinePartTest() { + GlyphLine.GlyphLinePart part = new GlyphLine.GlyphLinePart(0, 4); + part.SetStart(1); + part.SetEnd(5); + part.SetReversed(false); + NUnit.Framework.Assert.AreEqual(1, part.GetStart()); + NUnit.Framework.Assert.AreEqual(5, part.GetEnd()); + NUnit.Framework.Assert.IsFalse(part.IsReversed()); + } } } diff --git a/itext.tests/itext.io.tests/itext/io/font/otf/GlyphLineTest.cs b/itext.tests/itext.io.tests/itext/io/font/otf/GlyphLineTest.cs index a825953dbe..0c40cdee58 100644 --- a/itext.tests/itext.io.tests/itext/io/font/otf/GlyphLineTest.cs +++ b/itext.tests/itext.io.tests/itext/io/font/otf/GlyphLineTest.cs @@ -30,6 +30,9 @@ You should have received a copy of the GNU Affero General Public License namespace iText.IO.Font.Otf { [NUnit.Framework.Category("UnitTest")] public class GlyphLineTest : ExtendedITextTest { + public static readonly String FREESANS_FONT_PATH = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + .CurrentContext.TestDirectory) + "/resources/itext/io/font/otf/FreeSans.ttf"; + private static IList ConstructGlyphListFromString(String text, TrueTypeFont font) { IList glyphList = new List(); char[] chars = text.ToCharArray(); @@ -49,48 +52,42 @@ public virtual void TestEquals() { >(JavaUtil.ArraysAsList(actualText)), 0, 1); one.Add(glyph); two.Add(glyph); - one.end++; - two.end++; + one.SetEnd(one.GetEnd() + 1); + two.SetEnd(two.GetEnd() + 1); NUnit.Framework.Assert.IsTrue(one.Equals(two)); } [NUnit.Framework.Test] public virtual void TestOtherLinesAddition() { - byte[] ttf = StreamUtil.InputStreamToArray(FileUtil.GetInputStreamForFile(iText.Test.TestUtil.GetParentProjectDirectory - (NUnit.Framework.TestContext.CurrentContext.TestDirectory) + "/resources/itext/io/font/otf/FreeSans.ttf" - )); - TrueTypeFont font = new TrueTypeFont(ttf); + TrueTypeFont font = InitializeFont(); GlyphLine containerLine = new GlyphLine(ConstructGlyphListFromString("Viva France!", font)); GlyphLine childLine1 = new GlyphLine(ConstructGlyphListFromString(" Liberte", font)); containerLine.Add(childLine1); - NUnit.Framework.Assert.AreEqual(containerLine.end, 12); - containerLine.end = 20; + NUnit.Framework.Assert.AreEqual(12, containerLine.GetEnd()); + containerLine.SetEnd(20); GlyphLine childLine2 = new GlyphLine(ConstructGlyphListFromString(" Egalite", font)); containerLine.Add(childLine2); - NUnit.Framework.Assert.AreEqual(containerLine.end, 20); - containerLine.start = 10; + NUnit.Framework.Assert.AreEqual(20, containerLine.GetEnd()); + containerLine.SetStart(10); GlyphLine childLine3 = new GlyphLine(ConstructGlyphListFromString(" Fraternite", font)); containerLine.Add(childLine3); - NUnit.Framework.Assert.AreEqual(containerLine.start, 10); - containerLine.start = 0; + NUnit.Framework.Assert.AreEqual(10, containerLine.GetStart()); + containerLine.SetStart(0); containerLine.Add(ConstructGlyphListFromString("!", font)[0]); - containerLine.end = 40; - NUnit.Framework.Assert.AreEqual(containerLine.glyphs.Count, 40); + containerLine.SetEnd(40); + NUnit.Framework.Assert.AreEqual(40, containerLine.glyphs.Count); } [NUnit.Framework.Test] public virtual void TestAdditionWithActualText() { - byte[] ttf = StreamUtil.InputStreamToArray(FileUtil.GetInputStreamForFile(iText.Test.TestUtil.GetParentProjectDirectory - (NUnit.Framework.TestContext.CurrentContext.TestDirectory) + "/resources/itext/io/font/otf/FreeSans.ttf" - )); - TrueTypeFont font = new TrueTypeFont(ttf); + TrueTypeFont font = InitializeFont(); IList glyphs = ConstructGlyphListFromString("Viva France!", font); GlyphLine containerLine = new GlyphLine(glyphs); NUnit.Framework.Assert.IsNull(containerLine.actualText); containerLine.SetActualText(0, 1, "TEST"); NUnit.Framework.Assert.IsNotNull(containerLine.actualText); NUnit.Framework.Assert.AreEqual(12, containerLine.actualText.Count); - NUnit.Framework.Assert.AreEqual("TEST", containerLine.actualText[0].value); + NUnit.Framework.Assert.AreEqual("TEST", containerLine.actualText[0].GetValue()); containerLine.Add(new GlyphLine(glyphs)); NUnit.Framework.Assert.AreEqual(24, containerLine.actualText.Count); for (int i = 13; i < 24; i++) { @@ -100,55 +97,46 @@ public virtual void TestAdditionWithActualText() { [NUnit.Framework.Test] public virtual void TestOtherLinesWithActualTextAddition() { - byte[] ttf = StreamUtil.InputStreamToArray(FileUtil.GetInputStreamForFile(iText.Test.TestUtil.GetParentProjectDirectory - (NUnit.Framework.TestContext.CurrentContext.TestDirectory) + "/resources/itext/io/font/otf/FreeSans.ttf" - )); - TrueTypeFont font = new TrueTypeFont(ttf); + TrueTypeFont font = InitializeFont(); GlyphLine containerLine = new GlyphLine(ConstructGlyphListFromString("France", font)); GlyphLine childLine = new GlyphLine(ConstructGlyphListFromString("---Liberte", font)); childLine.SetActualText(3, 10, "Viva"); containerLine.Add(childLine); - containerLine.end = 16; + containerLine.SetEnd(16); for (int i = 0; i < 9; i++) { NUnit.Framework.Assert.IsNull(containerLine.actualText[i]); } for (int i = 9; i < 16; i++) { - NUnit.Framework.Assert.AreEqual("Viva", containerLine.actualText[i].value); + NUnit.Framework.Assert.AreEqual("Viva", containerLine.actualText[i].GetValue()); } NUnit.Framework.Assert.AreEqual("France---Viva", containerLine.ToString()); } [NUnit.Framework.Test] public virtual void TestOtherLinesWithActualTextAddition02() { - byte[] ttf = StreamUtil.InputStreamToArray(FileUtil.GetInputStreamForFile(iText.Test.TestUtil.GetParentProjectDirectory - (NUnit.Framework.TestContext.CurrentContext.TestDirectory) + "/resources/itext/io/font/otf/FreeSans.ttf" - )); - TrueTypeFont font = new TrueTypeFont(ttf); + TrueTypeFont font = InitializeFont(); GlyphLine containerLine = new GlyphLine(ConstructGlyphListFromString("France", font)); containerLine.SetActualText(1, 5, "id"); GlyphLine childLine = new GlyphLine(ConstructGlyphListFromString("---Liberte", font)); childLine.SetActualText(3, 10, "Viva"); containerLine.Add(childLine); - containerLine.end = 16; + containerLine.SetEnd(16); NUnit.Framework.Assert.IsNull(containerLine.actualText[0]); for (int i = 1; i < 5; i++) { - NUnit.Framework.Assert.AreEqual("id", containerLine.actualText[i].value); + NUnit.Framework.Assert.AreEqual("id", containerLine.actualText[i].GetValue()); } for (int i = 5; i < 9; i++) { NUnit.Framework.Assert.IsNull(containerLine.actualText[i]); } for (int i = 9; i < 16; i++) { - NUnit.Framework.Assert.AreEqual("Viva", containerLine.actualText[i].value); + NUnit.Framework.Assert.AreEqual("Viva", containerLine.actualText[i].GetValue()); } NUnit.Framework.Assert.AreEqual("Fide---Viva", containerLine.ToString()); } [NUnit.Framework.Test] public virtual void TestContentReplacingWithNullActualText() { - byte[] ttf = StreamUtil.InputStreamToArray(FileUtil.GetInputStreamForFile(iText.Test.TestUtil.GetParentProjectDirectory - (NUnit.Framework.TestContext.CurrentContext.TestDirectory) + "/resources/itext/io/font/otf/FreeSans.ttf" - )); - TrueTypeFont font = new TrueTypeFont(ttf); + TrueTypeFont font = InitializeFont(); GlyphLine lineToBeReplaced = new GlyphLine(ConstructGlyphListFromString("Byelorussia", font)); lineToBeReplaced.SetActualText(1, 2, "e"); GlyphLine lineToBeCopied = new GlyphLine(ConstructGlyphListFromString("Belarus", font)); @@ -161,49 +149,219 @@ public virtual void TestContentReplacingWithNullActualText() { public virtual void TestActualTextForSubstitutedGlyphProcessingInSubstituteOneToMany01() { String expectedActualTextForFirstGlyph = "0"; String expectedActualTextForSecondGlyph = "A"; - byte[] ttf = StreamUtil.InputStreamToArray(FileUtil.GetInputStreamForFile(iText.Test.TestUtil.GetParentProjectDirectory - (NUnit.Framework.TestContext.CurrentContext.TestDirectory) + "/resources/itext/io/font/otf/FreeSans.ttf" - )); - TrueTypeFont font = new TrueTypeFont(ttf); + TrueTypeFont font = InitializeFont(); // no actual text for the second glyph is set - it should be created during substitution GlyphLine line = new GlyphLine(ConstructGlyphListFromString("AA", font)); line.SetActualText(0, 1, expectedActualTextForFirstGlyph); - line.idx = 1; + line.SetIdx(1); line.SubstituteOneToMany(font.GetGsubTable(), new int[] { 39, 40 }); NUnit.Framework.Assert.IsNotNull(line.actualText); NUnit.Framework.Assert.AreEqual(3, line.actualText.Count); NUnit.Framework.Assert.AreSame(line.actualText[1], line.actualText[2]); - NUnit.Framework.Assert.AreEqual(expectedActualTextForSecondGlyph, line.actualText[1].value); + NUnit.Framework.Assert.AreEqual(expectedActualTextForSecondGlyph, line.actualText[1].GetValue()); // check that it hasn't been corrupted - NUnit.Framework.Assert.AreEqual(expectedActualTextForFirstGlyph, line.actualText[0].value); + NUnit.Framework.Assert.AreEqual(expectedActualTextForFirstGlyph, line.actualText[0].GetValue()); } [NUnit.Framework.Test] public virtual void TestActualTextForSubstitutedGlyphProcessingInSubstituteOneToMany02() { String expectedActualTextForFirstGlyph = "A"; - byte[] ttf = StreamUtil.InputStreamToArray(FileUtil.GetInputStreamForFile(iText.Test.TestUtil.GetParentProjectDirectory - (NUnit.Framework.TestContext.CurrentContext.TestDirectory) + "/resources/itext/io/font/otf/FreeSans.ttf" - )); - TrueTypeFont font = new TrueTypeFont(ttf); + TrueTypeFont font = InitializeFont(); GlyphLine line = new GlyphLine(ConstructGlyphListFromString("A", font)); line.SetActualText(0, 1, expectedActualTextForFirstGlyph); line.SubstituteOneToMany(font.GetGsubTable(), new int[] { 39, 40 }); NUnit.Framework.Assert.IsNotNull(line.actualText); NUnit.Framework.Assert.AreEqual(2, line.actualText.Count); NUnit.Framework.Assert.AreSame(line.actualText[0], line.actualText[1]); - NUnit.Framework.Assert.AreEqual(expectedActualTextForFirstGlyph, line.actualText[0].value); + NUnit.Framework.Assert.AreEqual(expectedActualTextForFirstGlyph, line.actualText[0].GetValue()); } [NUnit.Framework.Test] public virtual void TestActualTextForSubstitutedGlyphProcessingInSubstituteOneToMany03() { - byte[] ttf = StreamUtil.InputStreamToArray(FileUtil.GetInputStreamForFile(iText.Test.TestUtil.GetParentProjectDirectory - (NUnit.Framework.TestContext.CurrentContext.TestDirectory) + "/resources/itext/io/font/otf/FreeSans.ttf" - )); - TrueTypeFont font = new TrueTypeFont(ttf); + TrueTypeFont font = InitializeFont(); // no actual text is set GlyphLine line = new GlyphLine(ConstructGlyphListFromString("A", font)); line.SubstituteOneToMany(font.GetGsubTable(), new int[] { 39, 40 }); NUnit.Framework.Assert.IsNull(line.actualText); } + + [NUnit.Framework.Test] + public virtual void DefaultConstructorTest() { + GlyphLine glyphLine = new GlyphLine(); + NUnit.Framework.Assert.AreEqual(0, glyphLine.GetStart()); + NUnit.Framework.Assert.AreEqual(0, glyphLine.GetEnd()); + NUnit.Framework.Assert.AreEqual(0, glyphLine.GetIdx()); + } + + [NUnit.Framework.Test] + public virtual void OtherConstructorTest() { + TrueTypeFont font = InitializeFont(); + GlyphLine otherLine = new GlyphLine(ConstructGlyphListFromString("A test otherLine", font)); + GlyphLine glyphLine = new GlyphLine(otherLine); + NUnit.Framework.Assert.AreEqual(0, glyphLine.GetStart()); + NUnit.Framework.Assert.AreEqual(16, glyphLine.GetEnd()); + NUnit.Framework.Assert.AreEqual(0, glyphLine.GetIdx()); + NUnit.Framework.Assert.AreEqual("A test otherLine", glyphLine.ToString()); + } + + [NUnit.Framework.Test] + public virtual void StartEndConstructorTest() { + TrueTypeFont font = InitializeFont(); + GlyphLine otherLine = new GlyphLine(ConstructGlyphListFromString("A test otherLine", font)); + GlyphLine glyphLine = new GlyphLine(otherLine, 2, 16); + NUnit.Framework.Assert.AreEqual(0, glyphLine.GetStart()); + NUnit.Framework.Assert.AreEqual(14, glyphLine.GetEnd()); + NUnit.Framework.Assert.AreEqual(-2, glyphLine.GetIdx()); + NUnit.Framework.Assert.AreEqual("test otherLine", glyphLine.ToString()); + } + + [NUnit.Framework.Test] + public virtual void StartEndAndActualTextTest() { + TrueTypeFont font = InitializeFont(); + GlyphLine glyphLine = new GlyphLine(ConstructGlyphListFromString("XXX otherLine", font)); + glyphLine.SetActualText(0, 3, "txt"); + GlyphLine other = new GlyphLine(glyphLine, 0, 13); + NUnit.Framework.Assert.AreEqual("txt otherLine", other.ToString()); + } + + [NUnit.Framework.Test] + public virtual void CopyGlyphLineTest() { + TrueTypeFont font = InitializeFont(); + GlyphLine glyphLine = new GlyphLine(ConstructGlyphListFromString("A test otherLine", font)); + GlyphLine copyLine = glyphLine.Copy(2, 6); + NUnit.Framework.Assert.AreEqual(0, copyLine.GetStart()); + NUnit.Framework.Assert.AreEqual(4, copyLine.GetEnd()); + NUnit.Framework.Assert.AreEqual(0, copyLine.GetIdx()); + NUnit.Framework.Assert.AreEqual("test", copyLine.ToString()); + } + + [NUnit.Framework.Test] + public virtual void CopyWithActualTextGlyphLineTest() { + TrueTypeFont font = InitializeFont(); + GlyphLine glyphLine = new GlyphLine(ConstructGlyphListFromString("XXX otherLine", font)); + glyphLine.SetActualText(0, 3, "txt"); + GlyphLine copyLine = glyphLine.Copy(0, 3); + NUnit.Framework.Assert.AreEqual(0, copyLine.GetStart()); + NUnit.Framework.Assert.AreEqual(3, copyLine.GetEnd()); + NUnit.Framework.Assert.AreEqual(0, copyLine.GetIdx()); + NUnit.Framework.Assert.AreEqual("txt", copyLine.ToString()); + } + + [NUnit.Framework.Test] + public virtual void AddIndexedGlyphLineTest() { + TrueTypeFont font = InitializeFont(); + GlyphLine glyphLine = new GlyphLine(ConstructGlyphListFromString("A test otherLine", font)); + Glyph glyph = new Glyph(200, 200, 200); + glyphLine.Add(0, glyph); + NUnit.Framework.Assert.AreEqual(0, glyphLine.GetStart()); + NUnit.Framework.Assert.AreEqual(16, glyphLine.GetEnd()); + NUnit.Framework.Assert.AreEqual(0, glyphLine.GetIdx()); + NUnit.Framework.Assert.AreEqual("ÈA test otherLin", glyphLine.ToString()); + } + + [NUnit.Framework.Test] + public virtual void AddIndexedGlyphLineActualTextTest() { + TrueTypeFont font = InitializeFont(); + GlyphLine glyphLine = new GlyphLine(ConstructGlyphListFromString("XXX otherLine", font)); + glyphLine.SetActualText(0, 3, "txt"); + Glyph glyph = new Glyph(200, 200, 200); + glyphLine.Add(0, glyph); + NUnit.Framework.Assert.AreEqual(0, glyphLine.GetStart()); + NUnit.Framework.Assert.AreEqual(13, glyphLine.GetEnd()); + NUnit.Framework.Assert.AreEqual(0, glyphLine.GetIdx()); + NUnit.Framework.Assert.AreEqual("Ètxt otherLin", glyphLine.ToString()); + } + + [NUnit.Framework.Test] + public virtual void ReplaceGlyphInLineTest() { + TrueTypeFont font = InitializeFont(); + GlyphLine glyphLine = new GlyphLine(ConstructGlyphListFromString("A test otherLine", font)); + Glyph glyph = new Glyph(200, 200, 200); + glyphLine.Set(0, glyph); + NUnit.Framework.Assert.AreEqual(0, glyphLine.GetStart()); + NUnit.Framework.Assert.AreEqual(16, glyphLine.GetEnd()); + NUnit.Framework.Assert.AreEqual(0, glyphLine.GetIdx()); + NUnit.Framework.Assert.AreEqual("È test otherLine", glyphLine.ToString()); + } + + [NUnit.Framework.Test] + public virtual void ReplaceGlyphLineNoActualTextTest() { + TrueTypeFont font = InitializeFont(); + GlyphLine glyphLine = new GlyphLine(ConstructGlyphListFromString("A test otherLine", font)); + GlyphLine replaceLine = new GlyphLine(ConstructGlyphListFromString("different text", font)); + replaceLine.SetActualText(0, 14, "different text"); + glyphLine.ReplaceContent(replaceLine); + NUnit.Framework.Assert.AreEqual(0, glyphLine.GetStart()); + NUnit.Framework.Assert.AreEqual(14, glyphLine.GetEnd()); + NUnit.Framework.Assert.AreEqual(0, glyphLine.GetIdx()); + NUnit.Framework.Assert.AreEqual("different text", glyphLine.ToString()); + } + + [NUnit.Framework.Test] + public virtual void ReplaceGlyphLineWithActualTextTest() { + TrueTypeFont font = InitializeFont(); + GlyphLine glyphLine = new GlyphLine(ConstructGlyphListFromString("A test otherLine", font)); + glyphLine.SetActualText(0, 14, "A test otherLine"); + GlyphLine replaceLine = new GlyphLine(ConstructGlyphListFromString("different text", font)); + replaceLine.SetActualText(0, 14, "different text"); + glyphLine.ReplaceContent(replaceLine); + NUnit.Framework.Assert.AreEqual(0, glyphLine.GetStart()); + NUnit.Framework.Assert.AreEqual(14, glyphLine.GetEnd()); + NUnit.Framework.Assert.AreEqual(0, glyphLine.GetIdx()); + NUnit.Framework.Assert.AreEqual("different text", glyphLine.ToString()); + } + + [NUnit.Framework.Test] + public virtual void NullEqualsTest() { + TrueTypeFont font = InitializeFont(); + GlyphLine glyphLine = new GlyphLine(ConstructGlyphListFromString("A test otherLine", font)); + bool equals = glyphLine.Equals(null); + NUnit.Framework.Assert.IsFalse(equals); + } + + [NUnit.Framework.Test] + public virtual void EqualsItselfTest() { + TrueTypeFont font = InitializeFont(); + GlyphLine glyphLine = new GlyphLine(ConstructGlyphListFromString("A test otherLine", font)); + bool equals = glyphLine.Equals(glyphLine); + NUnit.Framework.Assert.IsTrue(equals); + } + + [NUnit.Framework.Test] + public virtual void EqualGlyphLinesTest() { + TrueTypeFont font = InitializeFont(); + GlyphLine first = new GlyphLine(ConstructGlyphListFromString("A test otherLine", font)); + first.SetActualText(0, 14, "A test otherLine"); + GlyphLine second = new GlyphLine(ConstructGlyphListFromString("A test otherLine", font)); + second.SetActualText(0, 14, "A test otherLine"); + bool equals = first.Equals(second); + NUnit.Framework.Assert.IsTrue(equals); + } + + [NUnit.Framework.Test] + public virtual void DiffStartEndEqualsTest() { + TrueTypeFont font = InitializeFont(); + GlyphLine first = new GlyphLine(ConstructGlyphListFromString("A test otherLine", font)); + GlyphLine second = new GlyphLine(ConstructGlyphListFromString("A test otherLine", font)); + second.SetEnd(3); + second.SetStart(1); + bool equals = first.Equals(second); + NUnit.Framework.Assert.IsFalse(equals); + } + + [NUnit.Framework.Test] + public virtual void DiffActualTextEqualsTest() { + TrueTypeFont font = InitializeFont(); + GlyphLine first = new GlyphLine(ConstructGlyphListFromString("A test otherLine", font)); + first.SetActualText(0, 3, "txt"); + GlyphLine second = new GlyphLine(ConstructGlyphListFromString("A test otherLine", font)); + bool equals = first.Equals(second); + NUnit.Framework.Assert.IsFalse(equals); + } + + private TrueTypeFont InitializeFont() { + byte[] ttf = StreamUtil.InputStreamToArray(FileUtil.GetInputStreamForFile(FREESANS_FONT_PATH)); + return new TrueTypeFont(ttf); + } } } diff --git a/itext.tests/itext.io.tests/itext/io/font/otf/GposLookupType1Test.cs b/itext.tests/itext.io.tests/itext/io/font/otf/GposLookupType1Test.cs index 6f9f48bc91..cc9835a795 100644 --- a/itext.tests/itext.io.tests/itext/io/font/otf/GposLookupType1Test.cs +++ b/itext.tests/itext.io.tests/itext/io/font/otf/GposLookupType1Test.cs @@ -41,7 +41,7 @@ public virtual void VerifyXAdvanceIsAppliedSubFormat1() { IList glyphs = JavaUtil.ArraysAsList(new Glyph(fontProgram.GetGlyphByCode(174)), new Glyph(fontProgram .GetGlyphByCode(5))); GlyphLine gl = new GlyphLine(glyphs); - gl.idx = 0; + gl.SetIdx(0); NUnit.Framework.Assert.AreEqual(0, gl.Get(0).GetXAdvance()); NUnit.Framework.Assert.IsTrue(lookup.TransformOne(gl)); NUnit.Framework.Assert.AreEqual(219, gl.Get(0).GetXAdvance()); @@ -56,7 +56,7 @@ public virtual void VerifyPositionIsNotAppliedForIrrelevantGlyphSubFormat1() { IList glyphs = JavaUtil.ArraysAsList(new Glyph(fontProgram.GetGlyphByCode(5)), new Glyph(fontProgram .GetGlyphByCode(174))); GlyphLine gl = new GlyphLine(glyphs); - gl.idx = 0; + gl.SetIdx(0); NUnit.Framework.Assert.AreEqual(0, gl.Get(0).GetXAdvance()); NUnit.Framework.Assert.IsFalse(lookup.TransformOne(gl)); NUnit.Framework.Assert.AreEqual(0, gl.Get(0).GetXAdvance()); diff --git a/itext.tests/itext.io.tests/itext/io/font/otf/GposLookupType2Test.cs b/itext.tests/itext.io.tests/itext/io/font/otf/GposLookupType2Test.cs new file mode 100644 index 0000000000..63b1c55584 --- /dev/null +++ b/itext.tests/itext.io.tests/itext/io/font/otf/GposLookupType2Test.cs @@ -0,0 +1,63 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using System.Collections.Generic; +using iText.Commons.Utils; +using iText.IO.Font; +using iText.Test; + +namespace iText.IO.Font.Otf { + [NUnit.Framework.Category("IntegrationTest")] + public class GposLookupType2Test : ExtendedITextTest { + private static readonly String RESOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + .CurrentContext.TestDirectory) + "/resources/itext/io/font/otf/GposLookupType2Test/"; + + private static readonly String DEJAVU_FONT_PATH = RESOURCE_FOLDER + "DejaVuSans.ttf"; + + [NUnit.Framework.Test] + public virtual void IdxEqualToEndLineGpos2Test() { + TrueTypeFont font = new TrueTypeFont(DEJAVU_FONT_PATH); + GlyphPositioningTableReader gposTableReader = font.GetGposTable(); + GposLookupType2 lookup = (GposLookupType2)gposTableReader.GetLookupTable(15); + IList glyphs = JavaUtil.ArraysAsList(new Glyph(font.GetGlyphByCode(174)), new Glyph(font.GetGlyphByCode + (5))); + GlyphLine gl = new GlyphLine(glyphs); + gl.SetIdx(2); + bool transform = lookup.TransformOne(gl); + NUnit.Framework.Assert.IsFalse(transform); + } + + [NUnit.Framework.Test] + public virtual void IdxSmallerThanEndLineGpos2Test() { + TrueTypeFont font = new TrueTypeFont(DEJAVU_FONT_PATH); + GlyphPositioningTableReader gposTableReader = font.GetGposTable(); + GposLookupType2 lookup = (GposLookupType2)gposTableReader.GetLookupTable(15); + IList glyphs = JavaUtil.ArraysAsList(new Glyph(font.GetGlyphByCode(174)), new Glyph(font.GetGlyphByCode + (5))); + GlyphLine gl = new GlyphLine(glyphs); + gl.SetIdx(0); + bool transform = lookup.TransformOne(gl); + NUnit.Framework.Assert.IsFalse(transform); + } + } +} diff --git a/itext.tests/itext.io.tests/itext/io/font/otf/GposLookupType4Test.cs b/itext.tests/itext.io.tests/itext/io/font/otf/GposLookupType4Test.cs index 05051cb972..d42cdbbda2 100644 --- a/itext.tests/itext.io.tests/itext/io/font/otf/GposLookupType4Test.cs +++ b/itext.tests/itext.io.tests/itext/io/font/otf/GposLookupType4Test.cs @@ -41,7 +41,7 @@ public virtual void VerifyMarkToBaseAttachment() { IList glyphs = JavaUtil.ArraysAsList(new Glyph(fontProgram.GetGlyphByCode(163)), new Glyph(fontProgram .GetGlyphByCode(207)), new Glyph(fontProgram.GetGlyphByCode(213))); GlyphLine gl = new GlyphLine(glyphs); - gl.idx = 2; + gl.SetIdx(2); NUnit.Framework.Assert.AreEqual(0, gl.Get(2).GetXPlacement()); NUnit.Framework.Assert.AreEqual(0, gl.Get(2).GetAnchorDelta()); lookup.TransformOne(gl); diff --git a/itext.tests/itext.io.tests/itext/io/font/otf/GposLookupType5Test.cs b/itext.tests/itext.io.tests/itext/io/font/otf/GposLookupType5Test.cs index 2e57c3d250..d54e897d1e 100644 --- a/itext.tests/itext.io.tests/itext/io/font/otf/GposLookupType5Test.cs +++ b/itext.tests/itext.io.tests/itext/io/font/otf/GposLookupType5Test.cs @@ -40,7 +40,7 @@ public virtual void VerifyMarkToBaseAttachment() { IList glyphs = JavaUtil.ArraysAsList(new Glyph(fontProgram.GetGlyphByCode(445)), new Glyph(fontProgram .GetGlyphByCode(394))); GlyphLine gl = new GlyphLine(glyphs); - gl.idx = 1; + gl.SetIdx(1); lookup.TransformOne(gl); NUnit.Framework.Assert.AreEqual(2, gl.Size()); NUnit.Framework.Assert.AreEqual(445, gl.Get(0).GetCode()); @@ -60,7 +60,7 @@ public virtual void TestSelectingCorrectAttachmentAlternative() { (75))); GlyphPositioningTableReader gposTableReader = fontProgram.GetGposTable(); GposLookupType5 lookup = (GposLookupType5)gposTableReader.GetLookupTable(3); - glyphLine.idx = 1; + glyphLine.SetIdx(1); lookup.TransformOne(glyphLine); NUnit.Framework.Assert.AreEqual(2, glyphLine.Size()); NUnit.Framework.Assert.AreEqual(513, glyphLine.Get(0).GetCode()); @@ -77,7 +77,7 @@ public virtual void TestThatNoTransformationsAppliedForNonRelevantGlyphs() { (75))); GlyphPositioningTableReader gposTableReader = fontProgram.GetGposTable(); GposLookupType5 lookup = (GposLookupType5)gposTableReader.GetLookupTable(3); - glyphLine.idx = 1; + glyphLine.SetIdx(1); lookup.TransformOne(glyphLine); NUnit.Framework.Assert.AreEqual(2, glyphLine.Size()); NUnit.Framework.Assert.AreEqual(1490, glyphLine.Get(0).GetCode()); @@ -85,5 +85,16 @@ public virtual void TestThatNoTransformationsAppliedForNonRelevantGlyphs() { NUnit.Framework.Assert.AreEqual(0, glyphLine.Get(1).GetAnchorDelta()); NUnit.Framework.Assert.AreEqual(0, glyphLine.Get(1).GetXPlacement()); } + + [NUnit.Framework.Test] + public virtual void IdxBiggerThanLineEndTest() { + TrueTypeFont fontProgram = (TrueTypeFont)FontProgramFactory.CreateFont(RESOURCE_FOLDER + "NotoNaskhArabic-Regular.ttf" + ); + GlyphLine glyphLine = new GlyphLine(JavaCollectionsUtil.SingletonList(fontProgram.GetGlyph(203))); + GlyphPositioningTableReader gposTableReader = fontProgram.GetGposTable(); + GposLookupType5 lookup = (GposLookupType5)gposTableReader.GetLookupTable(3); + glyphLine.SetIdx(10); + NUnit.Framework.Assert.IsFalse(lookup.TransformOne(glyphLine)); + } } } diff --git a/itext.tests/itext.io.tests/itext/io/font/otf/GposLookupType6Test.cs b/itext.tests/itext.io.tests/itext/io/font/otf/GposLookupType6Test.cs new file mode 100644 index 0000000000..05331d5669 --- /dev/null +++ b/itext.tests/itext.io.tests/itext/io/font/otf/GposLookupType6Test.cs @@ -0,0 +1,63 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using System.Collections.Generic; +using iText.Commons.Utils; +using iText.IO.Font; +using iText.Test; + +namespace iText.IO.Font.Otf { + [NUnit.Framework.Category("IntegrationTest")] + public class GposLookupType6Test : ExtendedITextTest { + private static readonly String RESOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + .CurrentContext.TestDirectory) + "/resources/itext/io/font/otf/"; + + private static readonly String FREE_SANS_FONT_PATH = RESOURCE_FOLDER + "FreeSans.ttf"; + + [NUnit.Framework.Test] + public virtual void IdxEqualToEndLineGpos6Test() { + TrueTypeFont fontProgram = (TrueTypeFont)FontProgramFactory.CreateFont(FREE_SANS_FONT_PATH); + GlyphPositioningTableReader gposTableReader = fontProgram.GetGposTable(); + GposLookupType6 lookup = new GposLookupType6(gposTableReader, 0, new int[0]); + IList glyphs = JavaUtil.ArraysAsList(new Glyph(fontProgram.GetGlyphByCode(445)), new Glyph(fontProgram + .GetGlyphByCode(394))); + GlyphLine gl = new GlyphLine(glyphs); + gl.SetIdx(2); + bool transform = lookup.TransformOne(gl); + NUnit.Framework.Assert.IsFalse(transform); + } + + [NUnit.Framework.Test] + public virtual void IdxSmallerThanEndLineGpos6Test() { + TrueTypeFont font = new TrueTypeFont(FREE_SANS_FONT_PATH); + GlyphPositioningTableReader gposTableReader = font.GetGposTable(); + GposLookupType6 lookup = new GposLookupType6(gposTableReader, 0, new int[0]); + IList glyphs = JavaUtil.ArraysAsList(new Glyph(font.GetGlyphByCode(174)), new Glyph(font.GetGlyphByCode + (5))); + GlyphLine gl = new GlyphLine(glyphs); + gl.SetIdx(0); + bool transform = lookup.TransformOne(gl); + NUnit.Framework.Assert.IsFalse(transform); + } + } +} diff --git a/itext.tests/itext.io.tests/itext/io/font/otf/GsubLookupType4Test.cs b/itext.tests/itext.io.tests/itext/io/font/otf/GsubLookupType4Test.cs index 153a8f1e83..ead2a0a303 100644 --- a/itext.tests/itext.io.tests/itext/io/font/otf/GsubLookupType4Test.cs +++ b/itext.tests/itext.io.tests/itext/io/font/otf/GsubLookupType4Test.cs @@ -40,10 +40,23 @@ public virtual void TestNoIndexOutOfBound() { IList glyphs = JavaUtil.ArraysAsList(new Glyph(1, 1, 1), new Glyph(1, 1, 1), new Glyph(1, 1, 1), new Glyph(1, 1, 1), new Glyph(1, 1, 1), new Glyph(1, 1, 1)); GlyphLine gl = new GlyphLine(glyphs); - gl.idx = gl.end; + gl.SetIdx(gl.GetEnd()); GsubLookupType4 lookup = (GsubLookupType4)gsubTableReader.GetLookupTable(6); //Assert that no exception is thrown if gl.idx = gl.end NUnit.Framework.Assert.IsFalse(lookup.TransformOne(gl)); } + + [NUnit.Framework.Test] + public virtual void NoTransformationTest() { + TrueTypeFont fontProgram = (TrueTypeFont)FontProgramFactory.CreateFont(RESOURCE_FOLDER + "DejaVuSansMono.ttf" + ); + GlyphSubstitutionTableReader gsubTableReader = fontProgram.GetGsubTable(); + IList glyphs = JavaUtil.ArraysAsList(new Glyph(1, 1, 1), new Glyph(1, 1, 1), new Glyph(1, 1, 1), new + Glyph(1, 1, 1), new Glyph(1, 1, 1), new Glyph(1, 1, 1)); + GlyphLine gl = new GlyphLine(glyphs); + gl.SetIdx(3); + GsubLookupType4 lookup = (GsubLookupType4)gsubTableReader.GetLookupTable(6); + NUnit.Framework.Assert.IsFalse(lookup.TransformOne(gl)); + } } } diff --git a/itext.tests/itext.kernel.tests/itext/kernel/utils/ValidationContextTest.cs b/itext.tests/itext.io.tests/itext/io/font/otf/LanguageRecordTest.cs similarity index 54% rename from itext.tests/itext.kernel.tests/itext/kernel/utils/ValidationContextTest.cs rename to itext.tests/itext.io.tests/itext/io/font/otf/LanguageRecordTest.cs index 469e633544..a53439260e 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/utils/ValidationContextTest.cs +++ b/itext.tests/itext.io.tests/itext/io/font/otf/LanguageRecordTest.cs @@ -20,30 +20,31 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ -using System.Collections.Generic; -using iText.IO.Source; -using iText.Kernel.Font; -using iText.Kernel.Pdf; using iText.Test; -namespace iText.Kernel.Utils { +namespace iText.IO.Font.Otf { [NUnit.Framework.Category("UnitTest")] - public class ValidationContextTest : ExtendedITextTest { + public class LanguageRecordTest : ExtendedITextTest { [NUnit.Framework.Test] - public virtual void WithDocumentsCheckTest() { - ValidationContext context = new ValidationContext(); - NUnit.Framework.Assert.IsNull(context.GetPdfDocument()); - context.WithPdfDocument(new PdfDocument(new PdfWriter(new ByteArrayOutputStream()))); - NUnit.Framework.Assert.IsNotNull(context.GetPdfDocument()); + public virtual void FeaturesRequiredTest() { + LanguageRecord languageRecord = new LanguageRecord(); + languageRecord.SetFeatureRequired(1); + NUnit.Framework.Assert.AreEqual(1, languageRecord.GetFeatureRequired()); } [NUnit.Framework.Test] - public virtual void WithFontsCheckTest() { - ValidationContext context = new ValidationContext(); - NUnit.Framework.Assert.IsNull(context.GetFonts()); - IList fonts = new List(); - context.WithFonts(fonts); - NUnit.Framework.Assert.IsNotNull(context.GetFonts()); + public virtual void TaggingTest() { + LanguageRecord languageRecord = new LanguageRecord(); + languageRecord.SetTag("tagname"); + NUnit.Framework.Assert.AreEqual("tagname", languageRecord.GetTag()); + } + + [NUnit.Framework.Test] + public virtual void FeaturesTest() { + LanguageRecord languageRecord = new LanguageRecord(); + int[] features = new int[2]; + languageRecord.SetFeatures(features); + NUnit.Framework.Assert.AreEqual(2, languageRecord.GetFeatures().Length); } } } diff --git a/itext.tests/itext.io.tests/itext/io/font/otf/OpenTableLookupTest.cs b/itext.tests/itext.io.tests/itext/io/font/otf/OpenTableLookupTest.cs new file mode 100644 index 0000000000..7a8027cf31 --- /dev/null +++ b/itext.tests/itext.io.tests/itext/io/font/otf/OpenTableLookupTest.cs @@ -0,0 +1,57 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Commons.Utils; +using iText.Test; + +namespace iText.IO.Font.Otf { + [NUnit.Framework.Category("UnitTest")] + public class OpenTableLookupTest : ExtendedITextTest { + [NUnit.Framework.Test] + public virtual void IdxTest() { + OpenTableLookup.GlyphIndexer glyphIndexer = new OpenTableLookup.GlyphIndexer(); + glyphIndexer.SetIdx(2); + NUnit.Framework.Assert.AreEqual(2, glyphIndexer.GetIdx()); + } + + [NUnit.Framework.Test] + public virtual void GlyphTest() { + Glyph glyph = new Glyph(200, 200, 200); + OpenTableLookup.GlyphIndexer glyphIndexer = new OpenTableLookup.GlyphIndexer(); + glyphIndexer.SetGlyph(glyph); + NUnit.Framework.Assert.AreEqual(200, glyphIndexer.GetGlyph().GetWidth()); + NUnit.Framework.Assert.AreEqual(200, glyphIndexer.GetGlyph().GetCode()); + NUnit.Framework.Assert.AreEqual(200, glyphIndexer.GetGlyph().GetUnicode()); + } + + [NUnit.Framework.Test] + public virtual void GlyphLineTest() { + Glyph glyph = new Glyph(200, 200, 200); + GlyphLine glyphLine = new GlyphLine(JavaCollectionsUtil.SingletonList(glyph)); + OpenTableLookup.GlyphIndexer glyphIndexer = new OpenTableLookup.GlyphIndexer(); + glyphIndexer.SetLine(glyphLine); + NUnit.Framework.Assert.AreEqual(0, glyphIndexer.GetLine().GetIdx()); + NUnit.Framework.Assert.AreEqual(0, glyphIndexer.GetLine().GetStart()); + NUnit.Framework.Assert.AreEqual(1, glyphIndexer.GetLine().GetEnd()); + } + } +} diff --git a/itext.tests/itext.io.tests/itext/io/font/otf/OpenTypeFontTableReaderTest.cs b/itext.tests/itext.io.tests/itext/io/font/otf/OpenTypeFontTableReaderTest.cs index c68e7d2942..af8e0e5142 100644 --- a/itext.tests/itext.io.tests/itext/io/font/otf/OpenTypeFontTableReaderTest.cs +++ b/itext.tests/itext.io.tests/itext/io/font/otf/OpenTypeFontTableReaderTest.cs @@ -21,6 +21,7 @@ You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ using System; +using System.Collections.Generic; using System.Linq; using iText.IO.Font; using iText.Test; @@ -31,18 +32,25 @@ public class OpenTypeFontTableReaderTest : ExtendedITextTest { private static readonly String RESOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext .CurrentContext.TestDirectory) + "/resources/itext/io/font/otf/OpenTypeFontTableReaderTest/"; + private static readonly String FONTS_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + .CurrentContext.TestDirectory) + "/resources/itext/io/font/sharedFontsResourceFiles/"; + + private static readonly String CJK_JP_BOLD_PATH = FONTS_FOLDER + "NotoSansCJKjp-Bold.otf"; + + private static readonly String SANS_MYANMAR_REGULAR_PATH = RESOURCE_FOLDER + "NotoSansMyanmar-Regular.ttf"; + [NUnit.Framework.Test] public virtual void TestFetchLangSysByTag() { - TrueTypeFont fontProgram = (TrueTypeFont)FontProgramFactory.CreateFont(RESOURCE_FOLDER + "NotoSansMyanmar-Regular.ttf" - ); + TrueTypeFont fontProgram = (TrueTypeFont)FontProgramFactory.CreateFont(SANS_MYANMAR_REGULAR_PATH); GlyphSubstitutionTableReader gsub = fontProgram.GetGsubTable(); ScriptRecord mym2 = gsub.GetScriptRecords()[0]; - NUnit.Framework.Assert.AreEqual("mym2", mym2.tag); + NUnit.Framework.Assert.AreEqual("mym2", mym2.GetTag()); // default LangSys has no tag - NUnit.Framework.Assert.AreEqual("", gsub.GetLanguageRecord("mym2").tag); + NUnit.Framework.Assert.AreEqual("", gsub.GetLanguageRecord("mym2").GetTag()); NUnit.Framework.Assert.AreEqual(LanguageTags.SGAW_KAREN, gsub.GetLanguageRecord("mym2", LanguageTags.SGAW_KAREN - ).tag); - NUnit.Framework.Assert.AreEqual(LanguageTags.MON, gsub.GetLanguageRecord("mym2", LanguageTags.MON).tag); + ).GetTag()); + NUnit.Framework.Assert.AreEqual(LanguageTags.MON, gsub.GetLanguageRecord("mym2", LanguageTags.MON).GetTag( + )); NUnit.Framework.Assert.IsNull(gsub.GetLanguageRecord(null)); NUnit.Framework.Assert.IsNull(gsub.GetLanguageRecord("mym3")); NUnit.Framework.Assert.IsNull(gsub.GetLanguageRecord("mym3", LanguageTags.SGAW_KAREN)); @@ -50,15 +58,14 @@ public virtual void TestFetchLangSysByTag() { [NUnit.Framework.Test] public virtual void TestGetLookupsArray() { - TrueTypeFont fontProgram = (TrueTypeFont)FontProgramFactory.CreateFont(RESOURCE_FOLDER + "NotoSansMyanmar-Regular.ttf" - ); + TrueTypeFont fontProgram = (TrueTypeFont)FontProgramFactory.CreateFont(SANS_MYANMAR_REGULAR_PATH); GlyphSubstitutionTableReader gsub = fontProgram.GetGsubTable(); FeatureRecord firstRecord = new FeatureRecord(); - firstRecord.lookups = new int[] { 5, 2 }; - firstRecord.tag = "1"; + firstRecord.SetLookups(new int[] { 5, 2 }); + firstRecord.SetTag("1"); FeatureRecord secondRecord = new FeatureRecord(); - secondRecord.lookups = new int[] { 4, 10 }; - secondRecord.tag = "2"; + secondRecord.SetLookups(new int[] { 4, 10 }); + secondRecord.SetTag("2"); FeatureRecord[] records = new FeatureRecord[] { firstRecord, secondRecord }; int[] lookupsLocations = gsub.GetLookups(firstRecord).Select((record) => record.subTableLocations[0]).ToArray (); @@ -68,5 +75,93 @@ public virtual void TestGetLookupsArray() { expected = new int[] { 142436, 142538, 142610, 143908 }; NUnit.Framework.Assert.AreEqual(expected, lookupsLocations); } + + [NUnit.Framework.Test] + public virtual void GetNegativeIdxTest() { + GlyphPositioningTableReader gposTableReader = GetGPosTableReader(SANS_MYANMAR_REGULAR_PATH); + GposLookupType1 lookup = (GposLookupType1)gposTableReader.GetLookupTable(-1); + NUnit.Framework.Assert.IsNull(lookup); + } + + [NUnit.Framework.Test] + public virtual void GetFeatureRecordsTest() { + GlyphPositioningTableReader gposTableReader = GetGPosTableReader(SANS_MYANMAR_REGULAR_PATH); + IList lookup = gposTableReader.GetFeatureRecords(); + NUnit.Framework.Assert.AreEqual(3, lookup.Count); + } + + [NUnit.Framework.Test] + public virtual void GetFeaturesNullTest() { + GlyphPositioningTableReader gposTableReader = GetGPosTableReader(SANS_MYANMAR_REGULAR_PATH); + String[] scripts = new String[0]; + IList lookup = gposTableReader.GetFeatures(scripts, "null"); + NUnit.Framework.Assert.IsNull(lookup); + } + + [NUnit.Framework.Test] + public virtual void GetRequiredFeaturesNullTest() { + GlyphPositioningTableReader gposTableReader = GetGPosTableReader(SANS_MYANMAR_REGULAR_PATH); + String[] scripts = new String[1]; + scripts[0] = "test"; + FeatureRecord requiredFeature = gposTableReader.GetRequiredFeature(scripts, "null"); + NUnit.Framework.Assert.IsNull(requiredFeature); + } + + [NUnit.Framework.Test] + public virtual void DefaultLangTest() { + GlyphPositioningTableReader gposTableReader = GetGPosTableReader(CJK_JP_BOLD_PATH); + String[] scripts = new String[7]; + scripts[0] = "DFLT"; + IList featureRecords = gposTableReader.GetFeatures(scripts, ""); + NUnit.Framework.Assert.AreEqual(8, featureRecords.Count); + } + + [NUnit.Framework.Test] + public virtual void NullStringArrayScriptsTest() { + GlyphPositioningTableReader gposTableReader = GetGPosTableReader(CJK_JP_BOLD_PATH); + String[] scripts = new String[7]; + IList featureRecords = gposTableReader.GetFeatures(scripts, ""); + NUnit.Framework.Assert.AreEqual(8, featureRecords.Count); + } + + [NUnit.Framework.Test] + public virtual void NonDefTest() { + GlyphPositioningTableReader gposTableReader = GetGPosTableReader(SANS_MYANMAR_REGULAR_PATH); + String[] scripts = new String[7]; + scripts[2] = "DFLT"; + IList featureRecords = gposTableReader.GetFeatures(scripts, ""); + NUnit.Framework.Assert.AreEqual(3, featureRecords.Count); + } + + [NUnit.Framework.Test] + public virtual void TestFetchLangSysByTag2() { + TrueTypeFont fontProgram = (TrueTypeFont)FontProgramFactory.CreateFont(SANS_MYANMAR_REGULAR_PATH); + GlyphSubstitutionTableReader gsub = fontProgram.GetGsubTable(); + NUnit.Framework.Assert.IsNull(gsub.GetLanguageRecord("mym2", LanguageTags.ARABIC)); + } + + [NUnit.Framework.Test] + public virtual void SpecificEqualsNullTest() { + GlyphPositioningTableReader gPosTableReader = GetGPosTableReader(CJK_JP_BOLD_PATH); + IList test = new List(); + test.Add(new FeatureRecord()); + IList specificFeatures = gPosTableReader.GetSpecificFeatures(test, null); + NUnit.Framework.Assert.AreEqual(test, specificFeatures); + } + + [NUnit.Framework.Test] + public virtual void SpecificFeaturesTest() { + GlyphPositioningTableReader gPosTableReader = GetGPosTableReader(CJK_JP_BOLD_PATH); + String[] specific = new String[1]; + IList test = new List(); + test.Add(new FeatureRecord()); + IList specificFeatures = gPosTableReader.GetSpecificFeatures(test, specific); + NUnit.Framework.Assert.AreEqual(test, specificFeatures); + } + + private GlyphPositioningTableReader GetGPosTableReader(String fontPath) { + TrueTypeFont fontProgram = (TrueTypeFont)FontProgramFactory.CreateFont(fontPath); + return fontProgram.GetGposTable(); + } } } diff --git a/itext.tests/itext.io.tests/itext/io/font/otf/OtfReadCommonTest.cs b/itext.tests/itext.io.tests/itext/io/font/otf/OtfReadCommonTest.cs index a924fc698d..eafc761d67 100644 --- a/itext.tests/itext.io.tests/itext/io/font/otf/OtfReadCommonTest.cs +++ b/itext.tests/itext.io.tests/itext/io/font/otf/OtfReadCommonTest.cs @@ -71,10 +71,10 @@ public virtual void TestConversionGlyphToTextSpace() { (this, new OtfReadCommonTest.RandomAccesArrayTest(this, null), 0, null, null, 1); // at 15 we fill up all values GposValueRecord valueRecord = OtfReadCommon.ReadGposValueRecord(gposTableReader, 15); - NUnit.Framework.Assert.AreEqual(2000, valueRecord.XAdvance); - NUnit.Framework.Assert.AreEqual(2000, valueRecord.XPlacement); - NUnit.Framework.Assert.AreEqual(2000, valueRecord.YAdvance); - NUnit.Framework.Assert.AreEqual(2000, valueRecord.YPlacement); + NUnit.Framework.Assert.AreEqual(2000, valueRecord.GetXAdvance()); + NUnit.Framework.Assert.AreEqual(2000, valueRecord.GetXPlacement()); + NUnit.Framework.Assert.AreEqual(2000, valueRecord.GetYAdvance()); + NUnit.Framework.Assert.AreEqual(2000, valueRecord.GetYPlacement()); } //\cond DO_NOT_DOCUMENT diff --git a/itext.tests/itext.io.tests/itext/io/image/RawImageHelperTest.cs b/itext.tests/itext.io.tests/itext/io/image/RawImageHelperTest.cs new file mode 100644 index 0000000000..ea5650f71e --- /dev/null +++ b/itext.tests/itext.io.tests/itext/io/image/RawImageHelperTest.cs @@ -0,0 +1,68 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Test; + +namespace iText.IO.Image { + [NUnit.Framework.Category("UnitTest")] + public class RawImageHelperTest : ExtendedITextTest { + [NUnit.Framework.Test] + public virtual void OneBitBlackPixelsTest() { + PngImageData pngImageData1 = new PngImageData(new byte[1]); + pngImageData1.SetTypeCcitt(256); + pngImageData1.SetColorEncodingComponentsNumber(RawImageData.CCITT_BLACKIS1); + RawImageHelper.UpdateImageAttributes(pngImageData1, null); + bool? blackIs1 = (bool?)pngImageData1.GetDecodeParms().Get("BlackIs1"); + NUnit.Framework.Assert.IsTrue(blackIs1, "CCITT_BLACKIS1 is false."); + } + + [NUnit.Framework.Test] + public virtual void ExtraZeroBitsBeforeEncodedLineTest() { + PngImageData pngImageData1 = new PngImageData(new byte[1]); + pngImageData1.SetTypeCcitt(256); + pngImageData1.SetColorEncodingComponentsNumber(RawImageData.CCITT_ENCODEDBYTEALIGN); + RawImageHelper.UpdateImageAttributes(pngImageData1, null); + bool? blackIs1 = (bool?)pngImageData1.GetDecodeParms().Get("EncodedByteAlign"); + NUnit.Framework.Assert.IsTrue(blackIs1, "CCITT_ENCODEDBYTEALIGN is false."); + } + + [NUnit.Framework.Test] + public virtual void EndOfLineBitsPresentTest() { + PngImageData pngImageData1 = new PngImageData(new byte[1]); + pngImageData1.SetTypeCcitt(256); + pngImageData1.SetColorEncodingComponentsNumber(RawImageData.CCITT_ENDOFLINE); + RawImageHelper.UpdateImageAttributes(pngImageData1, null); + bool? blackIs1 = (bool?)pngImageData1.GetDecodeParms().Get("EndOfLine"); + NUnit.Framework.Assert.IsTrue(blackIs1, "CCITT_ENDOFLINE is false."); + } + + [NUnit.Framework.Test] + public virtual void EndOfBlockPatternFalseTest() { + PngImageData pngImageData1 = new PngImageData(new byte[1]); + pngImageData1.SetTypeCcitt(256); + pngImageData1.SetColorEncodingComponentsNumber(RawImageData.CCITT_ENDOFBLOCK); + RawImageHelper.UpdateImageAttributes(pngImageData1, null); + bool? blackIs1 = (bool?)pngImageData1.GetDecodeParms().Get("EndOfBlock"); + NUnit.Framework.Assert.IsFalse(blackIs1, "CCITT_ENDOFBLOCK is true."); + } + } +} diff --git a/itext.tests/itext.io.tests/itext/io/source/OutputStreamTest.cs b/itext.tests/itext.io.tests/itext/io/source/HighPrecisionOutputStreamTest.cs similarity index 77% rename from itext.tests/itext.io.tests/itext/io/source/OutputStreamTest.cs rename to itext.tests/itext.io.tests/itext/io/source/HighPrecisionOutputStreamTest.cs index 9db0f611ef..8bc8ca928d 100644 --- a/itext.tests/itext.io.tests/itext/io/source/OutputStreamTest.cs +++ b/itext.tests/itext.io.tests/itext/io/source/HighPrecisionOutputStreamTest.cs @@ -28,13 +28,13 @@ You should have received a copy of the GNU Affero General Public License using iText.Test.Attributes; namespace iText.IO.Source { - public class OutputStreamTest : ExtendedITextTest { + public class HighPrecisionOutputStreamTest : ExtendedITextTest { private static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext .CurrentContext.TestDirectory) + "/resources/itext/io/source/OSTEST.txt"; private static Stream IO_EXCEPTION_OUTPUT_STREAM; - static OutputStreamTest() { + static HighPrecisionOutputStreamTest() { try { IO_EXCEPTION_OUTPUT_STREAM = new FileStream(SOURCE_FOLDER, FileMode.Append); IO_EXCEPTION_OUTPUT_STREAM.Dispose(); @@ -49,7 +49,7 @@ public virtual void ChangePrecisionTest() { //the data is random double? expected = 2.002d; using (ByteArrayOutputStream bytes = new ByteArrayOutputStream()) { - using (OutputStream stream = new OutputStream(bytes, false)) { + using (HighPrecisionOutputStream stream = new HighPrecisionOutputStream(bytes, false)) { stream.SetLocalHighPrecision(true); stream.WriteDouble((double)expected); stream.Flush(); @@ -63,7 +63,7 @@ public virtual void ChangePrecisionToFalseTest() { //the data is random double? expected = 2.002d; using (ByteArrayOutputStream bytes = new ByteArrayOutputStream()) { - using (OutputStream stream = new OutputStream(bytes, false)) { + using (HighPrecisionOutputStream stream = new HighPrecisionOutputStream(bytes, false)) { stream.SetLocalHighPrecision(false); stream.WriteDouble((double)expected); stream.Flush(); @@ -78,7 +78,7 @@ public virtual void WriteNanTest() { //the data is random String expected = "0"; using (ByteArrayOutputStream bytes = new ByteArrayOutputStream()) { - using (OutputStream stream = new OutputStream(bytes)) { + using (HighPrecisionOutputStream stream = new HighPrecisionOutputStream(bytes)) { stream.WriteDouble(double.NaN); stream.Flush(); NUnit.Framework.Assert.AreEqual(expected, Encoding.UTF8.GetString(bytes.ToArray())); @@ -91,7 +91,7 @@ public virtual void WriteValidByteArrayTest() { //the data is random byte[] expected = new byte[] { (byte)68, (byte)14, (byte)173, (byte)105 }; using (ByteArrayOutputStream bytes = new ByteArrayOutputStream()) { - using (OutputStream stream = new OutputStream(bytes)) { + using (HighPrecisionOutputStream stream = new HighPrecisionOutputStream(bytes)) { stream.Write(expected); stream.Flush(); NUnit.Framework.Assert.AreEqual(expected, bytes.ToArray()); @@ -104,7 +104,7 @@ public virtual void WriteSingleValidByteTest() { //the data is random byte expected = (byte)193; using (ByteArrayOutputStream bytes = new ByteArrayOutputStream()) { - using (OutputStream stream = new OutputStream(bytes)) { + using (HighPrecisionOutputStream stream = new HighPrecisionOutputStream(bytes)) { stream.WriteByte(expected); stream.Flush(); NUnit.Framework.Assert.AreEqual(new byte[] { expected }, bytes.ToArray()); @@ -117,7 +117,7 @@ public virtual void WriteSingleValidIntegerTest() { //the data is random int expected = 1695609641; using (ByteArrayOutputStream bytes = new ByteArrayOutputStream()) { - using (OutputStream stream = new OutputStream(bytes)) { + using (HighPrecisionOutputStream stream = new HighPrecisionOutputStream(bytes)) { stream.WriteInteger(expected); stream.Flush(); NUnit.Framework.Assert.AreEqual(JavaUtil.IntegerToString(expected), Encoding.UTF8.GetString(bytes.ToArray())); @@ -130,7 +130,7 @@ public virtual void WriteSingleValidLongTest() { //the data is random long? expected = 1695609641552L; using (ByteArrayOutputStream bytes = new ByteArrayOutputStream()) { - using (OutputStream stream = new OutputStream(bytes)) { + using (HighPrecisionOutputStream stream = new HighPrecisionOutputStream(bytes)) { stream.WriteLong((long)expected); stream.Flush(); NUnit.Framework.Assert.AreEqual(Convert.ToString(expected), Encoding.UTF8.GetString(bytes.ToArray())); @@ -143,7 +143,7 @@ public virtual void WriteValidFloatsArrayTest() { //the data is random float[] expected = new float[] { 12.05f, 0.001f }; using (ByteArrayOutputStream bytes = new ByteArrayOutputStream()) { - using (OutputStream stream = new OutputStream(bytes)) { + using (HighPrecisionOutputStream stream = new HighPrecisionOutputStream(bytes)) { stream.WriteFloats(expected); stream.Flush(); NUnit.Framework.Assert.AreEqual(expected[0] + " " + expected[1], Encoding.UTF8.GetString(bytes.ToArray())); @@ -156,7 +156,7 @@ public virtual void WriteValidBytesWithOffsetTest() { //the data is random byte[] expected = new byte[] { (byte)58, (byte)97 }; using (ByteArrayOutputStream bytes = new ByteArrayOutputStream()) { - using (OutputStream stream = new OutputStream(bytes)) { + using (HighPrecisionOutputStream stream = new HighPrecisionOutputStream(bytes)) { stream.WriteBytes(new byte[] { (byte)15, (byte)233, (byte)58, (byte)97 }, 2, 2); stream.Flush(); NUnit.Framework.Assert.AreEqual(expected, bytes.ToArray()); @@ -169,7 +169,7 @@ public virtual void WriteBytesIOExceptionTest() { NUnit.Framework.Assert.That(() => { byte[] bytesToWrite = new byte[] { (byte)71 }; using (Stream bytes = IO_EXCEPTION_OUTPUT_STREAM) { - using (OutputStream stream = new OutputStream(bytes)) { + using (HighPrecisionOutputStream stream = new HighPrecisionOutputStream(bytes)) { stream.WriteBytes(bytesToWrite); } } @@ -183,7 +183,7 @@ public virtual void WriteByteIOExceptionTest() { NUnit.Framework.Assert.That(() => { byte byteToWrite = (byte)71; using (Stream bytes = IO_EXCEPTION_OUTPUT_STREAM) { - using (OutputStream stream = new OutputStream(bytes)) { + using (HighPrecisionOutputStream stream = new HighPrecisionOutputStream(bytes)) { stream.WriteByte(byteToWrite); } } @@ -198,7 +198,7 @@ public virtual void WriteByteIntIOExceptionTest() { //the data is random int byteToWrite = 71; using (Stream bytes = IO_EXCEPTION_OUTPUT_STREAM) { - using (OutputStream stream = new OutputStream(bytes)) { + using (HighPrecisionOutputStream stream = new HighPrecisionOutputStream(bytes)) { stream.WriteByte(byteToWrite); } } @@ -213,7 +213,7 @@ public virtual void WriteDoubleIOExceptionTest() { //the data is random double num = 55.55d; using (Stream bytes = IO_EXCEPTION_OUTPUT_STREAM) { - using (OutputStream stream = new OutputStream(bytes)) { + using (HighPrecisionOutputStream stream = new HighPrecisionOutputStream(bytes)) { stream.WriteDouble(num); } } @@ -228,7 +228,7 @@ public virtual void WriteLongIOExceptionTest() { //the data is random long num = 55L; using (Stream bytes = IO_EXCEPTION_OUTPUT_STREAM) { - using (OutputStream stream = new OutputStream(bytes)) { + using (HighPrecisionOutputStream stream = new HighPrecisionOutputStream(bytes)) { stream.WriteLong(num); } } @@ -241,7 +241,7 @@ public virtual void WriteLongIOExceptionTest() { public virtual void WriteValidStringTest() { String expected = "Test string to write"; using (ByteArrayOutputStream bytes = new ByteArrayOutputStream()) { - using (OutputStream stream = new OutputStream(bytes)) { + using (HighPrecisionOutputStream stream = new HighPrecisionOutputStream(bytes)) { stream.WriteString(expected); stream.WriteNewLine(); stream.Flush(); @@ -252,7 +252,7 @@ public virtual void WriteValidStringTest() { [NUnit.Framework.Test] public virtual void GettersAndSettersTest() { - OutputStream stream = new OutputStream(); + HighPrecisionOutputStream stream = new HighPrecisionOutputStream(); stream.SetCloseStream(true); NUnit.Framework.Assert.IsTrue(stream.IsCloseStream()); stream.SetCloseStream(false); @@ -266,7 +266,7 @@ public virtual void WriteValidBytesArrayTest() { //the data is random byte[] expected = new byte[] { (byte)15, (byte)233, (byte)58, (byte)97 }; using (ByteArrayOutputStream bytes = new ByteArrayOutputStream()) { - using (OutputStream stream = new OutputStream(bytes)) { + using (HighPrecisionOutputStream stream = new HighPrecisionOutputStream(bytes)) { stream.WriteBytes(expected); stream.Flush(); NUnit.Framework.Assert.AreEqual(expected, bytes.ToArray()); @@ -279,7 +279,7 @@ public virtual void AssignBytesArrayTest() { //the data is random byte[] expected = new byte[] { (byte)15, (byte)233, (byte)58, (byte)97 }; using (ByteArrayOutputStream bytes = new ByteArrayOutputStream()) { - using (OutputStream stream = new OutputStream(bytes)) { + using (HighPrecisionOutputStream stream = new HighPrecisionOutputStream(bytes)) { stream.AssignBytes(expected, 4); NUnit.Framework.Assert.AreEqual(expected, bytes.ToArray()); } @@ -292,7 +292,7 @@ public virtual void AssignBytesExceptionTest() { //the data is random byte[] bytes = new byte[] { (byte)15, (byte)233, (byte)58, (byte)97 }; using (Stream outputStream = IO_EXCEPTION_OUTPUT_STREAM) { - using (OutputStream stream = new OutputStream(outputStream)) { + using (HighPrecisionOutputStream stream = new HighPrecisionOutputStream(outputStream)) { stream.AssignBytes(bytes, 4); } } @@ -305,7 +305,7 @@ public virtual void AssignBytesExceptionTest() { public virtual void ResetTestNoException() { byte[] expected = new byte[] { }; using (ByteArrayOutputStream bytes = new ByteArrayOutputStream()) { - using (OutputStream stream = new OutputStream(bytes)) { + using (HighPrecisionOutputStream stream = new HighPrecisionOutputStream(bytes)) { stream.WriteBytes(new byte[] { (byte)15, (byte)233, (byte)58, (byte)97 }); stream.Flush(); stream.Reset(); @@ -318,7 +318,7 @@ public virtual void ResetTestNoException() { public virtual void ResetExceptionTest() { NUnit.Framework.Assert.That(() => { using (Stream bytes = IO_EXCEPTION_OUTPUT_STREAM) { - using (OutputStream stream = new OutputStream(bytes)) { + using (HighPrecisionOutputStream stream = new HighPrecisionOutputStream(bytes)) { stream.Reset(); } } @@ -330,15 +330,15 @@ public virtual void ResetExceptionTest() { [NUnit.Framework.Test] public virtual void LocalHighPrecisionOverridesGlobalTest() { - bool highPrecision = OutputStream.GetHighPrecision(); + bool highPrecision = HighPrecisionOutputStream.GetHighPrecision(); //the data is random double? numberToWrite = 2.002d; try { using (ByteArrayOutputStream bytes = new ByteArrayOutputStream()) { - using (OutputStream stream = - new OutputStream(bytes, false)) { - OutputStream.SetHighPrecision(true); + using (HighPrecisionOutputStream stream = + new HighPrecisionOutputStream(bytes, false)) { + HighPrecisionOutputStream.SetHighPrecision(true); stream.SetLocalHighPrecision(false); stream.WriteDouble((double)numberToWrite); stream.Flush(); @@ -347,7 +347,7 @@ public virtual void LocalHighPrecisionOverridesGlobalTest() { } } finally { - OutputStream.SetHighPrecision(highPrecision); + HighPrecisionOutputStream.SetHighPrecision(highPrecision); } } } diff --git a/itext.tests/itext.io.tests/itext/io/source/PdfTokenizerTest.cs b/itext.tests/itext.io.tests/itext/io/source/PdfTokenizerTest.cs index 8b27dcfc22..ab4d260c1f 100644 --- a/itext.tests/itext.io.tests/itext/io/source/PdfTokenizerTest.cs +++ b/itext.tests/itext.io.tests/itext/io/source/PdfTokenizerTest.cs @@ -57,6 +57,39 @@ public virtual void SeekTest() { NUnit.Framework.Assert.AreEqual(expectedTypes[2], tok.GetTokenType()); } + [NUnit.Framework.Test] + public virtual void PeekTest() { + String data = "/Name1 70"; + PdfTokenizer tokenizer = new PdfTokenizer(new RandomAccessFileOrArray(new RandomAccessSourceFactory().CreateSource + (data.GetBytes(iText.Commons.Utils.EncodingUtil.ISO_8859_1)))); + tokenizer.Seek(0); + int symbol = tokenizer.Peek(); + NUnit.Framework.Assert.AreEqual((int)'/', symbol); + NUnit.Framework.Assert.AreEqual(0, tokenizer.GetPosition()); + tokenizer.Seek(7); + symbol = tokenizer.Peek(); + NUnit.Framework.Assert.AreEqual((int)'7', symbol); + NUnit.Framework.Assert.AreEqual(7, tokenizer.GetPosition()); + tokenizer.Seek(9); + symbol = tokenizer.Peek(); + NUnit.Framework.Assert.AreEqual(-1, symbol); + NUnit.Framework.Assert.AreEqual(9, tokenizer.GetPosition()); + byte[] name = new byte[6]; + tokenizer.Seek(0); + int read = tokenizer.Peek(name); + byte[] expected = "/Name1".GetBytes(); + NUnit.Framework.Assert.AreEqual(expected, name); + NUnit.Framework.Assert.AreEqual(0, tokenizer.GetPosition()); + NUnit.Framework.Assert.AreEqual(6, read); + byte[] bigBuffer = new byte[13]; + read = tokenizer.Peek(bigBuffer); + expected = new byte[] { (byte)47, (byte)78, (byte)97, (byte)109, (byte)101, (byte)49, (byte)32, (byte)55, + (byte)48, (byte)0, (byte)0, (byte)0, (byte)0 }; + NUnit.Framework.Assert.AreEqual(expected, bigBuffer); + NUnit.Framework.Assert.AreEqual(0, tokenizer.GetPosition()); + NUnit.Framework.Assert.AreEqual(9, read); + } + [NUnit.Framework.Test] public virtual void GetLongValueTest() { String data = "21474836470"; @@ -175,7 +208,7 @@ public virtual void GetNextEofShortTextTest() { using (PdfTokenizer tok = new PdfTokenizer(new RandomAccessFileOrArray(factory.CreateSource(data.GetBytes( iText.Commons.Utils.EncodingUtil.ISO_8859_1))))) { long eofPosition = tok.GetNextEof(); - NUnit.Framework.Assert.AreEqual(data.Length + 1, eofPosition); + NUnit.Framework.Assert.AreEqual(data.Length, eofPosition); } } @@ -191,7 +224,7 @@ public virtual void GetNextEofLongTextTest() { using (PdfTokenizer tok = new PdfTokenizer(new RandomAccessFileOrArray(factory.CreateSource(stringBuilder. ToString().GetBytes(iText.Commons.Utils.EncodingUtil.ISO_8859_1))))) { long eofPosition = tok.GetNextEof(); - NUnit.Framework.Assert.AreEqual(data.Length * 20 + 6, eofPosition); + NUnit.Framework.Assert.AreEqual(data.Length * 20 + 5, eofPosition); } } @@ -208,7 +241,7 @@ public virtual void GetNextEofWhichIsCutTest() { using (PdfTokenizer tok = new PdfTokenizer(new RandomAccessFileOrArray(factory.CreateSource(stringBuilder. ToString().GetBytes(iText.Commons.Utils.EncodingUtil.ISO_8859_1))))) { long eofPosition = tok.GetNextEof(); - NUnit.Framework.Assert.AreEqual(124 + 6, eofPosition); + NUnit.Framework.Assert.AreEqual(124 + 5, eofPosition); } } @@ -219,7 +252,18 @@ public virtual void GetNextEofSeveralEofTest() { using (PdfTokenizer tok = new PdfTokenizer(new RandomAccessFileOrArray(factory.CreateSource(data.GetBytes( iText.Commons.Utils.EncodingUtil.ISO_8859_1))))) { long eofPosition = tok.GetNextEof(); - NUnit.Framework.Assert.AreEqual(data.IndexOf("%%EOF", StringComparison.Ordinal) + 6, eofPosition); + NUnit.Framework.Assert.AreEqual(data.IndexOf("%%EOF", StringComparison.Ordinal) + 5, eofPosition); + } + } + + [NUnit.Framework.Test] + public virtual void GetNextEofFollowedByEOLTest() { + String data = "some text to test \ngetting end of\n file logic%%EOF\n\r\r\n\r\r\n"; + RandomAccessSourceFactory factory = new RandomAccessSourceFactory(); + using (PdfTokenizer tok = new PdfTokenizer(new RandomAccessFileOrArray(factory.CreateSource(data.GetBytes( + iText.Commons.Utils.EncodingUtil.ISO_8859_1))))) { + long eofPosition = tok.GetNextEof(); + NUnit.Framework.Assert.AreEqual(data.IndexOf("%%EOF", StringComparison.Ordinal) + 4 + 5, eofPosition); } } diff --git a/itext.tests/itext.io.tests/itext/io/util/GhostscriptHelperTest.cs b/itext.tests/itext.io.tests/itext/io/util/GhostscriptHelperTest.cs index bc2361670a..c544bab706 100644 --- a/itext.tests/itext.io.tests/itext/io/util/GhostscriptHelperTest.cs +++ b/itext.tests/itext.io.tests/itext/io/util/GhostscriptHelperTest.cs @@ -54,9 +54,6 @@ public virtual void GhostScriptEnvVarIsDefault() { [NUnit.Framework.Test] public virtual void GhostScriptEnvVarIsExplicitlySpecified() { String gsExec = SystemUtil.GetEnvironmentVariable(GhostscriptHelper.GHOSTSCRIPT_ENVIRONMENT_VARIABLE); - if (gsExec == null) { - gsExec = SystemUtil.GetEnvironmentVariable(GhostscriptHelper.GHOSTSCRIPT_ENVIRONMENT_VARIABLE_LEGACY); - } GhostscriptHelper ghostscriptHelper = new GhostscriptHelper(gsExec); NUnit.Framework.Assert.IsNotNull(ghostscriptHelper.GetCliExecutionCommand()); } diff --git a/itext.tests/itext.io.tests/itext/io/util/ImageMagickHelperTest.cs b/itext.tests/itext.io.tests/itext/io/util/ImageMagickHelperTest.cs index 815f174d95..b7ba751e35 100644 --- a/itext.tests/itext.io.tests/itext/io/util/ImageMagickHelperTest.cs +++ b/itext.tests/itext.io.tests/itext/io/util/ImageMagickHelperTest.cs @@ -58,10 +58,6 @@ public virtual void ImageMagickEnvVarIsDefault() { public virtual void ImageMagickEnvVarIsExplicitlySpecified() { String compareExec = SystemUtil.GetEnvironmentVariable(ImageMagickHelper.MAGICK_COMPARE_ENVIRONMENT_VARIABLE ); - if (compareExec == null) { - compareExec = SystemUtil.GetEnvironmentVariable(ImageMagickHelper.MAGICK_COMPARE_ENVIRONMENT_VARIABLE_LEGACY - ); - } ImageMagickHelper imageMagickHelper = new ImageMagickHelper(compareExec); NUnit.Framework.Assert.IsNotNull(imageMagickHelper.GetCliExecutionCommand()); } diff --git a/itext.tests/itext.io.tests/resources/itext/io/font/otf/GposLookupType2Test/BitstreamCopyright.txt b/itext.tests/itext.io.tests/resources/itext/io/font/otf/GposLookupType2Test/BitstreamCopyright.txt new file mode 100644 index 0000000000..ce8e3a19b1 --- /dev/null +++ b/itext.tests/itext.io.tests/resources/itext/io/font/otf/GposLookupType2Test/BitstreamCopyright.txt @@ -0,0 +1,15 @@ +Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is a trademark of Bitstream, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy of the fonts accompanying this license ("Fonts") and associated documentation files (the "Font Software"), to reproduce and distribute the Font Software, including without limitation the rights to use, copy, merge, publish, distribute, and/or sell copies of the Font Software, and to permit persons to whom the Font Software is furnished to do so, subject to the following conditions: + +The above copyright and trademark notices and this permission notice shall be included in all copies of one or more of the Font Software typefaces. + +The Font Software may be modified, altered, or added to, and in particular the designs of glyphs or characters in the Fonts may be modified and additional glyphs or characters may be added to the Fonts, only if the fonts are renamed to names not containing either the words "Bitstream" or the word "Vera". + +This License becomes null and void to the extent applicable to Fonts or Font Software that has been modified and is distributed under the "Bitstream Vera" names. + +The Font Software may be sold as part of a larger software package but no copy of one or more of the Font Software typefaces may be sold by itself. + +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. + +Except as contained in this notice, the names of Gnome, the Gnome Foundation, and Bitstream Inc., shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Font Software without prior written authorization from the Gnome Foundation or Bitstream Inc., respectively. For further information, contact: fonts at gnome dot org. \ No newline at end of file diff --git a/itext.tests/itext.io.tests/resources/itext/io/font/otf/GposLookupType2Test/DejaVuSans.ttf b/itext.tests/itext.io.tests/resources/itext/io/font/otf/GposLookupType2Test/DejaVuSans.ttf new file mode 100644 index 0000000000..e5f7eecce4 Binary files /dev/null and b/itext.tests/itext.io.tests/resources/itext/io/font/otf/GposLookupType2Test/DejaVuSans.ttf differ diff --git a/itext.tests/itext.io.tests/resources/itext/io/font/otf/GposLookupType2Test/LICENSE_OFL.txt b/itext.tests/itext.io.tests/resources/itext/io/font/otf/GposLookupType2Test/LICENSE_OFL.txt new file mode 100644 index 0000000000..d952d62c06 --- /dev/null +++ b/itext.tests/itext.io.tests/resources/itext/io/font/otf/GposLookupType2Test/LICENSE_OFL.txt @@ -0,0 +1,92 @@ +This Font Software is licensed under the SIL Open Font License, +Version 1.1. + +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font +creation efforts of academic and linguistic communities, and to +provide a free and open framework in which fonts may be shared and +improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply to +any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software +components as distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, +deleting, or substituting -- in part or in whole -- any of the +components of the Original Version, by changing formats or by porting +the Font Software to a new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, +modify, redistribute, and sell modified and unmodified copies of the +Font Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, in +Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the +corresponding Copyright Holder. This restriction only applies to the +primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created using +the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/itext.tests/itext.io.tests/resources/itext/io/font/otf/GposLookupType2Test/NOTICE.txt b/itext.tests/itext.io.tests/resources/itext/io/font/otf/GposLookupType2Test/NOTICE.txt new file mode 100644 index 0000000000..afc7fd35ee --- /dev/null +++ b/itext.tests/itext.io.tests/resources/itext/io/font/otf/GposLookupType2Test/NOTICE.txt @@ -0,0 +1,3 @@ +This software uses the following test resources under the following licenses: +| NotoSansMyanmar-Regular.ttf | OFL-1.1 | LICENSE-OFL.txt | +| DejaVuSans.ttf | BitstreamCopyright | BitstreamCopyright.txt | diff --git a/itext.tests/itext.io.tests/resources/itext/io/font/otf/GposLookupType2Test/NotoSansMyanmar-Regular.ttf b/itext.tests/itext.io.tests/resources/itext/io/font/otf/GposLookupType2Test/NotoSansMyanmar-Regular.ttf new file mode 100644 index 0000000000..e70e237f6d Binary files /dev/null and b/itext.tests/itext.io.tests/resources/itext/io/font/otf/GposLookupType2Test/NotoSansMyanmar-Regular.ttf differ diff --git a/itext.tests/itext.io.tests/resources/itext/io/font/sharedFontsResourceFiles/NOTICE.txt b/itext.tests/itext.io.tests/resources/itext/io/font/sharedFontsResourceFiles/NOTICE.txt index 1bd85853dd..1a10901d9c 100644 --- a/itext.tests/itext.io.tests/resources/itext/io/font/sharedFontsResourceFiles/NOTICE.txt +++ b/itext.tests/itext.io.tests/resources/itext/io/font/sharedFontsResourceFiles/NOTICE.txt @@ -3,4 +3,5 @@ This software uses the following test resources under the following licenses: | NotoSansTC-Regular.otf | OFL-1.1 | OFL.txt | Based on commit 165c01b46ea533872e002e0785ff17e44f6d97d8 (30.04.2021) from repository: "https://github.com/googlefonts/noto-cjk" | NotoSansSC-Regular.otf | OFL-1.1 | OFL.txt | Based on commit 165c01b46ea533872e002e0785ff17e44f6d97d8 (30.04.2021) from repository: "https://github.com/googlefonts/noto-cjk" | NotoSansCJKjp-Bold.otf | OFL-1.1 | OFL.txt | Based on commit 165c01b46ea533872e002e0785ff17e44f6d97d8 (30.04.2021) from repository: "https://github.com/googlefonts/noto-cjk" -| Puritan2 | OFL-1.1 | OFL.txt | \ No newline at end of file +| Puritan2 | OFL-1.1 | OFL.txt | +| glyphs.ttf, glyphs-fmt-6.ttf | MIT | Derived from https://github.com/RazrFalcon/ttf-parser/tree/337e7d1c08b06478a84c4345f4f289fc2cb9210c/tests/fonts-src | diff --git a/itext.tests/itext.io.tests/resources/itext/io/font/sharedFontsResourceFiles/glyphs-fmt-6.ttf b/itext.tests/itext.io.tests/resources/itext/io/font/sharedFontsResourceFiles/glyphs-fmt-6.ttf new file mode 100644 index 0000000000..941a4cd173 Binary files /dev/null and b/itext.tests/itext.io.tests/resources/itext/io/font/sharedFontsResourceFiles/glyphs-fmt-6.ttf differ diff --git a/itext.tests/itext.io.tests/resources/itext/io/font/sharedFontsResourceFiles/glyphs.ttf b/itext.tests/itext.io.tests/resources/itext/io/font/sharedFontsResourceFiles/glyphs.ttf new file mode 100644 index 0000000000..60436aeb3c Binary files /dev/null and b/itext.tests/itext.io.tests/resources/itext/io/font/sharedFontsResourceFiles/glyphs.ttf differ diff --git a/itext.tests/itext.io.tests/resources/itext/io/font/woff2/w3c/format/cmp_tabledata-transform-glyf-loca-001.ttf b/itext.tests/itext.io.tests/resources/itext/io/font/woff2/w3c/format/cmp_tabledata-transform-glyf-loca-001.ttf deleted file mode 100644 index 65803816de..0000000000 Binary files a/itext.tests/itext.io.tests/resources/itext/io/font/woff2/w3c/format/cmp_tabledata-transform-glyf-loca-001.ttf and /dev/null differ diff --git a/itext.tests/itext.io.tests/resources/itext/io/image/ImageTypeDetectorTest/image.png b/itext.tests/itext.io.tests/resources/itext/io/image/ImageTypeDetectorTest/image.png deleted file mode 100644 index 002a133c4e..0000000000 Binary files a/itext.tests/itext.io.tests/resources/itext/io/image/ImageTypeDetectorTest/image.png and /dev/null differ diff --git a/itext.tests/itext.kernel.tests/Properties/AssemblyInfo.cs b/itext.tests/itext.kernel.tests/Properties/AssemblyInfo.cs index e696372d26..bba5fb9cc3 100644 --- a/itext.tests/itext.kernel.tests/Properties/AssemblyInfo.cs +++ b/itext.tests/itext.kernel.tests/Properties/AssemblyInfo.cs @@ -15,9 +15,9 @@ [assembly: Guid("02e54061-eb72-409d-b2c0-307ce66b57e9")] -[assembly: AssemblyVersion("8.0.5.0")] -[assembly: AssemblyFileVersion("8.0.5.0")] -[assembly: AssemblyInformationalVersion("8.0.5")] +[assembly: AssemblyVersion("9.0.0.0")] +[assembly: AssemblyFileVersion("9.0.0.0")] +[assembly: AssemblyInformationalVersion("9.0.0")] #if !NETSTANDARD2_0 [assembly: NUnit.Framework.Timeout(300000)] diff --git a/itext.tests/itext.kernel.tests/itext/kernel/actions/events/AddFingerPrintEventTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/actions/events/AddFingerPrintEventTest.cs new file mode 100644 index 0000000000..2df7ddd186 --- /dev/null +++ b/itext.tests/itext.kernel.tests/itext/kernel/actions/events/AddFingerPrintEventTest.cs @@ -0,0 +1,70 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Commons.Actions.Data; +using iText.IO.Source; +using iText.Kernel.Logs; +using iText.Kernel.Pdf; +using iText.Test; +using iText.Test.Attributes; + +namespace iText.Kernel.Actions.Events { + [NUnit.Framework.Category("UnitTest")] + public class AddFingerPrintEventTest : ExtendedITextTest { + [NUnit.Framework.Test] + public virtual void NullDocumentTest() { + AddFingerPrintEvent addFingerPrintEvent = new AddFingerPrintEvent(null); + NUnit.Framework.Assert.DoesNotThrow(() => addFingerPrintEvent.DoAction()); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.FINGERPRINT_DISABLED_BUT_NO_REQUIRED_LICENCE)] + public virtual void DisableFingerPrintAGPLTest() { + using (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + using (PdfDocument doc = new PdfDocument(new PdfWriter(outputStream))) { + doc.GetFingerPrint().DisableFingerPrint(); + NUnit.Framework.Assert.DoesNotThrow(() => doc.Close()); + } + } + } + + [NUnit.Framework.Test] + public virtual void EnabledFingerPrintAGPLTest() { + using (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + using (PdfDocument doc = new PdfDocument(new PdfWriter(outputStream))) { + NUnit.Framework.Assert.DoesNotThrow(() => doc.Close()); + } + } + } + + [NUnit.Framework.Test] + public virtual void DisableFingerPrintNoProcessorForProductTest() { + using (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + using (PdfDocument doc = new PdfDocument(new PdfWriter(outputStream))) { + ProductData productData = new ProductData("public product name", "product name", "1", 2000, 2024); + doc.GetFingerPrint().RegisterProduct(productData); + NUnit.Framework.Assert.DoesNotThrow(() => doc.Close()); + } + } + } + } +} diff --git a/itext.tests/itext.kernel.tests/itext/kernel/crypto/pdfencryption/PdfEncryptionTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/crypto/pdfencryption/PdfEncryptionTest.cs index 58af785e65..3a37d3f5a4 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/crypto/pdfencryption/PdfEncryptionTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/crypto/pdfencryption/PdfEncryptionTest.cs @@ -223,7 +223,7 @@ public virtual void MetadataReadingInEncryptedDoc() { PdfReader reader = new PdfReader(sourceFolder + "encryptedWithPlainMetadata.pdf", new ReaderProperties().SetPassword (PdfEncryptionTestUtils.OWNER)); PdfDocument doc = new PdfDocument(reader); - XMPMeta xmpMeta = XMPMetaFactory.ParseFromBuffer(doc.GetXmpMetadata()); + XMPMeta xmpMeta = doc.GetXmpMetadata(); XMPProperty creatorToolXmp = xmpMeta.GetProperty(XMPConst.NS_XMP, "CreatorTool"); doc.Close(); NUnit.Framework.Assert.IsNotNull(creatorToolXmp); @@ -310,6 +310,37 @@ public virtual void EncryptWithPasswordAes128EmbeddedFilesOnly() { , textContent, ERROR_IS_EXPECTED); } + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void EncryptWithPasswordAes256EmbeddedFilesOnly() { + String filename = "encryptWithPasswordAes256EmbeddedFilesOnly.pdf"; + int encryptionType = EncryptionConstants.ENCRYPTION_AES_256 | EncryptionConstants.EMBEDDED_FILES_ONLY; + String outFileName = destinationFolder + filename; + int permissions = EncryptionConstants.ALLOW_SCREENREADERS; + PdfWriter writer = CompareTool.CreateTestPdfWriter(outFileName, new WriterProperties().SetStandardEncryption + (PdfEncryptionTestUtils.USER, PdfEncryptionTestUtils.OWNER, permissions, encryptionType).AddXmpMetadata + ().SetPdfVersion(PdfVersion.PDF_2_0)); + PdfDocument document = new PdfDocument(writer); + document.GetDocumentInfo().SetMoreInfo(PdfEncryptionTestUtils.CUSTOM_INFO_ENTRY_KEY, PdfEncryptionTestUtils + .CUSTOM_INFO_ENTRY_VALUE); + PdfPage page = document.AddNewPage(); + String textContent = "Hello world!"; + PdfEncryptionTestUtils.WriteTextBytesOnPageContent(page, textContent); + String descripton = "encryptedFile"; + String path = sourceFolder + "pageWithContent.pdf"; + document.AddFileAttachment(descripton, PdfFileSpec.CreateEmbeddedFileSpec(document, path, descripton, path + , null, null)); + page.Flush(); + document.Close(); + //TODO DEVSIX-5355 Specific crypto filters for EFF StmF and StrF are not supported at the moment. + // However we can read embedded files only mode. + bool ERROR_IS_EXPECTED = false; + encryptionUtil.CheckDecryptedWithPasswordContent(destinationFolder + filename, PdfEncryptionTestUtils.OWNER + , textContent, ERROR_IS_EXPECTED); + encryptionUtil.CheckDecryptedWithPasswordContent(destinationFolder + filename, PdfEncryptionTestUtils.USER + , textContent, ERROR_IS_EXPECTED); + } + [NUnit.Framework.Test] [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] public virtual void EncryptAes256Pdf2NotEncryptMetadata() { @@ -363,7 +394,7 @@ public virtual void EncryptWithPasswordAes256Pdf2() { [NUnit.Framework.Test] [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] - [LogMessage(VersionConforming.DEPRECATED_ENCRYPTION_ALGORITHMS)] + [LogMessage(VersionConforming.DEPRECATED_ENCRYPTION_ALGORITHMS, Count = 2)] public virtual void EncryptWithPasswordAes128Pdf2() { String filename = "encryptWithPasswordAes128Pdf2.pdf"; int encryptionType = EncryptionConstants.ENCRYPTION_AES_128; @@ -551,7 +582,7 @@ public virtual void CheckEncryptedWithPasswordDocumentAppending(String filename, newPage.Put(PdfName.Default, new PdfString("Hello world string")); PdfEncryptionTestUtils.WriteTextBytesOnPageContent(newPage, "Hello world page_2!"); document.Close(); - CompareTool compareTool = new CompareTool().EnableEncryptionCompare(); + CompareTool compareTool = new CompareTool().EnableEncryptionCompare(false); String compareResult = compareTool.CompareByContent(outFileName, sourceFolder + "cmp_appended_" + filename , destinationFolder, "diff_", PdfEncryptionTestUtils.USER, PdfEncryptionTestUtils.USER); if (compareResult != null) { diff --git a/itext.tests/itext.kernel.tests/itext/kernel/crypto/pdfencryption/PdfEncryptionTestUtils.cs b/itext.tests/itext.kernel.tests/itext/kernel/crypto/pdfencryption/PdfEncryptionTestUtils.cs index c977b6beaf..b683b704c1 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/crypto/pdfencryption/PdfEncryptionTestUtils.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/crypto/pdfencryption/PdfEncryptionTestUtils.cs @@ -52,7 +52,7 @@ public PdfEncryptionTestUtils(String destinationFolder, String sourceFolder) { public virtual void CompareEncryptedPdf(String filename) { CheckDecryptedWithPasswordContent(destinationFolder + filename, OWNER, PAGE_TEXT_CONTENT); CheckDecryptedWithPasswordContent(destinationFolder + filename, USER, PAGE_TEXT_CONTENT); - CompareTool compareTool = new CompareTool().EnableEncryptionCompare(); + CompareTool compareTool = new CompareTool().EnableEncryptionCompare(false); String compareResult = compareTool.CompareByContent(destinationFolder + filename, sourceFolder + "cmp_" + filename, destinationFolder, "diff_", USER, USER); if (compareResult != null) { diff --git a/itext.tests/itext.kernel.tests/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest.cs index 297b472ad9..cb156c42f8 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest.cs @@ -185,7 +185,7 @@ private void EncryptAes256AndCheck(String filename, byte[] ownerPassword) { document.Close(); encryptionUtil.CheckDecryptedWithPasswordContent(destinationFolder + filename, ownerPassword, PdfEncryptionTestUtils .PAGE_TEXT_CONTENT); - CompareTool compareTool = new CompareTool().EnableEncryptionCompare(); + CompareTool compareTool = new CompareTool().EnableEncryptionCompare(false); String compareResult = compareTool.CompareByContent(destinationFolder + filename, sourceFolder + "cmp_" + filename, destinationFolder, "diff_", ownerPassword, ownerPassword); if (compareResult != null) { diff --git a/itext.tests/itext.kernel.tests/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest.cs new file mode 100644 index 0000000000..d63b4c36df --- /dev/null +++ b/itext.tests/itext.kernel.tests/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest.cs @@ -0,0 +1,200 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using System.Collections.Generic; +using NUnit.Framework; +using iText.Bouncycastleconnector; +using iText.Commons.Bouncycastle; +using iText.Commons.Bouncycastle.Cert; +using iText.Commons.Bouncycastle.Crypto; +using iText.Commons.Utils; +using iText.Kernel.Crypto; +using iText.Kernel.Exceptions; +using iText.Kernel.Logs; +using iText.Kernel.Pdf; +using iText.Kernel.Utils; +using iText.Test; +using iText.Test.Attributes; + +namespace iText.Kernel.Crypto.Securityhandler { + [NUnit.Framework.Category("BouncyCastleIntegrationTest")] + public class PubSecHandlerUsingAesGcmTest : ExtendedITextTest { + public static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + .CurrentContext.TestDirectory) + "/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/"; + + public static readonly String DESTINATION_FOLDER = NUnit.Framework.TestContext.CurrentContext.TestDirectory + + "/test/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/"; + + private static readonly IBouncyCastleFactory FACTORY = BouncyCastleFactoryCreator.GetFactory(); + + private static readonly char[] PASSWORD = "testpassphrase".ToCharArray(); + + [NUnit.Framework.OneTimeSetUp] + public static void SetUp() { + CreateOrClearDestinationFolder(DESTINATION_FOLDER); + } + + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + [NUnit.Framework.Test] + public virtual void TestSimpleEncryptDecryptTest() { + try { + BouncyCastleFactoryCreator.GetFactory().IsEncryptionFeatureSupported(0, true); + } + catch (Exception) { + NUnit.Framework.Assume.That(false); + } + NUnit.Framework.Assume.That(!BouncyCastleFactoryCreator.GetFactory().IsInApprovedOnlyMode()); + String fileName = "simpleEncryptDecrypt.pdf"; + String srcFile = SOURCE_FOLDER + fileName; + String outFile = DESTINATION_FOLDER + fileName; + DoEncrypt(srcFile, outFile, true); + DecryptWithCertificate(fileName, DESTINATION_FOLDER, "test.cer", "test.pem"); + } + + [LogMessage(VersionConforming.NOT_SUPPORTED_AES_GCM, Ignore = true)] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + [NUnit.Framework.Test] + public virtual void TestSimpleEncryptDecryptPdf17Test() { + try { + BouncyCastleFactoryCreator.GetFactory().IsEncryptionFeatureSupported(0, true); + } + catch (Exception) { + NUnit.Framework.Assume.That(false); + } + NUnit.Framework.Assume.That(!BouncyCastleFactoryCreator.GetFactory().IsInApprovedOnlyMode()); + String fileName = "simpleEncryptDecrypt_1_7.pdf"; + String srcFile = SOURCE_FOLDER + fileName; + String outFile = DESTINATION_FOLDER + fileName; + DoEncrypt(srcFile, outFile, false); + DecryptWithCertificate(fileName, DESTINATION_FOLDER, "test.cer", "test.pem"); + } + + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + [NUnit.Framework.Test] + public virtual void DecryptExternalFileTest() { + try { + BouncyCastleFactoryCreator.GetFactory().IsEncryptionFeatureSupported(0, true); + } + catch (Exception) { + NUnit.Framework.Assume.That(false); + } + DecryptWithCertificate("externalFile.pdf", SOURCE_FOLDER, "decrypter.cert.pem", "signerkey.pem"); + } + + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + [NUnit.Framework.Test] + public virtual void InvalidCryptFilterTest() { + String fileName = "invalidCryptFilter.pdf"; + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => DecryptWithCertificate(fileName, SOURCE_FOLDER + , "test.cer", "test.pem")); + NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.NO_COMPATIBLE_ENCRYPTION_FOUND, e.Message); + } + + [NUnit.Framework.Test] + public virtual void EncryptPdfWithMissingCFTest() { + IPrivateKey certificateKey = PemFileHelper.ReadPrivateKeyFromPemFile(FileUtil.GetInputStreamForFile(SOURCE_FOLDER + + "signerkey.pem"), PASSWORD); + IX509Certificate certificate = CryptoUtil.ReadPublicCertificate(FileUtil.GetInputStreamForFile(SOURCE_FOLDER + + "decrypter.cert.pem")); + Dictionary encMap = new Dictionary(); + encMap.Put(PdfName.V, new PdfNumber(6)); + encMap.Put(PdfName.EncryptMetadata, PdfBoolean.TRUE); + PdfDictionary dictionary = new PdfDictionary(encMap); + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => new PdfEncryption(dictionary, certificateKey + , certificate)); + NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.CF_NOT_FOUND_ENCRYPTION, e.Message); + } + + [NUnit.Framework.Test] + public virtual void EncryptPdfWithMissingDefaultCryptFilterTest() { + IPrivateKey certificateKey = PemFileHelper.ReadPrivateKeyFromPemFile(FileUtil.GetInputStreamForFile(SOURCE_FOLDER + + "signerkey.pem"), PASSWORD); + IX509Certificate certificate = CryptoUtil.ReadPublicCertificate(FileUtil.GetInputStreamForFile(SOURCE_FOLDER + + "decrypter.cert.pem")); + Dictionary encMap = new Dictionary(); + encMap.Put(PdfName.V, new PdfNumber(6)); + PdfDictionary embeddedFilesDict = new PdfDictionary(); + embeddedFilesDict.Put(PdfName.FlateDecode, new PdfDictionary()); + encMap.Put(PdfName.CF, embeddedFilesDict); + PdfDictionary dictionary = new PdfDictionary(encMap); + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => new PdfEncryption(dictionary, certificateKey + , certificate)); + NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.DEFAULT_CRYPT_FILTER_NOT_FOUND_ENCRYPTION, + e.Message); + } + + [NUnit.Framework.Test] + public virtual void EncryptPdfWithMissingCFMTest() { + IPrivateKey certificateKey = PemFileHelper.ReadPrivateKeyFromPemFile(FileUtil.GetInputStreamForFile(SOURCE_FOLDER + + "signerkey.pem"), PASSWORD); + IX509Certificate certificate = CryptoUtil.ReadPublicCertificate(FileUtil.GetInputStreamForFile(SOURCE_FOLDER + + "decrypter.cert.pem")); + Dictionary encMap = new Dictionary(); + encMap.Put(PdfName.V, new PdfNumber(6)); + PdfDictionary embeddedFilesDict = new PdfDictionary(); + embeddedFilesDict.Put(PdfName.DefaultCryptFilter, new PdfDictionary()); + encMap.Put(PdfName.CF, embeddedFilesDict); + PdfDictionary dictionary = new PdfDictionary(encMap); + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => new PdfEncryption(dictionary, certificateKey + , certificate)); + NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.NO_COMPATIBLE_ENCRYPTION_FOUND, e.Message); + } + + private void DoEncrypt(String input, String output, bool isPdf20) { + IX509Certificate certificate = CryptoUtil.ReadPublicCertificate(FileUtil.GetInputStreamForFile(SOURCE_FOLDER + + "test.cer")); + WriterProperties writerProperties = new WriterProperties().SetPublicKeyEncryption(new IX509Certificate[] { + certificate }, new int[] { EncryptionConstants.ALLOW_PRINTING }, EncryptionConstants.ENCRYPTION_AES_GCM + ); + if (isPdf20) { + writerProperties.SetPdfVersion(PdfVersion.PDF_2_0); + } + // Instantiate input/output document. + using (PdfDocument docIn = new PdfDocument(new PdfReader(input))) { + using (PdfDocument docOut = new PdfDocument(new PdfWriter(output, writerProperties))) { + // Copy one page from input to output. + docIn.CopyPagesTo(1, 1, docOut); + } + } + } + + private void DecryptWithCertificate(String fileName, String srcFileFolder, String certificateName, String + privateKeyName) { + String srcFile = srcFileFolder + fileName; + String cmpFile = SOURCE_FOLDER + "cmp_" + fileName; + String outFile = DESTINATION_FOLDER + "decrypted_" + fileName; + IX509Certificate certificate = CryptoUtil.ReadPublicCertificate(FileUtil.GetInputStreamForFile(SOURCE_FOLDER + + certificateName)); + IPrivateKey privateKey = PemFileHelper.ReadPrivateKeyFromPemFile(FileUtil.GetInputStreamForFile(SOURCE_FOLDER + + privateKeyName), PASSWORD); + ReaderProperties readerProperties = new ReaderProperties().SetPublicKeySecurityParams(certificate, privateKey + ); + PdfDocument ignored = new PdfDocument(new PdfReader(srcFile, readerProperties), new PdfWriter(outFile)); + ignored.Close(); + String errorMessage = new CompareTool().CompareByContent(outFile, cmpFile, DESTINATION_FOLDER, "diff_"); + if (errorMessage != null) { + NUnit.Framework.Assert.Fail(errorMessage); + } + } + } +} diff --git a/itext.tests/itext.kernel.tests/itext/kernel/crypto/securityhandler/StandardHandlerUsingAesGcmTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/crypto/securityhandler/StandardHandlerUsingAesGcmTest.cs new file mode 100644 index 0000000000..53c1099c7e --- /dev/null +++ b/itext.tests/itext.kernel.tests/itext/kernel/crypto/securityhandler/StandardHandlerUsingAesGcmTest.cs @@ -0,0 +1,282 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using System.Collections.Generic; +using iText.Bouncycastleconnector; +using iText.Commons.Bouncycastle; +using iText.Kernel.Exceptions; +using iText.Kernel.Logs; +using iText.Kernel.Pdf; +using iText.Kernel.Utils; +using iText.Kernel.Utils.Objectpathitems; +using iText.Test; +using iText.Test.Attributes; + +namespace iText.Kernel.Crypto.Securityhandler { + [NUnit.Framework.Category("BouncyCastleIntegrationTest")] + public class StandardHandlerUsingAesGcmTest : ExtendedITextTest { + public static readonly String SRC = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + .CurrentContext.TestDirectory) + "/resources/itext/kernel/crypto/securityhandler/StandardHandlerUsingAesGcmTest/"; + + public static readonly String DEST = NUnit.Framework.TestContext.CurrentContext.TestDirectory + "/test/itext/kernel/crypto/securityhandler/StandardHandlerUsingAesGcmTest/"; + + private static readonly IBouncyCastleFactory FACTORY = BouncyCastleFactoryCreator.GetFactory(); + + private static readonly byte[] OWNER_PASSWORD = "supersecret".GetBytes(System.Text.Encoding.UTF8); + + private static readonly byte[] USER_PASSWORD = "secret".GetBytes(System.Text.Encoding.UTF8); + + [NUnit.Framework.OneTimeSetUp] + public static void SetUp() { + CreateOrClearDestinationFolder(DEST); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void SimpleEncryptDecryptTest() { + String srcFile = SRC + "simpleDocument.pdf"; + String encryptedCmpFile = SRC + "cmp_encryptedSimpleDocument.pdf"; + String outFile = DEST + "simpleEncryptDecrypt.pdf"; + // Set usage permissions. + int perms = EncryptionConstants.ALLOW_PRINTING | EncryptionConstants.ALLOW_DEGRADED_PRINTING; + WriterProperties wProps = new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0).SetStandardEncryption(USER_PASSWORD + , OWNER_PASSWORD, perms, EncryptionConstants.ENCRYPTION_AES_GCM); + // Instantiate input/output document. + using (PdfDocument docIn = new PdfDocument(new PdfReader(srcFile))) { + using (PdfDocument docOut = new PdfDocument(new PdfWriter(outFile, wProps))) { + // Copy one page from input to output. + docIn.CopyPagesTo(1, 1, docOut); + } + } + new CToolNoDeveloperExtension().CompareByContent(outFile, srcFile, DEST, "diff", USER_PASSWORD, null); + new CompareTool().CompareByContent(outFile, encryptedCmpFile, DEST, "diff", USER_PASSWORD, USER_PASSWORD); + } + + [NUnit.Framework.Test] + [LogMessage(VersionConforming.NOT_SUPPORTED_AES_GCM)] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void SimpleEncryptDecryptPdf15Test() { + String srcFile = SRC + "simpleDocument.pdf"; + String outFile = DEST + "notSupportedVersionDocument.pdf"; + int perms = EncryptionConstants.ALLOW_PRINTING | EncryptionConstants.ALLOW_DEGRADED_PRINTING; + WriterProperties wProps = new WriterProperties().SetStandardEncryption(USER_PASSWORD, OWNER_PASSWORD, perms + , EncryptionConstants.ENCRYPTION_AES_GCM); + PdfDocument ignored = new PdfDocument(new PdfReader(srcFile), new PdfWriter(outFile, wProps)); + ignored.Close(); + new CToolNoDeveloperExtension().CompareByContent(outFile, srcFile, DEST, "diff", USER_PASSWORD, null); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void KnownOutputTest() { + String srcFile = SRC + "encryptedDocument.pdf"; + String outFile = DEST + "encryptedDocument.pdf"; + String cmpFile = SRC + "simpleDocument.pdf"; + using (PdfDocument ignored = new PdfDocument(new PdfReader(srcFile, new ReaderProperties().SetPassword(OWNER_PASSWORD + )), new PdfWriter(outFile))) { + } + // We need to copy the source file to the destination folder to be able to compare pdf files in android. + new CompareTool().CompareByContent(outFile, cmpFile, DEST, "diff", USER_PASSWORD, null); + } + + // In all these tampered files, the stream content of object 14 has been modified. + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + [NUnit.Framework.Test] + public virtual void MacTamperedTest() { + String srcFile = SRC + "encryptedDocumentTamperedMac.pdf"; + AssertTampered(srcFile); + } + + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + [NUnit.Framework.Test] + public virtual void InitVectorTamperedTest() { + String srcFile = SRC + "encryptedDocumentTamperedIv.pdf"; + AssertTampered(srcFile); + } + + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + [NUnit.Framework.Test] + public virtual void CiphertextTamperedTest() { + String srcFile = SRC + "encryptedDocumentTamperedCiphertext.pdf"; + AssertTampered(srcFile); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.ENCRYPTION_ENTRIES_P_AND_ENCRYPT_METADATA_NOT_CORRESPOND_PERMS_ENTRY + )] + public virtual void PdfEncryptionWithEmbeddedFilesTest() { + byte[] documentId = new byte[] { (byte)88, (byte)189, (byte)192, (byte)48, (byte)240, (byte)200, (byte)87, + (byte)183, (byte)244, (byte)119, (byte)224, (byte)109, (byte)226, (byte)173, (byte)32, (byte)90 }; + byte[] password = new byte[] { (byte)115, (byte)101, (byte)99, (byte)114, (byte)101, (byte)116 }; + Dictionary encMap = new Dictionary(); + encMap.Put(PdfName.R, new PdfNumber(7)); + encMap.Put(PdfName.V, new PdfNumber(6)); + encMap.Put(PdfName.P, new PdfNumber(-1852)); + encMap.Put(PdfName.EFF, PdfName.FlateDecode); + encMap.Put(PdfName.StmF, PdfName.Identity); + encMap.Put(PdfName.StrF, PdfName.Identity); + PdfDictionary embeddedFilesDict = new PdfDictionary(); + embeddedFilesDict.Put(PdfName.FlateDecode, new PdfDictionary()); + PdfDictionary cfmDict = new PdfDictionary(); + cfmDict.Put(PdfName.CFM, PdfName.AESV4); + embeddedFilesDict.Put(PdfName.StdCF, cfmDict); + encMap.Put(PdfName.CF, embeddedFilesDict); + encMap.Put(PdfName.EncryptMetadata, PdfBoolean.FALSE); + encMap.Put(PdfName.O, new PdfString("\u0006¡Ê\u009A<@\u009DÔG\u0013&\u008C5r\u0096\u0081i!\u0091\u000Fªìh=±\u0091\u0006Að¨\u008D\"¼\u0018?õ\u001DNó»{y\u0091)\u0090vâý" + )); + encMap.Put(PdfName.U, new PdfString("ôY\u009DÃ\u0017Ý·Ü\u0097vØ\fJ\u0099c\u0004áݹÔB\u0084·9÷\u008F\u009D-¿xnkþ\u0086Æ\u0088º\u0086ÜTÿëÕï\u0018\u009D\u0016-" + )); + encMap.Put(PdfName.OE, new PdfString("5Ë\u009EUÔº\u0007 Nøß\u0094ä\u001DÄ_wnù\u001AKò-\u007F\u00ADQ²Ø \u001FSJ" + )); + encMap.Put(PdfName.UE, new PdfString("\u000B:\rÆ\u0004\u0094Ûìkþ,ôBS9ü\u001E³\u0088\u001D(\u0098ºÀ\u0010½\u0082.'`kñ" + )); + encMap.Put(PdfName.Perms, new PdfString("\u008F»\u0080.òç\u0011\u001Et\u0012\u00905\u001B\u0019\u0014«")); + PdfDictionary dictionary = new PdfDictionary(encMap); + PdfEncryption encryption = new PdfEncryption(dictionary, password, documentId); + NUnit.Framework.Assert.IsTrue(encryption.IsEmbeddedFilesOnly()); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void PdfEncryptionWithMetadataTest() { + byte[] documentId = new byte[] { (byte)88, (byte)189, (byte)192, (byte)48, (byte)240, (byte)200, (byte)87, + (byte)183, (byte)244, (byte)119, (byte)224, (byte)109, (byte)226, (byte)173, (byte)32, (byte)90 }; + byte[] password = new byte[] { (byte)115, (byte)101, (byte)99, (byte)114, (byte)101, (byte)116 }; + Dictionary encMap = new Dictionary(); + encMap.Put(PdfName.R, new PdfNumber(7)); + encMap.Put(PdfName.V, new PdfNumber(6)); + encMap.Put(PdfName.P, new PdfNumber(-1852)); + encMap.Put(PdfName.StmF, PdfName.StdCF); + encMap.Put(PdfName.StrF, PdfName.StdCF); + PdfDictionary embeddedFilesDict = new PdfDictionary(); + embeddedFilesDict.Put(PdfName.FlateDecode, new PdfDictionary()); + PdfDictionary cfmDict = new PdfDictionary(); + cfmDict.Put(PdfName.CFM, PdfName.AESV4); + embeddedFilesDict.Put(PdfName.StdCF, cfmDict); + encMap.Put(PdfName.CF, embeddedFilesDict); + encMap.Put(PdfName.EncryptMetadata, PdfBoolean.TRUE); + encMap.Put(PdfName.O, new PdfString("\u0006¡Ê\u009A<@\u009DÔG\u0013&\u008C5r\u0096\u0081i!\u0091\u000Fªìh=±\u0091\u0006Að¨\u008D\"¼\u0018?õ\u001DNó»{y\u0091)\u0090vâý" + )); + encMap.Put(PdfName.U, new PdfString("ôY\u009DÃ\u0017Ý·Ü\u0097vØ\fJ\u0099c\u0004áݹÔB\u0084·9÷\u008F\u009D-¿xnkþ\u0086Æ\u0088º\u0086ÜTÿëÕï\u0018\u009D\u0016-" + )); + encMap.Put(PdfName.OE, new PdfString("5Ë\u009EUÔº\u0007 Nøß\u0094ä\u001DÄ_wnù\u001AKò-\u007F\u00ADQ²Ø \u001FSJ" + )); + encMap.Put(PdfName.UE, new PdfString("\u000B:\rÆ\u0004\u0094Ûìkþ,ôBS9ü\u001E³\u0088\u001D(\u0098ºÀ\u0010½\u0082.'`kñ" + )); + encMap.Put(PdfName.Perms, new PdfString("\u008F»\u0080.òç\u0011\u001Et\u0012\u00905\u001B\u0019\u0014«")); + PdfDictionary dictionary = new PdfDictionary(encMap); + PdfEncryption encryption = new PdfEncryption(dictionary, password, documentId); + NUnit.Framework.Assert.IsTrue(encryption.IsMetadataEncrypted()); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void EncryptPdfWithMissingCFTest() { + byte[] documentId = new byte[] { (byte)88, (byte)189, (byte)192, (byte)48, (byte)240, (byte)200, (byte)87, + (byte)183, (byte)244, (byte)119, (byte)224, (byte)109, (byte)226, (byte)173, (byte)32, (byte)90 }; + byte[] password = new byte[] { (byte)115, (byte)101, (byte)99, (byte)114, (byte)101, (byte)116 }; + Dictionary encMap = new Dictionary(); + encMap.Put(PdfName.R, new PdfNumber(7)); + encMap.Put(PdfName.V, new PdfNumber(6)); + PdfDictionary dictionary = new PdfDictionary(encMap); + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => new PdfEncryption(dictionary, password + , documentId)); + NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.CF_NOT_FOUND_ENCRYPTION, e.Message); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void EncryptPdfWithMissingStdCFTest() { + byte[] documentId = new byte[] { (byte)88, (byte)189, (byte)192, (byte)48, (byte)240, (byte)200, (byte)87, + (byte)183, (byte)244, (byte)119, (byte)224, (byte)109, (byte)226, (byte)173, (byte)32, (byte)90 }; + byte[] password = new byte[] { (byte)115, (byte)101, (byte)99, (byte)114, (byte)101, (byte)116 }; + Dictionary encMap = new Dictionary(); + encMap.Put(PdfName.R, new PdfNumber(7)); + encMap.Put(PdfName.V, new PdfNumber(6)); + PdfDictionary embeddedFilesDict = new PdfDictionary(); + embeddedFilesDict.Put(PdfName.FlateDecode, new PdfDictionary()); + PdfDictionary cfmDict = new PdfDictionary(); + cfmDict.Put(PdfName.CFM, PdfName.AESV4); + encMap.Put(PdfName.CF, embeddedFilesDict); + PdfDictionary dictionary = new PdfDictionary(encMap); + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => new PdfEncryption(dictionary, password + , documentId)); + NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.STDCF_NOT_FOUND_ENCRYPTION, e.Message); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void EncryptPdfWithMissingCFMTest() { + byte[] documentId = new byte[] { (byte)88, (byte)189, (byte)192, (byte)48, (byte)240, (byte)200, (byte)87, + (byte)183, (byte)244, (byte)119, (byte)224, (byte)109, (byte)226, (byte)173, (byte)32, (byte)90 }; + byte[] password = new byte[] { (byte)115, (byte)101, (byte)99, (byte)114, (byte)101, (byte)116 }; + Dictionary encMap = new Dictionary(); + encMap.Put(PdfName.R, new PdfNumber(7)); + encMap.Put(PdfName.V, new PdfNumber(6)); + encMap.Put(PdfName.P, new PdfNumber(-1852)); + encMap.Put(PdfName.StmF, PdfName.StdCF); + encMap.Put(PdfName.StrF, PdfName.StdCF); + PdfDictionary embeddedFilesDict = new PdfDictionary(); + embeddedFilesDict.Put(PdfName.FlateDecode, new PdfDictionary()); + PdfDictionary cfmDict = new PdfDictionary(); + embeddedFilesDict.Put(PdfName.StdCF, cfmDict); + encMap.Put(PdfName.CF, embeddedFilesDict); + PdfDictionary dictionary = new PdfDictionary(encMap); + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => new PdfEncryption(dictionary, password + , documentId)); + NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.NO_COMPATIBLE_ENCRYPTION_FOUND, e.Message); + } + + private void AssertTampered(String outFile) { + using (PdfDocument pdfDoc = new PdfDocument(new PdfReader(outFile, new ReaderProperties().SetPassword(USER_PASSWORD + )))) { + PdfObject obj = pdfDoc.GetPdfObject(14); + if (obj != null && obj.IsStream()) { + // Get decoded stream bytes. + NUnit.Framework.Assert.Catch(typeof(Exception), () => ((PdfStream)obj).GetBytes()); + } + } + } + } + +//\cond DO_NOT_DOCUMENT + // Outside test class for porting + internal class CToolNoDeveloperExtension : CompareTool { + protected internal override bool CompareObjects(PdfObject outObj, PdfObject cmpObj, ObjectPath currentPath + , CompareTool.CompareResult compareResult) { + if (outObj != null && outObj.IsDictionary()) { + if (((PdfDictionary)outObj).Get(PdfName.ISO_) != null) { + return true; + } + } + if (cmpObj != null && cmpObj.IsDictionary()) { + if (((PdfDictionary)cmpObj).Get(PdfName.ISO_) != null) { + return true; + } + } + return base.CompareObjects(outObj, cmpObj, currentPath, compareResult); + } + } +//\endcond +} diff --git a/itext.tests/itext.kernel.tests/itext/kernel/font/PdfType3FontTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/font/PdfType3FontTest.cs index f3df9f57e6..fed5ba6fde 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/font/PdfType3FontTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/font/PdfType3FontTest.cs @@ -45,7 +45,7 @@ public virtual void AddDifferentGlyphsInConstructorTest() { dictionary.Put(PdfName.Widths, new PdfArray()); dictionary.Put(PdfName.ToUnicode, PdfName.IdentityH); dictionary.Put(PdfName.Encoding, new PdfName("zapfdingbatsencoding")); - PdfType3Font type3Font = new _PdfType3Font_62(dictionary); + PdfType3Font type3Font = new _PdfType3Font_61(dictionary); NUnit.Framework.Assert.IsNotNull(type3Font.GetFontProgram()); int spaceGlyphCode = 32; Glyph glyph = type3Font.GetFontProgram().GetGlyph(spaceGlyphCode); @@ -55,8 +55,8 @@ public virtual void AddDifferentGlyphsInConstructorTest() { NUnit.Framework.Assert.AreEqual(new Glyph(AGlyphCode, 0, new char[] { 'A' }), glyph); } - private sealed class _PdfType3Font_62 : PdfType3Font { - public _PdfType3Font_62(PdfDictionary baseArg1) + private sealed class _PdfType3Font_61 : PdfType3Font { + public _PdfType3Font_61(PdfDictionary baseArg1) : base(baseArg1) { } @@ -74,7 +74,7 @@ public virtual void AddAlreadyExistingGlyphTest() { charProcs.Put(new PdfName("A"), new PdfStream()); dictionary.Put(PdfName.CharProcs, charProcs); dictionary.Put(PdfName.Widths, new PdfArray()); - PdfType3Font type3Font = new _PdfType3Font_87(dictionary); + PdfType3Font type3Font = new _PdfType3Font_86(dictionary); Type3Glyph type3Glyph = type3Font.AddGlyph('A', 1, 2, 3, 5, 8); NUnit.Framework.Assert.AreEqual(0, type3Glyph.GetWx(), EPS); NUnit.Framework.Assert.AreEqual(0, type3Glyph.GetLlx(), EPS); @@ -83,8 +83,8 @@ public virtual void AddAlreadyExistingGlyphTest() { NUnit.Framework.Assert.AreEqual(0, type3Glyph.GetUry(), EPS); } - private sealed class _PdfType3Font_87 : PdfType3Font { - public _PdfType3Font_87(PdfDictionary baseArg1) + private sealed class _PdfType3Font_86 : PdfType3Font { + public _PdfType3Font_86(PdfDictionary baseArg1) : base(baseArg1) { } @@ -145,7 +145,7 @@ public virtual void ContainsGlyphTest() { PdfDictionary charProcs = new PdfDictionary(); dictionary.Put(PdfName.CharProcs, charProcs); dictionary.Put(PdfName.Widths, new PdfArray()); - PdfType3Font type3Font = new _PdfType3Font_157(dictionary); + PdfType3Font type3Font = new _PdfType3Font_156(dictionary); NUnit.Framework.Assert.IsFalse(type3Font.ContainsGlyph(333)); NUnit.Framework.Assert.IsFalse(type3Font.ContainsGlyph(-5)); NUnit.Framework.Assert.IsFalse(type3Font.ContainsGlyph(32)); @@ -155,8 +155,8 @@ public virtual void ContainsGlyphTest() { NUnit.Framework.Assert.IsTrue(type3Font.ContainsGlyph(65)); } - private sealed class _PdfType3Font_157 : PdfType3Font { - public _PdfType3Font_157(PdfDictionary baseArg1) + private sealed class _PdfType3Font_156 : PdfType3Font { + public _PdfType3Font_156(PdfDictionary baseArg1) : base(baseArg1) { } @@ -192,14 +192,14 @@ public virtual void FillFontDescriptorTest() { String fontStretch = "test"; fontDescriptor.Put(PdfName.FontStretch, new PdfName(fontStretch)); dictionary.Put(PdfName.FontDescriptor, fontDescriptor); - PdfType3Font type3Font = new _PdfType3Font_201(dictionary); + PdfType3Font type3Font = new _PdfType3Font_200(dictionary); NUnit.Framework.Assert.IsNotNull(type3Font.fontProgram); NUnit.Framework.Assert.IsNotNull(type3Font.fontProgram.GetFontNames()); NUnit.Framework.Assert.AreEqual(fontStretch, type3Font.fontProgram.GetFontNames().GetFontStretch()); } - private sealed class _PdfType3Font_201 : PdfType3Font { - public _PdfType3Font_201(PdfDictionary baseArg1) + private sealed class _PdfType3Font_200 : PdfType3Font { + public _PdfType3Font_200(PdfDictionary baseArg1) : base(baseArg1) { } diff --git a/itext.tests/itext.kernel.tests/itext/kernel/geom/PointTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/geom/PointTest.cs index 4074756b88..a4bb8d3670 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/geom/PointTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/geom/PointTest.cs @@ -31,8 +31,8 @@ public class PointTest : ExtendedITextTest { [NUnit.Framework.Test] public virtual void DefaultConstructorTest() { Point first = new Point(); - NUnit.Framework.Assert.AreEqual(0, first.x, EPSILON_COMPARISON); - NUnit.Framework.Assert.AreEqual(0, first.y, EPSILON_COMPARISON); + NUnit.Framework.Assert.AreEqual(0, first.GetX(), EPSILON_COMPARISON); + NUnit.Framework.Assert.AreEqual(0, first.GetY(), EPSILON_COMPARISON); } [NUnit.Framework.Test] @@ -45,15 +45,8 @@ public virtual void DoubleParamConstructorTest() { [NUnit.Framework.Test] public virtual void IntParamConstructorTest() { Point first = new Point(2, 3); - NUnit.Framework.Assert.AreEqual(2, first.x, EPSILON_COMPARISON); - NUnit.Framework.Assert.AreEqual(3, first.y, EPSILON_COMPARISON); - } - - [NUnit.Framework.Test] - public virtual void CopyConstructorTest() { - Point second = new Point(new Point(0.13, 1.1)); - NUnit.Framework.Assert.AreEqual(0.13, second.GetX(), EPSILON_COMPARISON); - NUnit.Framework.Assert.AreEqual(1.1, second.GetY(), EPSILON_COMPARISON); + NUnit.Framework.Assert.AreEqual(2, first.GetX(), EPSILON_COMPARISON); + NUnit.Framework.Assert.AreEqual(3, first.GetY(), EPSILON_COMPARISON); } [NUnit.Framework.Test] @@ -87,52 +80,13 @@ public virtual void NotEqualsToNullTest() { NUnit.Framework.Assert.IsFalse(first.Equals(null)); } - [NUnit.Framework.Test] - public virtual void DistanceSquareBetweenCoordinatesTest() { - Point first = new Point(1, 1); - Point second = new Point(1.1, 1.1); - double expected = 0.02; - NUnit.Framework.Assert.AreEqual(expected, Point.DistanceSq(first.x, first.y, second.x, second.y), EPSILON_COMPARISON - ); - } - - [NUnit.Framework.Test] - public virtual void DistanceSquareByCoordinatesTest() { - Point first = new Point(1, 1); - Point second = new Point(1.1, 1.1); - double expected = 0.02; - NUnit.Framework.Assert.AreEqual(expected, first.DistanceSq(second.x, second.y), EPSILON_COMPARISON); - } - - [NUnit.Framework.Test] - public virtual void DistanceSquareByPointTest() { - Point first = new Point(1, 1); - Point second = new Point(1.1, 1.1); - double expected = 0.02; - NUnit.Framework.Assert.AreEqual(expected, first.DistanceSq(second), EPSILON_COMPARISON); - } - - [NUnit.Framework.Test] - public virtual void DistanceItselfSquareTest() { - Point first = new Point(1, 1); - NUnit.Framework.Assert.AreEqual(0, first.DistanceSq(first), EPSILON_COMPARISON); - } - - [NUnit.Framework.Test] - public virtual void DistanceBetweenCoordinatesTest() { - Point first = new Point(1, 1); - Point second = new Point(1.1, 1.1); - double expected = Math.Sqrt(0.02); - NUnit.Framework.Assert.AreEqual(expected, Point.Distance(first.x, first.y, second.x, second.y), EPSILON_COMPARISON - ); - } - [NUnit.Framework.Test] public virtual void DistanceByCoordinatesTest() { Point first = new Point(1, 1); Point second = new Point(1.1, 1.1); double expected = Math.Sqrt(0.02); - NUnit.Framework.Assert.AreEqual(expected, first.Distance(second.x, second.y), EPSILON_COMPARISON); + NUnit.Framework.Assert.AreEqual(expected, first.Distance(second.GetX(), second.GetY()), EPSILON_COMPARISON + ); } [NUnit.Framework.Test] @@ -164,19 +118,19 @@ public virtual void CloneTest() { } [NUnit.Framework.Test] - public virtual void TranslateTest() { + public virtual void MoveTest() { float w = 3.73f; float h = 5.23f; Rectangle rectangle = new Rectangle(0, 0, w, h); Point[] expectedPoints = rectangle.ToPointsArray(); Point point = new Point(0, 0); - point.Translate(w, 0); + point.Move(w, 0); NUnit.Framework.Assert.AreEqual(expectedPoints[1], point); - point.Translate(0, h); + point.Move(0, h); NUnit.Framework.Assert.AreEqual(expectedPoints[2], point); - point.Translate(-w, 0); + point.Move(-w, 0); NUnit.Framework.Assert.AreEqual(expectedPoints[3], point); - point.Translate(0, -h); + point.Move(0, -h); NUnit.Framework.Assert.AreEqual(expectedPoints[0], point); } @@ -187,39 +141,12 @@ public virtual void PointVsItLocationTest() { NUnit.Framework.Assert.IsTrue(first != location && first.Equals(location)); } - [NUnit.Framework.Test] - public virtual void SetLocationByPointTest() { - Point first = new Point(1.23, 1.1); - Point second = new Point(3.59, 0.87); - NUnit.Framework.Assert.AreNotEqual(first, second); - first.SetLocation(second); - NUnit.Framework.Assert.AreEqual(first, second); - } - [NUnit.Framework.Test] public virtual void SetLocationByDoubleParamTest() { Point first = new Point(1.23, 1.1); Point second = new Point(3.59, 0.87); NUnit.Framework.Assert.AreNotEqual(first, second); - first.SetLocation(second.x, second.y); - NUnit.Framework.Assert.AreEqual(first, second); - } - - [NUnit.Framework.Test] - public virtual void SetLocationByIntParamTest() { - Point first = new Point(1.23, 1.1); - Point second = new Point(3.59, 0.87); - NUnit.Framework.Assert.AreNotEqual(first, second); - first.SetLocation((int)second.x, (int)second.y); - NUnit.Framework.Assert.AreEqual(first, new Point(3, 0)); - } - - [NUnit.Framework.Test] - public virtual void MovePointTest() { - Point first = new Point(1.23, 1.1); - Point second = new Point(3.59, 0.87); - NUnit.Framework.Assert.AreNotEqual(first, second); - first.Move(second.x, second.y); + first.SetLocation(second.GetX(), second.GetY()); NUnit.Framework.Assert.AreEqual(first, second); } } diff --git a/itext.tests/itext.kernel.tests/itext/kernel/mac/MacIntegrityProtectorCreationTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/mac/MacIntegrityProtectorCreationTest.cs new file mode 100644 index 0000000000..cc5f8e8de7 --- /dev/null +++ b/itext.tests/itext.kernel.tests/itext/kernel/mac/MacIntegrityProtectorCreationTest.cs @@ -0,0 +1,347 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using System.IO; +using NUnit.Framework; +using iText.Bouncycastleconnector; +using iText.Commons.Bouncycastle.Cert; +using iText.Commons.Bouncycastle.Crypto; +using iText.Commons.Utils; +using iText.IO.Util; +using iText.Kernel.Crypto; +using iText.Kernel.Exceptions; +using iText.Kernel.Geom; +using iText.Kernel.Logs; +using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Annot; +using iText.Kernel.Utils; +using iText.Test; +using iText.Test.Attributes; + +namespace iText.Kernel.Mac { + [NUnit.Framework.Category("BouncyCastleIntegrationTest")] + public class MacIntegrityProtectorCreationTest : ExtendedITextTest { + private static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + .CurrentContext.TestDirectory) + "/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/"; + + private static readonly String DESTINATION_FOLDER = NUnit.Framework.TestContext.CurrentContext.TestDirectory + + "/test/itext/kernel/mac/MacIntegrityProtectorCreationTest/"; + + private static readonly String CERTS_SRC = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + .CurrentContext.TestDirectory) + "/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/certs/"; + + private static readonly byte[] PASSWORD = "123".GetBytes(); + + private static readonly String PROVIDER_NAME = BouncyCastleFactoryCreator.GetFactory().GetProviderName(); + + [NUnit.Framework.OneTimeSetUp] + public static void BeforeClass() { + CreateOrClearDestinationFolder(DESTINATION_FOLDER); + } + + [NUnit.Framework.OneTimeTearDown] + public static void AfterClass() { + CompareTool.Cleanup(DESTINATION_FOLDER); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void StandaloneMacStandardEncryptionTest() { + String fileName = "standaloneMacStandardEncryptionTest.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + String cmpFileName = SOURCE_FOLDER + "cmp_" + fileName; + WriterProperties writerProperties = new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0).SetStandardEncryption + (PASSWORD, PASSWORD, 0, EncryptionConstants.ENCRYPTION_AES_256, new MacProperties(MacProperties.MacDigestAlgorithm + .SHA_256)); + using (PdfDocument pdfDoc = new PdfDocument(CompareTool.CreateTestPdfWriter(outputFileName, writerProperties + ))) { + pdfDoc.AddNewPage().AddAnnotation(new PdfTextAnnotation(new Rectangle(100, 100, 100, 100))); + } + NUnit.Framework.Assert.IsNull(new CompareTool().EnableEncryptionCompare(false).CompareByContent(outputFileName + , cmpFileName, DESTINATION_FOLDER, "diff", PASSWORD, PASSWORD)); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void NoMacProtectionTest() { + String fileName = "noMacProtectionTest.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + String cmpFileName = SOURCE_FOLDER + "cmp_" + fileName; + WriterProperties writerProperties = new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0).SetStandardEncryption + (PASSWORD, PASSWORD, 0, EncryptionConstants.ENCRYPTION_AES_256, null); + using (PdfDocument pdfDoc = new PdfDocument(CompareTool.CreateTestPdfWriter(outputFileName, writerProperties + ))) { + pdfDoc.AddNewPage().AddAnnotation(new PdfTextAnnotation(new Rectangle(100, 100, 100, 100))); + } + NUnit.Framework.Assert.IsNull(new CompareTool().EnableEncryptionCompare().CompareByContent(outputFileName, + cmpFileName, DESTINATION_FOLDER, "diff", PASSWORD, PASSWORD)); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void MacEncryptionWithAesGcmTest() { + String fileName = "macEncryptionWithAesGsmTest.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + String cmpFileName = SOURCE_FOLDER + "cmp_" + fileName; + WriterProperties writerProperties = new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0).SetStandardEncryption + (PASSWORD, PASSWORD, 0, EncryptionConstants.ENCRYPTION_AES_GCM, new MacProperties(MacProperties.MacDigestAlgorithm + .SHA_256)); + using (PdfDocument pdfDoc = new PdfDocument(CompareTool.CreateTestPdfWriter(outputFileName, writerProperties + ))) { + pdfDoc.AddNewPage().AddAnnotation(new PdfTextAnnotation(new Rectangle(100, 100, 100, 100))); + } + NUnit.Framework.Assert.IsNull(new CompareTool().EnableEncryptionCompare(false).CompareByContent(outputFileName + , cmpFileName, DESTINATION_FOLDER, "diff", PASSWORD, PASSWORD)); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.PDF_WRITER_CLOSING_FAILED)] + public virtual void StandaloneMacUnwritableStreamTest() { + WriterProperties writerProperties = new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0).SetStandardEncryption + (PASSWORD, PASSWORD, 0, EncryptionConstants.ENCRYPTION_AES_256, new MacProperties(MacProperties.MacDigestAlgorithm + .SHA_256)); + MemoryStream unwritableStream = new _MemoryStream_152(); + using (PdfDocument pdfDoc = new PdfDocument(new PdfWriter(unwritableStream, writerProperties))) { + pdfDoc.AddNewPage().AddAnnotation(new PdfTextAnnotation(new Rectangle(100, 100, 100, 100))); + } + unwritableStream.Dispose(); + } + + private sealed class _MemoryStream_152 : MemoryStream { + public _MemoryStream_152() { + } + + public override void Write(byte[] b, int off, int len) { + throw new Exception("expected"); + } + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void StandaloneMacWithAllHashAlgorithmsTest() { + for (int i = 0; i < EnumUtil.GetAllValuesOfEnum().Count; i++) { + String fileName = "standaloneMacWithAllHashAlgorithmsTest" + (i + 1) + ".pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + String cmpFileName = SOURCE_FOLDER + "cmp_" + fileName; + MacProperties macProperties = new MacProperties(EnumUtil.GetAllValuesOfEnum()[i], MacProperties.MacAlgorithm.HMAC_WITH_SHA_256, MacProperties.KeyWrappingAlgorithm.AES_256_NO_PADD + ); + WriterProperties writerProperties = new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0).SetStandardEncryption + (PASSWORD, PASSWORD, 0, EncryptionConstants.ENCRYPTION_AES_256, macProperties); + using (PdfDocument pdfDoc = new PdfDocument(CompareTool.CreateTestPdfWriter(outputFileName, writerProperties + ))) { + pdfDoc.AddNewPage().AddAnnotation(new PdfTextAnnotation(new Rectangle(100, 100, 100, 100))); + } + NUnit.Framework.Assert.IsNull(new CompareTool().EnableEncryptionCompare(false).CompareByContent(outputFileName + , cmpFileName, DESTINATION_FOLDER, "diff", PASSWORD, PASSWORD)); + } + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void StandaloneMacPdfVersionNotSetTest() { + String fileName = "standaloneMacPdfVersionNotSetTest.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + MacProperties macProperties = new MacProperties(MacProperties.MacDigestAlgorithm.SHA_256, MacProperties.MacAlgorithm + .HMAC_WITH_SHA_256, MacProperties.KeyWrappingAlgorithm.AES_256_NO_PADD); + WriterProperties writerProperties = new WriterProperties().SetStandardEncryption(PASSWORD, PASSWORD, 0, EncryptionConstants + .ENCRYPTION_AES_256, macProperties); + String exceptionMessage = NUnit.Framework.Assert.Catch(typeof(PdfException), () => { + using (PdfDocument pdfDoc = new PdfDocument(CompareTool.CreateTestPdfWriter(outputFileName, writerProperties + ))) { + pdfDoc.AddNewPage().AddAnnotation(new PdfTextAnnotation(new Rectangle(100, 100, 100, 100))); + } + } + ).Message; + NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.MAC_FOR_PDF_2, exceptionMessage); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void AddMacOnPreserveEncryptionTest() { + String fileName = "addMacOnPreserveEncryptionTest.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + String cmpFileName = SOURCE_FOLDER + "cmp_" + fileName; + using (PdfDocument pdfDoc = new PdfDocument(new PdfReader(SOURCE_FOLDER + "noMacProtectionDocument.pdf", new + ReaderProperties().SetPassword(PASSWORD)), CompareTool.CreateTestPdfWriter(outputFileName, new WriterProperties + ().SetPdfVersion(PdfVersion.PDF_2_0)), new StampingProperties().PreserveEncryption())) { + pdfDoc.AddNewPage().AddAnnotation(new PdfTextAnnotation(new Rectangle(100, 100, 100, 100))); + } + NUnit.Framework.Assert.IsNull(new CompareTool().EnableEncryptionCompare(false).CompareByContent(outputFileName + , cmpFileName, DESTINATION_FOLDER, "diff", PASSWORD, PASSWORD)); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void AddMacOnAppendModeTest() { + // MAC should not be added in append mode + String fileName = "addMacOnAppendModeTest.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + String cmpFileName = SOURCE_FOLDER + "cmp_" + fileName; + using (PdfDocument pdfDoc = new PdfDocument(new PdfReader(SOURCE_FOLDER + "noMacProtectionDocument.pdf", new + ReaderProperties().SetPassword(PASSWORD)), CompareTool.CreateTestPdfWriter(outputFileName, new WriterProperties + ().SetPdfVersion(PdfVersion.PDF_2_0)), new StampingProperties().UseAppendMode())) { + pdfDoc.AddNewPage().AddAnnotation(new PdfTextAnnotation(new Rectangle(100, 100, 100, 100))); + } + NUnit.Framework.Assert.IsNull(new CompareTool().EnableEncryptionCompare().CompareByContent(outputFileName, + cmpFileName, DESTINATION_FOLDER, "diff", PASSWORD, PASSWORD)); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void AddMacWithDisableMacPropertyTest() { + // MAC should not be added in disable MAC mode even if it was provided with writer properties + String fileName = "addMacWithDisableMacPropertyTest.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + String cmpFileName = SOURCE_FOLDER + "cmp_" + fileName; + MacProperties macProperties = new MacProperties(MacProperties.MacDigestAlgorithm.SHA_384); + WriterProperties writerProperties = new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0).SetStandardEncryption + (PASSWORD, PASSWORD, 0, EncryptionConstants.ENCRYPTION_AES_256, macProperties); + using (PdfDocument pdfDoc = new PdfDocument(new PdfReader(SOURCE_FOLDER + "noMacProtectionDocument.pdf", new + ReaderProperties().SetPassword(PASSWORD)), new PdfWriter(outputFileName, writerProperties), new StampingProperties + ().DisableMac())) { + pdfDoc.AddNewPage().AddAnnotation(new PdfTextAnnotation(new Rectangle(100, 100, 100, 100))); + } + NUnit.Framework.Assert.IsNull(new CompareTool().EnableEncryptionCompare().CompareByContent(outputFileName, + cmpFileName, DESTINATION_FOLDER, "diff", PASSWORD, PASSWORD)); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void AddMacOnPreserveEncryptionWhileDowngradingTest() { + String fileName = "addMacOnPreserveEncryptionWhileDowngradingTest.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + String cmpFileName = SOURCE_FOLDER + "cmp_" + fileName; + using (PdfDocument pdfDoc = new PdfDocument(new PdfReader(SOURCE_FOLDER + "noMacProtectionDocument.pdf", new + ReaderProperties().SetPassword(PASSWORD)), CompareTool.CreateTestPdfWriter(outputFileName, new WriterProperties + ().SetPdfVersion(PdfVersion.PDF_1_7)), new StampingProperties().PreserveEncryption())) { + pdfDoc.AddNewPage().AddAnnotation(new PdfTextAnnotation(new Rectangle(100, 100, 100, 100))); + } + NUnit.Framework.Assert.IsNull(new CompareTool().EnableEncryptionCompare().CompareByContent(outputFileName, + cmpFileName, DESTINATION_FOLDER, "diff", PASSWORD, PASSWORD)); + } + + [NUnit.Framework.Test] + [LogMessage(VersionConforming.DEPRECATED_AES256_REVISION)] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void AddMacOnPreserveEncryptionFor17DocTest() { + // We can't embed MAC into encrypted documents during the conversion from earlier PDF version + // because their encryption does not support this. So WriterProperties should be used iso preserveEncryption + String fileName = "addMacOnPreserveEncryptionFor17DocTest.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + String cmpFileName = SOURCE_FOLDER + "cmp_" + fileName; + using (PdfDocument pdfDoc = new PdfDocument(new PdfReader(SOURCE_FOLDER + "noMacProtectionDocument_1_7.pdf" + , new ReaderProperties().SetPassword(PASSWORD)), CompareTool.CreateTestPdfWriter(outputFileName, new WriterProperties + ().SetPdfVersion(PdfVersion.PDF_2_0)), new StampingProperties().PreserveEncryption())) { + pdfDoc.AddNewPage().AddAnnotation(new PdfTextAnnotation(new Rectangle(100, 100, 100, 100))); + } + NUnit.Framework.Assert.IsNull(new CompareTool().EnableEncryptionCompare().CompareByContent(outputFileName, + cmpFileName, DESTINATION_FOLDER, "diff", PASSWORD, PASSWORD)); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void StandaloneMacOldEncryptionAlgorithmTest() { + String fileName = "standaloneMacOldEncryptionAlgorithmTest.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + MacProperties macProperties = new MacProperties(MacProperties.MacDigestAlgorithm.SHA_256, MacProperties.MacAlgorithm + .HMAC_WITH_SHA_256, MacProperties.KeyWrappingAlgorithm.AES_256_NO_PADD); + WriterProperties writerProperties = new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0).SetStandardEncryption + (PASSWORD, PASSWORD, 0, EncryptionConstants.ENCRYPTION_AES_128, macProperties); + String exceptionMessage = NUnit.Framework.Assert.Catch(typeof(PdfException), () => { + using (PdfDocument pdfDoc = new PdfDocument(CompareTool.CreateTestPdfWriter(outputFileName, writerProperties + ))) { + pdfDoc.AddNewPage().AddAnnotation(new PdfTextAnnotation(new Rectangle(100, 100, 100, 100))); + } + } + ).Message; + NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.MAC_FOR_ENCRYPTION_5, exceptionMessage); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void StandaloneMacPublicKeyEncryptionTest() { + try { + BouncyCastleFactoryCreator.GetFactory().IsEncryptionFeatureSupported(0, true); + } + catch (Exception) { + NUnit.Framework.Assume.That(false); + } + NUnit.Framework.Assume.That(!BouncyCastleFactoryCreator.GetFactory().IsInApprovedOnlyMode()); + String fileName = "standaloneMacPublicKeyEncryptionTest.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + String cmpFileName = SOURCE_FOLDER + "cmp_" + fileName; + IX509Certificate certificate = CryptoUtil.ReadPublicCertificate(FileUtil.GetInputStreamForFile(CERTS_SRC + + "SHA256withRSA.cer")); + WriterProperties writerProperties = new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0).SetPublicKeyEncryption + (new IX509Certificate[] { certificate }, new int[] { -1 }, EncryptionConstants.ENCRYPTION_AES_256, new + MacProperties(MacProperties.MacDigestAlgorithm.SHA_256)); + using (PdfDocument pdfDoc = new PdfDocument(CompareTool.CreateTestPdfWriter(outputFileName, writerProperties + ))) { + pdfDoc.AddNewPage().AddAnnotation(new PdfTextAnnotation(new Rectangle(100, 100, 100, 100))); + } + IPrivateKey privateKey = GetPrivateKey(CERTS_SRC + "SHA256withRSA.key"); + CompareTool compareTool = new CompareTool(); + compareTool.GetCmpReaderProperties().SetPublicKeySecurityParams(certificate, privateKey); + compareTool.GetOutReaderProperties().SetPublicKeySecurityParams(certificate, privateKey); + NUnit.Framework.Assert.IsNull(compareTool.CompareByContent(outputFileName, cmpFileName, DESTINATION_FOLDER + , "diff")); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void AddMacOnPreservePublicKeyEncryptionTest() { + // TODO DEVSIX-8635 - Verify MAC permission and embed MAC in stamping mode for public key encryption + try { + BouncyCastleFactoryCreator.GetFactory().IsEncryptionFeatureSupported(0, true); + } + catch (Exception) { + NUnit.Framework.Assume.That(false); + } + String fileName = "addMacOnPreservePublicKeyEncryptionTest.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + String cmpFileName = SOURCE_FOLDER + "cmp_" + fileName; + IX509Certificate certificate = CryptoUtil.ReadPublicCertificate(FileUtil.GetInputStreamForFile(CERTS_SRC + + "SHA256withRSA.cer")); + IPrivateKey privateKey = GetPrivateKey(CERTS_SRC + "SHA256withRSA.key"); + ReaderProperties readerProperties = new ReaderProperties(); + readerProperties.SetPublicKeySecurityParams(certificate, privateKey); + using (PdfDocument pdfDoc = new PdfDocument(new PdfReader(SOURCE_FOLDER + "noMacProtectionPublicKeyEncryptionDocument.pdf" + , readerProperties), CompareTool.CreateTestPdfWriter(outputFileName), new StampingProperties().PreserveEncryption + ())) { + pdfDoc.AddNewPage().AddAnnotation(new PdfTextAnnotation(new Rectangle(100, 100, 100, 100))); + } + CompareTool compareTool = new CompareTool(); + compareTool.GetCmpReaderProperties().SetPublicKeySecurityParams(certificate, privateKey); + compareTool.GetOutReaderProperties().SetPublicKeySecurityParams(certificate, privateKey); + NUnit.Framework.Assert.IsNull(compareTool.CompareByContent(outputFileName, cmpFileName, DESTINATION_FOLDER + , "diff")); + } + + public static IPrivateKey GetPrivateKey(String keyName) { + return PemFileHelper.ReadPrivateKeyFromPemFile(FileUtil.GetInputStreamForFile(keyName), "testpassphrase".ToCharArray + ()); + } + } +} diff --git a/itext.tests/itext.kernel.tests/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest.cs new file mode 100644 index 0000000000..776a118178 --- /dev/null +++ b/itext.tests/itext.kernel.tests/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest.cs @@ -0,0 +1,367 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using NUnit.Framework; +using iText.Bouncycastleconnector; +using iText.Commons.Bouncycastle.Cert; +using iText.Commons.Bouncycastle.Crypto; +using iText.Commons.Utils; +using iText.Kernel.Crypto; +using iText.Kernel.Exceptions; +using iText.Kernel.Geom; +using iText.Kernel.Logs; +using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Annot; +using iText.Kernel.Utils; +using iText.Test; +using iText.Test.Attributes; + +namespace iText.Kernel.Mac { + [NUnit.Framework.Category("BouncyCastleIntegrationTest")] + public class MacIntegrityProtectorReadingAndRewritingTest : ExtendedITextTest { + private static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + .CurrentContext.TestDirectory) + "/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/"; + + private static readonly String DESTINATION_FOLDER = NUnit.Framework.TestContext.CurrentContext.TestDirectory + + "/test/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/"; + + private static readonly String CERTS_SRC = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + .CurrentContext.TestDirectory) + "/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/certs/"; + + private static readonly byte[] PASSWORD = "123".GetBytes(); + + private static readonly String PROVIDER_NAME = BouncyCastleFactoryCreator.GetFactory().GetProviderName(); + + [NUnit.Framework.OneTimeSetUp] + public static void BeforeClass() { + CreateOrClearDestinationFolder(DESTINATION_FOLDER); + } + + [NUnit.Framework.OneTimeTearDown] + public static void AfterClass() { + CompareTool.Cleanup(DESTINATION_FOLDER); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void AppendModeTest() { + String fileName = "appendModeTest.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + String cmpFileName = SOURCE_FOLDER + "cmp_" + fileName; + using (PdfDocument pdfDoc = new PdfDocument(new PdfReader(SOURCE_FOLDER + "macProtectedDocument.pdf", new + ReaderProperties().SetPassword(PASSWORD)), CompareTool.CreateTestPdfWriter(outputFileName), new StampingProperties + ().UseAppendMode())) { + pdfDoc.AddNewPage().AddAnnotation(new PdfTextAnnotation(new Rectangle(100, 100, 100, 100))); + } + NUnit.Framework.Assert.IsNull(new CompareTool().EnableEncryptionCompare().CompareByContent(outputFileName, + cmpFileName, DESTINATION_FOLDER, "diff", PASSWORD, PASSWORD)); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void PreserveEncryptionTest() { + String fileName = "preserveEncryptionTest.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + String cmpFileName = SOURCE_FOLDER + "cmp_" + fileName; + using (PdfDocument pdfDoc = new PdfDocument(new PdfReader(SOURCE_FOLDER + "macProtectedDocument.pdf", new + ReaderProperties().SetPassword(PASSWORD)), CompareTool.CreateTestPdfWriter(outputFileName), new StampingProperties + ().PreserveEncryption())) { + pdfDoc.AddNewPage().AddAnnotation(new PdfTextAnnotation(new Rectangle(100, 100, 100, 100))); + } + NUnit.Framework.Assert.IsNull(new CompareTool().EnableEncryptionCompare().CompareByContent(outputFileName, + cmpFileName, DESTINATION_FOLDER, "diff", PASSWORD, PASSWORD)); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void DisableMacTest() { + String fileName = "disableMacTest.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + String cmpFileName = SOURCE_FOLDER + "cmp_" + fileName; + using (PdfDocument pdfDoc = new PdfDocument(new PdfReader(SOURCE_FOLDER + "macProtectedDocument.pdf", new + ReaderProperties().SetPassword(PASSWORD)), CompareTool.CreateTestPdfWriter(outputFileName), new StampingProperties + ().PreserveEncryption().DisableMac())) { + pdfDoc.AddNewPage().AddAnnotation(new PdfTextAnnotation(new Rectangle(100, 100, 100, 100))); + } + NUnit.Framework.Assert.IsNull(new CompareTool().EnableEncryptionCompare().CompareByContent(outputFileName, + cmpFileName, DESTINATION_FOLDER, "diff", PASSWORD, PASSWORD)); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void DisableMacInAppendModeTest() { + // We do not disable MAC in append mode if it was there + String fileName = "disableMacInAppendModeTest.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + String cmpFileName = SOURCE_FOLDER + "cmp_" + fileName; + using (PdfDocument pdfDoc = new PdfDocument(new PdfReader(SOURCE_FOLDER + "macProtectedDocument.pdf", new + ReaderProperties().SetPassword(PASSWORD)), CompareTool.CreateTestPdfWriter(outputFileName), new StampingProperties + ().UseAppendMode().DisableMac())) { + pdfDoc.AddNewPage().AddAnnotation(new PdfTextAnnotation(new Rectangle(100, 100, 100, 100))); + } + NUnit.Framework.Assert.IsNull(new CompareTool().EnableEncryptionCompare().CompareByContent(outputFileName, + cmpFileName, DESTINATION_FOLDER, "diff", PASSWORD, PASSWORD)); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void WriterPropertiesTest() { + String fileName = "writerPropertiesTest.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + String cmpFileName = SOURCE_FOLDER + "cmp_" + fileName; + MacProperties macProperties = new MacProperties(MacProperties.MacDigestAlgorithm.SHA_512); + WriterProperties writerProperties = new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0).SetStandardEncryption + (PASSWORD, PASSWORD, 0, EncryptionConstants.ENCRYPTION_AES_256, macProperties); + using (PdfDocument pdfDoc = new PdfDocument(new PdfReader(SOURCE_FOLDER + "macProtectedDocument.pdf", new + ReaderProperties().SetPassword(PASSWORD)), CompareTool.CreateTestPdfWriter(outputFileName, writerProperties + ))) { + pdfDoc.AddNewPage().AddAnnotation(new PdfTextAnnotation(new Rectangle(100, 100, 100, 100))); + } + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outputFileName, cmpFileName, DESTINATION_FOLDER + , "diff", PASSWORD, PASSWORD)); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void MacShouldNotBePreservedWithEncryptionTest() { + String fileName = "macShouldNotBePreservedWithEncryptionTest.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + String cmpFileName = SOURCE_FOLDER + "cmp_" + fileName; + WriterProperties writerProperties = new WriterProperties().SetPdfVersion(PdfVersion.PDF_1_7).SetStandardEncryption + (PASSWORD, PASSWORD, 0, EncryptionConstants.ENCRYPTION_AES_128); + using (PdfDocument pdfDoc = new PdfDocument(new PdfReader(SOURCE_FOLDER + "macProtectedDocument.pdf", new + ReaderProperties().SetPassword(PASSWORD)), CompareTool.CreateTestPdfWriter(outputFileName, writerProperties + ))) { + pdfDoc.AddNewPage().AddAnnotation(new PdfTextAnnotation(new Rectangle(100, 100, 100, 100))); + } + NUnit.Framework.Assert.IsNull(new CompareTool().EnableEncryptionCompare().CompareByContent(outputFileName, + cmpFileName, DESTINATION_FOLDER, "diff", PASSWORD, PASSWORD)); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void MacShouldNotBePreservedTest() { + String fileName = "macShouldNotBePreservedTest.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + String cmpFileName = SOURCE_FOLDER + "cmp_" + fileName; + using (PdfDocument pdfDoc = new PdfDocument(new PdfReader(SOURCE_FOLDER + "macProtectedDocument.pdf", new + ReaderProperties().SetPassword(PASSWORD)), CompareTool.CreateTestPdfWriter(outputFileName))) { + pdfDoc.AddNewPage().AddAnnotation(new PdfTextAnnotation(new Rectangle(100, 100, 100, 100))); + } + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outputFileName, cmpFileName, DESTINATION_FOLDER + , "diff", PASSWORD, PASSWORD)); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void InvalidMacTokenTest() { + String fileName = "invalidMacTokenTest.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + String exceptionMessage = NUnit.Framework.Assert.Catch(typeof(PdfException), () => { + using (PdfDocument pdfDoc = new PdfDocument(new PdfReader(SOURCE_FOLDER + "invalidMacProtectedDocument.pdf" + , new ReaderProperties().SetPassword(PASSWORD)), CompareTool.CreateTestPdfWriter(outputFileName))) { + pdfDoc.AddNewPage().AddAnnotation(new PdfTextAnnotation(new Rectangle(100, 100, 100, 100))); + } + } + ).Message; + NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.MAC_VALIDATION_FAILED, exceptionMessage); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void InvalidPublicKeyMacProtectedDocumentTest() { + try { + BouncyCastleFactoryCreator.GetFactory().IsEncryptionFeatureSupported(0, true); + } + catch (Exception) { + NUnit.Framework.Assume.That(false); + } + String fileName = "invalidPublicKeyMacProtectedDocumentTest.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + IX509Certificate certificate = CryptoUtil.ReadPublicCertificate(FileUtil.GetInputStreamForFile(CERTS_SRC + + "SHA256withRSA.cer")); + IPrivateKey privateKey = MacIntegrityProtectorCreationTest.GetPrivateKey(CERTS_SRC + "SHA256withRSA.key"); + String exceptionMessage = NUnit.Framework.Assert.Catch(typeof(PdfException), () => { + using (PdfDocument pdfDoc = new PdfDocument(new PdfReader(SOURCE_FOLDER + "invalidPublicKeyMacProtectedDocument.pdf" + , new ReaderProperties().SetPublicKeySecurityParams(certificate, privateKey)), CompareTool.CreateTestPdfWriter + (outputFileName))) { + pdfDoc.AddNewPage().AddAnnotation(new PdfTextAnnotation(new Rectangle(100, 100, 100, 100))); + } + } + ).Message; + NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.MAC_VALIDATION_FAILED, exceptionMessage); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void ReadSignedMacProtectedDocumentWithoutAttributeTest() { + String message = NUnit.Framework.Assert.Catch(typeof(PdfException), () => { + using (PdfDocument ignored = new PdfDocument(new PdfReader(SOURCE_FOLDER + "signedMacProtectedDocWithoutAttribute.pdf" + , new ReaderProperties().SetPassword(PASSWORD)))) { + } + } + ).Message; + NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.MAC_ATTRIBUTE_NOT_SPECIFIED, message); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void MacProtectionStrippedTest() { + String message = NUnit.Framework.Assert.Catch(typeof(PdfException), () => { + using (PdfDocument ignored = new PdfDocument(new PdfReader(SOURCE_FOLDER + "macProtectionStrippedTest.pdf" + , new ReaderProperties().SetPassword(PASSWORD)))) { + } + } + ).Message; + NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.MAC_PERMS_WITHOUT_MAC, message); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void ReadSignedMacProtectedDocumentTest() { + NUnit.Framework.Assert.DoesNotThrow(() => { + using (PdfDocument ignored = new PdfDocument(new PdfReader(SOURCE_FOLDER + "signedMacProtectedDocument.pdf" + , new ReaderProperties().SetPassword(PASSWORD)))) { + } + } + ); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void ReadThirdPartyMacProtectedDocumentTest() { + NUnit.Framework.Assert.DoesNotThrow(() => { + using (PdfDocument ignored = new PdfDocument(new PdfReader(SOURCE_FOLDER + "thirdPartyMacProtectedDocument.pdf" + , new ReaderProperties().SetPassword(PASSWORD)))) { + } + } + ); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void ReadThirdPartyPublicKeyMacProtectedDocumentTest() { + try { + BouncyCastleFactoryCreator.GetFactory().IsEncryptionFeatureSupported(0, true); + } + catch (Exception) { + NUnit.Framework.Assume.That(false); + } + IPrivateKey privateKey = MacIntegrityProtectorCreationTest.GetPrivateKey(CERTS_SRC + "keyForEncryption.pem" + ); + IX509Certificate certificate = CryptoUtil.ReadPublicCertificate(FileUtil.GetInputStreamForFile(CERTS_SRC + + "certForEncryption.crt")); + NUnit.Framework.Assert.DoesNotThrow(() => { + using (PdfDocument ignored = new PdfDocument(new PdfReader(SOURCE_FOLDER + "thirdPartyPublicKeyMacProtectedDocument.pdf" + , new ReaderProperties().SetPublicKeySecurityParams(certificate, privateKey)))) { + } + } + ); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void ReadMacProtectedPdf1_7() { + NUnit.Framework.Assert.DoesNotThrow(() => { + using (PdfDocument ignored = new PdfDocument(new PdfReader(SOURCE_FOLDER + "macProtectedDocumentPdf1_7.pdf" + , new ReaderProperties().SetPassword(PASSWORD)))) { + } + } + ); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void NoSaltTest() { + String message = NUnit.Framework.Assert.Catch(typeof(PdfException), () => { + using (PdfDocument pdfDoc = new PdfDocument(new PdfReader(SOURCE_FOLDER + "noSaltTest.pdf", new ReaderProperties + ().SetPassword(PASSWORD)))) { + } + } + ).Message; + NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.MAC_VALIDATION_NO_SALT, message); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void ReadTamperedMacProtectedDocumentTest() { + String message = NUnit.Framework.Assert.Catch(typeof(PdfException), () => { + using (PdfDocument ignored = new PdfDocument(new PdfReader(SOURCE_FOLDER + "thirdPartyMacProtectedDocumentTampered.pdf" + , new ReaderProperties().SetPassword(PASSWORD)))) { + } + } + ).Message; + NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.MAC_VALIDATION_FAILED, message); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void DoNotThrowOnValidationTest1() { + String fileName = "doNotThrowOnValidationTest1.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + String cmpFileName = SOURCE_FOLDER + "cmp_" + fileName; + StampingProperties stampingProperties = new StampingProperties(); + stampingProperties.RegisterDependency(typeof(IMacContainerLocator), new _StandaloneMacContainerLocator_360 + ()); + // do nothing + using (PdfDocument pdfDoc = new PdfDocument(new PdfReader(SOURCE_FOLDER + "macProtectionStrippedTest.pdf", + new ReaderProperties().SetPassword(PASSWORD)), CompareTool.CreateTestPdfWriter(outputFileName), stampingProperties + )) { + } + new CompareTool().CompareByContent(outputFileName, cmpFileName, DESTINATION_FOLDER, "diff"); + } + + private sealed class _StandaloneMacContainerLocator_360 : StandaloneMacContainerLocator { + public _StandaloneMacContainerLocator_360() { + } + + public override void HandleMacValidationError(MacValidationException exception) { + } + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void DoNotThrowOnValidationTest2() { + String fileName = "doNotThrowOnValidationTest2.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + String cmpFileName = SOURCE_FOLDER + "cmp_" + fileName; + StampingProperties stampingProperties = new StampingProperties(); + stampingProperties.RegisterDependency(typeof(IMacContainerLocator), new _StandaloneMacContainerLocator_384 + ()); + // do nothing + using (PdfDocument pdfDoc = new PdfDocument(new PdfReader(SOURCE_FOLDER + "thirdPartyMacProtectedDocumentTampered.pdf" + , new ReaderProperties().SetPassword(PASSWORD)), CompareTool.CreateTestPdfWriter(outputFileName), stampingProperties + )) { + } + new CompareTool().CompareByContent(outputFileName, cmpFileName, DESTINATION_FOLDER, "diff"); + } + + private sealed class _StandaloneMacContainerLocator_384 : StandaloneMacContainerLocator { + public _StandaloneMacContainerLocator_384() { + } + + public override void HandleMacValidationError(MacValidationException exception) { + } + } + } +} diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/FingerPrintTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/FingerPrintTest.cs index 87fd928b9e..d3f6e90ecf 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/FingerPrintTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/FingerPrintTest.cs @@ -53,5 +53,12 @@ public virtual void DuplicateTest() { fingerPrint.RegisterProduct(productData); NUnit.Framework.Assert.IsFalse(fingerPrint.RegisterProduct(duplicateProductData)); } + + [NUnit.Framework.Test] + public virtual void DisableFingerPrintTest() { + FingerPrint fingerPrint = new FingerPrint(); + fingerPrint.DisableFingerPrint(); + NUnit.Framework.Assert.IsFalse(fingerPrint.IsFingerPrintEnabled()); + } } } diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/FontToUnicodeTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/FontToUnicodeTest.cs index 167c2535f4..aa3c4818fe 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/FontToUnicodeTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/FontToUnicodeTest.cs @@ -53,7 +53,7 @@ public static void AfterClass() { [NUnit.Framework.Test] public virtual void SeveralUnicodesWithinOneGlyphTest() { // TODO DEVSIX-3634. In the output now we don't expect the \u2F46 unicode range. - // TODO DEVSIX-3634. SUBSTITUTE "Assert.assertEquals("\u2F46"..." to "Assert.assertEquals("\u65E0"..." after the fix + // TODO DEVSIX-3634. SUBSTITUTE "Assertions.assertEquals("\u2F46"..." to "Assertions.assertEquals("\u65E0"..." after the fix String outFileName = destinationFolder + "severalUnicodesWithinOneGlyphTest.pdf"; PdfDocument pdfDocument = new PdfDocument(CompareTool.CreateTestPdfWriter(outFileName)); PdfFont font = PdfFontFactory.CreateFont(fontsFolder + "NotoSansCJKjp-Bold.otf", PdfEncodings.IDENTITY_H); diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/MemoryLimitsAwareHandlerTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/MemoryLimitsAwareHandlerTest.cs index e760e722c3..3b7be43665 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/MemoryLimitsAwareHandlerTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/MemoryLimitsAwareHandlerTest.cs @@ -22,7 +22,9 @@ You should have received a copy of the GNU Affero General Public License */ using System; using iText.Kernel.Exceptions; +using iText.Kernel.Logs; using iText.Test; +using iText.Test.Attributes; namespace iText.Kernel.Pdf { [NUnit.Framework.Category("UnitTest")] @@ -46,15 +48,15 @@ public virtual void CustomMemoryHandler() { [NUnit.Framework.Test] public virtual void OverridenMemoryHandler() { MemoryLimitsAwareHandler defaultHandler = new MemoryLimitsAwareHandler(); - MemoryLimitsAwareHandler customHandler = new _MemoryLimitsAwareHandler_59(); + MemoryLimitsAwareHandler customHandler = new _MemoryLimitsAwareHandler_64(); PdfArray filters = new PdfArray(); filters.Add(PdfName.FlateDecode); NUnit.Framework.Assert.IsFalse(defaultHandler.IsMemoryLimitsAwarenessRequiredOnDecompression(filters)); NUnit.Framework.Assert.IsTrue(customHandler.IsMemoryLimitsAwarenessRequiredOnDecompression(filters)); } - private sealed class _MemoryLimitsAwareHandler_59 : MemoryLimitsAwareHandler { - public _MemoryLimitsAwareHandler_59() { + private sealed class _MemoryLimitsAwareHandler_64 : MemoryLimitsAwareHandler { + public _MemoryLimitsAwareHandler_64() { } public override bool IsMemoryLimitsAwarenessRequiredOnDecompression(PdfArray filters) { @@ -144,6 +146,54 @@ public virtual void CheckCapacityTest() { )); } + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MEMORYLIMITAWAREHANDLER_OVERRIDE_CREATENEWINSTANCE_METHOD)] + public virtual void CreateCopyMemoryHandlerWarningTest() { + MemoryLimitsAwareHandler customHandler = new _MemoryLimitsAwareHandler_173(); + customHandler.SetMaxNumberOfElementsInXrefStructure(1); + customHandler.SetMaxXObjectsSizePerPage(2); + customHandler.SetMaxSizeOfDecompressedPdfStreamsSum(3); + customHandler.SetMaxSizeOfSingleDecompressedPdfStream(4); + MemoryLimitsAwareHandler copy = customHandler.CreateNewInstance(); + NUnit.Framework.Assert.AreEqual(1, copy.GetMaxNumberOfElementsInXrefStructure()); + NUnit.Framework.Assert.AreEqual(2, copy.GetMaxXObjectsSizePerPage()); + NUnit.Framework.Assert.AreEqual(3, copy.GetMaxSizeOfDecompressedPdfStreamsSum()); + NUnit.Framework.Assert.AreEqual(4, copy.GetMaxSizeOfSingleDecompressedPdfStream()); + } + + private sealed class _MemoryLimitsAwareHandler_173 : MemoryLimitsAwareHandler { + public _MemoryLimitsAwareHandler_173() { + } + } + + [NUnit.Framework.Test] + public virtual void CreateCopyMemoryHandlerNoWarningTest() { + MemoryLimitsAwareHandler customHandler = new _MemoryLimitsAwareHandler_190(); + customHandler.SetMaxNumberOfElementsInXrefStructure(1); + customHandler.SetMaxXObjectsSizePerPage(2); + customHandler.SetMaxSizeOfDecompressedPdfStreamsSum(3); + customHandler.SetMaxSizeOfSingleDecompressedPdfStream(4); + MemoryLimitsAwareHandler copy = customHandler.CreateNewInstance(); + NUnit.Framework.Assert.AreEqual(1, copy.GetMaxNumberOfElementsInXrefStructure()); + NUnit.Framework.Assert.AreEqual(2, copy.GetMaxXObjectsSizePerPage()); + NUnit.Framework.Assert.AreEqual(3, copy.GetMaxSizeOfDecompressedPdfStreamsSum()); + NUnit.Framework.Assert.AreEqual(4, copy.GetMaxSizeOfSingleDecompressedPdfStream()); + } + + private sealed class _MemoryLimitsAwareHandler_190 : MemoryLimitsAwareHandler { + public _MemoryLimitsAwareHandler_190() { + } + + public override MemoryLimitsAwareHandler CreateNewInstance() { + MemoryLimitsAwareHandler to = new MemoryLimitsAwareHandler(); + to.SetMaxSizeOfSingleDecompressedPdfStream(this.GetMaxSizeOfSingleDecompressedPdfStream()); + to.SetMaxSizeOfDecompressedPdfStreamsSum(this.GetMaxSizeOfDecompressedPdfStreamsSum()); + to.SetMaxNumberOfElementsInXrefStructure(this.GetMaxNumberOfElementsInXrefStructure()); + to.SetMaxXObjectsSizePerPage(this.GetMaxXObjectsSizePerPage()); + return to; + } + } + private static void TestSingleStream(MemoryLimitsAwareHandler handler) { String expectedExceptionMessage = KernelExceptionMessageConstant.DURING_DECOMPRESSION_SINGLE_STREAM_OCCUPIED_MORE_MEMORY_THAN_ALLOWED; int expectedFailureIndex = 10; diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PageFlushingTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PageFlushingTest.cs index eebad2a321..1f496a859c 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PageFlushingTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PageFlushingTest.cs @@ -36,6 +36,8 @@ You should have received a copy of the GNU Affero General Public License using iText.Kernel.Pdf.Navigation; using iText.Kernel.Pdf.Xobject; using iText.Kernel.Utils; +using iText.Kernel.Validation; +using iText.Kernel.Validation.Context; using iText.Test; namespace iText.Kernel.Pdf { @@ -371,6 +373,34 @@ public virtual void FlushingPageResourcesMadeIndependent() { result.Close(); } + [NUnit.Framework.Test] + public virtual void PageValidationTest() { + using (PdfDocument doc = new PdfDocument(new PdfWriter(new MemoryStream()))) { + ValidationContainer container = new ValidationContainer(); + PageFlushingTest.CustomValidationChecker checker = new PageFlushingTest.CustomValidationChecker(); + container.AddChecker(checker); + doc.GetDiContainer().Register(typeof(ValidationContainer), container); + NUnit.Framework.Assert.IsNull(checker.page); + PdfPage pdfPage = doc.AddNewPage(); + pdfPage.Flush(true); + NUnit.Framework.Assert.AreSame(pdfPage, checker.page); + } + } + + private class CustomValidationChecker : IValidationChecker { + public PdfPage page; + + public virtual void Validate(IValidationContext validationContext) { + if (validationContext.GetType() == ValidationType.PDF_PAGE) { + page = ((PdfPageValidationContext)validationContext).GetPage(); + } + } + + public virtual bool IsPdfObjectReadyToFlush(PdfObject @object) { + return true; + } + } + private static void Test(String filename, PageFlushingTest.DocMode docMode, PageFlushingTest.FlushMode flushMode , PageFlushingTest.PagesOp pagesOp, int total, int flushedExpected, int notReadExpected) { String input = sourceFolder + "100pages.pdf"; diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfAConformanceLevelTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfAConformanceLevelTest.cs deleted file mode 100644 index 6626ac329c..0000000000 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfAConformanceLevelTest.cs +++ /dev/null @@ -1,84 +0,0 @@ -/* -This file is part of the iText (R) project. -Copyright (c) 1998-2024 Apryse Group NV -Authors: Apryse Software. - -This program is offered under a commercial and under the AGPL license. -For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. - -AGPL licensing: -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . -*/ -using iText.IO.Source; -using iText.Kernel.XMP; -using iText.Kernel.XMP.Impl; -using iText.Test; - -namespace iText.Kernel.Pdf { - [NUnit.Framework.Category("UnitTest")] - public class PdfAConformanceLevelTest : ExtendedITextTest { - [NUnit.Framework.Test] - public virtual void GetConformanceTest() { - NUnit.Framework.Assert.AreEqual(PdfAConformanceLevel.PDF_A_4, PdfAConformanceLevel.GetConformanceLevel("4" - , null)); - NUnit.Framework.Assert.AreEqual(PdfAConformanceLevel.PDF_A_4E, PdfAConformanceLevel.GetConformanceLevel("4" - , "E")); - NUnit.Framework.Assert.AreEqual(PdfAConformanceLevel.PDF_A_4F, PdfAConformanceLevel.GetConformanceLevel("4" - , "F")); - } - - [NUnit.Framework.Test] - public virtual void GetXmpConformanceNullTest() { - XMPMeta meta = new XMPMetaImpl(); - meta.SetProperty(XMPConst.NS_PDFA_ID, XMPConst.PART, "4"); - PdfAConformanceLevel level = PdfAConformanceLevel.GetConformanceLevel(meta); - NUnit.Framework.Assert.AreEqual(PdfAConformanceLevel.PDF_A_4, level); - } - - [NUnit.Framework.Test] - public virtual void GetXmpConformanceBTest() { - XMPMeta meta = new XMPMetaImpl(); - meta.SetProperty(XMPConst.NS_PDFA_ID, XMPConst.PART, "2"); - meta.SetProperty(XMPConst.NS_PDFA_ID, XMPConst.CONFORMANCE, "B"); - PdfAConformanceLevel level = PdfAConformanceLevel.GetConformanceLevel(meta); - NUnit.Framework.Assert.AreEqual(PdfAConformanceLevel.PDF_A_2B, level); - } - - [NUnit.Framework.Test] - public virtual void GetPdfAConformanceLevel01Test() { - NUnit.Framework.Assert.IsNull(PdfAConformanceLevel.GetPDFAConformance(null, null)); - } - - [NUnit.Framework.Test] - public virtual void GetPdfAConformanceLevel02Test() { - NUnit.Framework.Assert.AreEqual(PdfAConformanceLevel.PDF_A_1A, PdfAConformanceLevel.GetPDFAConformance(PdfAConformanceLevel - .PDF_A_1A, null)); - } - - [NUnit.Framework.Test] - public virtual void GetPdfAConformanceLevel03Test() { - using (PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()))) { - NUnit.Framework.Assert.AreEqual(PdfAConformanceLevel.PDF_A_1A, PdfAConformanceLevel.GetPDFAConformance(PdfAConformanceLevel - .PDF_A_1A, pdfDocument)); - } - } - - [NUnit.Framework.Test] - public virtual void GetPdfAConformanceLevel04Test() { - using (PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()))) { - NUnit.Framework.Assert.IsNull(PdfAConformanceLevel.GetPDFAConformance(null, pdfDocument)); - } - } - } -} diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfAConformanceTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfAConformanceTest.cs new file mode 100644 index 0000000000..648eaaa978 --- /dev/null +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfAConformanceTest.cs @@ -0,0 +1,56 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.XMP; +using iText.Kernel.XMP.Impl; +using iText.Test; + +namespace iText.Kernel.Pdf { + [NUnit.Framework.Category("UnitTest")] + public class PdfAConformanceTest : ExtendedITextTest { + [NUnit.Framework.Test] + public virtual void GetConformanceTest() { + NUnit.Framework.Assert.AreEqual(PdfAConformance.PDF_A_4, PdfConformance.GetAConformance("4", null)); + NUnit.Framework.Assert.AreEqual(PdfAConformance.PDF_A_4E, PdfConformance.GetAConformance("4", "E")); + NUnit.Framework.Assert.AreEqual(PdfAConformance.PDF_A_4F, PdfConformance.GetAConformance("4", "F")); + } + + [NUnit.Framework.Test] + public virtual void GetXmpConformanceNullTest() { + XMPMeta meta = new XMPMetaImpl(); + meta.SetProperty(XMPConst.NS_PDFA_ID, XMPConst.PART, "4"); + PdfConformance level = PdfConformance.GetConformance(meta); + NUnit.Framework.Assert.AreEqual(PdfAConformance.PDF_A_4, level.GetAConformance()); + NUnit.Framework.Assert.AreEqual(PdfConformance.PDF_A_4, level); + } + + [NUnit.Framework.Test] + public virtual void GetXmpConformanceBTest() { + XMPMeta meta = new XMPMetaImpl(); + meta.SetProperty(XMPConst.NS_PDFA_ID, XMPConst.PART, "2"); + meta.SetProperty(XMPConst.NS_PDFA_ID, XMPConst.CONFORMANCE, "B"); + PdfConformance level = PdfConformance.GetConformance(meta); + NUnit.Framework.Assert.AreEqual(PdfAConformance.PDF_A_2B, level.GetAConformance()); + NUnit.Framework.Assert.AreEqual(PdfConformance.PDF_A_2B, level); + } + } +} diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfCopyTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfCopyTest.cs index c0b7a130a4..a2b3e920ad 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfCopyTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfCopyTest.cs @@ -87,7 +87,7 @@ public virtual void Copying1() { pdfDoc1.Close(); PdfReader reader = CompareTool.CreateOutputReader(destinationFolder + "copying1_2.pdf"); PdfDocument pdfDocument = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); PdfDictionary trailer = pdfDocument.GetTrailer(); PdfDictionary info = trailer.GetAsDictionary(PdfName.Info); PdfName b = info.GetAsName(new PdfName("a")); @@ -118,7 +118,7 @@ public virtual void Copying2() { pdfDoc1.Close(); PdfReader reader = CompareTool.CreateOutputReader(destinationFolder + "copying2_2.pdf"); PdfDocument pdfDocument = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); for (int i = 0; i < 5; i++) { byte[] bytes = pdfDocument.GetPage(i + 1).GetContentBytes(); NUnit.Framework.Assert.AreEqual("%page " + (i * 2 + 1).ToString() + "\n", iText.Commons.Utils.JavaUtil.GetStringForBytes @@ -142,7 +142,7 @@ public virtual void Copying3() { pdfDoc.Close(); PdfReader reader = CompareTool.CreateOutputReader(destinationFolder + "copying3_1.pdf"); pdfDoc = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); PdfDictionary dic0 = pdfDoc.GetPage(1).GetPdfObject().GetAsDictionary(new PdfName("HelloWorld")); NUnit.Framework.Assert.AreEqual(4, dic0.GetIndirectReference().GetObjNumber()); NUnit.Framework.Assert.AreEqual(0, dic0.GetIndirectReference().GetGenNumber()); diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfDeveloperExtensionTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfDeveloperExtensionTest.cs index 56e66caf9e..a3a9b865fd 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfDeveloperExtensionTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfDeveloperExtensionTest.cs @@ -105,6 +105,28 @@ public virtual void AddMultivaluedExtensionNoOverrideTest() { .GetExtensionLevel(), MULTI_EXTENSION_2.GetExtensionLevel())); } + [NUnit.Framework.Test] + public virtual void RemoveSingleValuedExtensionTest() { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + using (PdfDocument pdfDoc = new PdfDocument(new PdfWriter(baos))) { + pdfDoc.GetCatalog().AddDeveloperExtension(SIMPLE_EXTENSION_L5); + pdfDoc.GetCatalog().RemoveDeveloperExtension(SIMPLE_EXTENSION_L5); + } + AssertNoExtensionWithPrefix(baos.ToArray(), SIMPLE_EXTENSION_L5.GetPrefix()); + } + + [NUnit.Framework.Test] + public virtual void RemoveMultivaluedExtensionTest() { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + using (PdfDocument pdfDoc = new PdfDocument(new PdfWriter(baos))) { + pdfDoc.GetCatalog().AddDeveloperExtension(MULTI_EXTENSION_1); + pdfDoc.GetCatalog().AddDeveloperExtension(MULTI_EXTENSION_2); + pdfDoc.GetCatalog().RemoveDeveloperExtension(MULTI_EXTENSION_2); + } + AssertMultiExtension(baos.ToArray(), MULTI_EXTENSION_1.GetPrefix(), JavaUtil.ArraysAsList(MULTI_EXTENSION_1 + .GetExtensionLevel())); + } + private void AssertSimpleExtension(byte[] docData, PdfName prefix, int expectedLevel) { using (PdfDocument pdfDoc = new PdfDocument(new PdfReader(new MemoryStream(docData)))) { PdfDictionary extDict = pdfDoc.GetCatalog().GetPdfObject().GetAsDictionary(PdfName.Extensions).GetAsDictionary @@ -113,6 +135,14 @@ private void AssertSimpleExtension(byte[] docData, PdfName prefix, int expectedL } } + private void AssertNoExtensionWithPrefix(byte[] docData, PdfName prefix) { + using (PdfDocument pdfDoc = new PdfDocument(new PdfReader(new MemoryStream(docData)))) { + PdfDictionary extDict = pdfDoc.GetCatalog().GetPdfObject().GetAsDictionary(PdfName.Extensions).GetAsDictionary + (prefix); + NUnit.Framework.Assert.IsNull(extDict); + } + } + private void AssertMultiExtension(byte[] docData, PdfName prefix, ICollection expectedLevels) { ICollection seen = new HashSet(); using (PdfDocument pdfDoc = new PdfDocument(new PdfReader(new MemoryStream(docData)))) { diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfDocumentIdTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfDocumentIdTest.cs index 2346243b9e..2eee3d8e4b 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfDocumentIdTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfDocumentIdTest.cs @@ -326,8 +326,8 @@ public virtual void ReadPdfWithNoIdAndConservativeReadingTest() { // PdfString originalId = new PdfString("Original ID 56789"); // PdfWriter initialWriter = CompareTool.createTestPdfWriter(baos, new WriterProperties().setInitialDocumentId(originalId)); // - // Assert.assertNotEquals(); - // Assert.assertEquals(); + // Assertions.assertNotEquals(); + // Assertions.assertEquals(); // // } } diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfDocumentTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfDocumentTest.cs index e1bae12dff..ffe06e8fef 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfDocumentTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfDocumentTest.cs @@ -501,7 +501,7 @@ public virtual void MergedSiblingWidgetsRemovePageTest() { } [NUnit.Framework.Test] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] public virtual void RootCannotBeReferenceFromTrailerTest() { String filename = SOURCE_FOLDER + "rootCannotBeReferenceFromTrailerTest.pdf"; PdfReader corruptedReader = new PdfReader(filename); @@ -526,7 +526,76 @@ public virtual void GetDiContainer() { [NUnit.Framework.Test] public virtual void GetDefaultConformanceLevelTest() { PdfDocument document = new PdfDocument(new PdfWriter(new MemoryStream())); - NUnit.Framework.Assert.IsNull(document.GetConformanceLevel()); + NUnit.Framework.Assert.IsNotNull(document.GetConformance()); + NUnit.Framework.Assert.IsFalse(document.GetConformance().IsPdfAOrUa()); + } + + //TODO DEVSIX-8490 remove this test when implemented + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.DUPLICATE_ENTRIES_IN_ORDER_ARRAY_REMOVED)] + public virtual void RemoveDuplicatesInOrderArrayTest() { + String inputPdf = "removeDuplicatesInOrderArray.pdf"; + String outputPdf = "removedDuplicateInOrderArray.pdf"; + PdfDocument doc = new PdfDocument(new PdfReader(SOURCE_FOLDER + inputPdf), CompareTool.CreateTestPdfWriter + (DESTINATION_FOLDER + outputPdf)); + //Need to update OCProperties + doc.GetCatalog().GetOCProperties(false); + doc.Close(); + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(DESTINATION_FOLDER + outputPdf, SOURCE_FOLDER + + "cmp_" + outputPdf, DESTINATION_FOLDER)); + } + + //TODO DEVSIX-8490 remove this test when implemented + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.DUPLICATE_ENTRIES_IN_ORDER_ARRAY_REMOVED)] + public virtual void RemoveNestedDuplicatesInOrderArrayTest() { + String inputPdf = "removeNestedDuplicatesInOrderArray.pdf"; + String outputPdf = "removedNestedDuplicatesInOrderArray.pdf"; + PdfDocument doc = new PdfDocument(new PdfReader(SOURCE_FOLDER + inputPdf), new PdfWriter(DESTINATION_FOLDER + + outputPdf)); + //Need to update OCProperties + doc.GetCatalog().GetOCProperties(false); + doc.Close(); + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(DESTINATION_FOLDER + outputPdf, SOURCE_FOLDER + + "cmp_" + outputPdf, DESTINATION_FOLDER)); + } + + //TODO DEVSIX-8490 remove this test when implemented + [NUnit.Framework.Test] + public virtual void RemoveDuplicatesHasChildInOrderArrayTest() { + String inputPdf = "removeDuplicatesHasChildInOrderArray.pdf"; + String outputPdf = "removedDuplicatesHasChildInOrderArray.pdf"; + PdfDocument doc = new PdfDocument(new PdfReader(SOURCE_FOLDER + inputPdf), CompareTool.CreateTestPdfWriter + (DESTINATION_FOLDER + outputPdf)); + PdfCatalog catalog = doc.GetCatalog(); + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => catalog.GetOCProperties(false)); + NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(KernelExceptionMessageConstant.UNABLE_TO_REMOVE_DUPLICATE_LAYER + , "4 0 R"), e.Message); + } + + //TODO DEVSIX-8490 remove this test when implemented + [NUnit.Framework.Test] + public virtual void RemoveNestedDuplicatesHasChildInOrderArrayTest() { + String inputPdf = "removeNestedDuplicatesHasChildInOrderArray.pdf"; + String outputPdf = "removedNestedDuplicatesHasChildInOrderArray.pdf"; + PdfDocument doc = new PdfDocument(new PdfReader(SOURCE_FOLDER + inputPdf), CompareTool.CreateTestPdfWriter + (DESTINATION_FOLDER + outputPdf)); + PdfCatalog catalog = doc.GetCatalog(); + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => catalog.GetOCProperties(false)); + NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(KernelExceptionMessageConstant.UNABLE_TO_REMOVE_DUPLICATE_LAYER + , "27 0 R"), e.Message); + } + + [NUnit.Framework.Test] + public virtual void CreatePdfDocumentWithAAndUaMetadataTest() { + String outputPdf = "pdfDocWithAAndUaMetadata.pdf"; + WriterProperties writerProperties = new WriterProperties().AddPdfAXmpMetadata(PdfAConformance.PDF_A_3A).AddPdfUaXmpMetadata + (PdfUAConformance.PDF_UA_1); + PdfDocument doc = new PdfDocument(new PdfWriter(DESTINATION_FOLDER + outputPdf, writerProperties)); + doc.AddNewPage(); + doc.Close(); + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(DESTINATION_FOLDER + outputPdf, SOURCE_FOLDER + + "cmp_" + outputPdf, DESTINATION_FOLDER)); } private class IgnoreTagStructurePdfDocument : PdfDocument { diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfDocumentUnitTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfDocumentUnitTest.cs index 1ce08f36d4..7e5b4434c2 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfDocumentUnitTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfDocumentUnitTest.cs @@ -31,7 +31,8 @@ You should have received a copy of the GNU Affero General Public License using iText.Kernel.Logs; using iText.Kernel.Pdf.Filespec; using iText.Kernel.Pdf.Layer; -using iText.Kernel.Utils; +using iText.Kernel.Validation; +using iText.Kernel.Validation.Context; using iText.Test; using iText.Test.Attributes; @@ -186,64 +187,6 @@ public virtual void CopyPagesFlushedResources() { } } - [NUnit.Framework.Test] - public virtual void PdfDocumentInstanceNoWriterInfoAndConformanceLevelInitialization() { - PdfDocument pdfDocument = new PdfDocument(new PdfReader(SOURCE_FOLDER + "pdfWithMetadata.pdf")); - NUnit.Framework.Assert.IsNull(pdfDocument.info); - NUnit.Framework.Assert.IsNull(pdfDocument.reader.pdfAConformanceLevel); - pdfDocument.Close(); - NUnit.Framework.Assert.IsNull(pdfDocument.info); - NUnit.Framework.Assert.IsNull(pdfDocument.reader.pdfAConformanceLevel); - } - - [NUnit.Framework.Test] - public virtual void PdfDocumentInstanceWriterInfoAndConformanceLevelInitialization() { - PdfDocument pdfDocument = new PdfDocument(new PdfReader(SOURCE_FOLDER + "pdfWithMetadata.pdf"), new PdfWriter - (new ByteArrayOutputStream())); - NUnit.Framework.Assert.IsNotNull(pdfDocument.info); - NUnit.Framework.Assert.IsNull(pdfDocument.reader.pdfAConformanceLevel); - pdfDocument.Close(); - NUnit.Framework.Assert.IsNotNull(pdfDocument.info); - NUnit.Framework.Assert.IsNull(pdfDocument.reader.pdfAConformanceLevel); - } - - [NUnit.Framework.Test] - public virtual void ExtendedPdfDocumentNoWriterInfoAndConformanceLevelInitialization() { - PdfDocument pdfDocument = new _PdfDocument_251(new PdfReader(SOURCE_FOLDER + "pdfWithMetadata.pdf")); - // This class instance extends pdfDocument - // TODO DEVSIX-5292 These fields shouldn't be initialized during the document's opening - NUnit.Framework.Assert.IsNotNull(pdfDocument.info); - NUnit.Framework.Assert.IsNotNull(pdfDocument.reader.pdfAConformanceLevel); - pdfDocument.Close(); - NUnit.Framework.Assert.IsNotNull(pdfDocument.info); - NUnit.Framework.Assert.IsNotNull(pdfDocument.reader.pdfAConformanceLevel); - } - - private sealed class _PdfDocument_251 : PdfDocument { - public _PdfDocument_251(PdfReader baseArg1) - : base(baseArg1) { - } - } - - [NUnit.Framework.Test] - public virtual void ExtendedPdfDocumentWriterInfoAndConformanceLevelInitialization() { - PdfDocument pdfDocument = new _PdfDocument_268(new PdfReader(SOURCE_FOLDER + "pdfWithMetadata.pdf"), new PdfWriter - (new ByteArrayOutputStream())); - // This class instance extends pdfDocument - NUnit.Framework.Assert.IsNotNull(pdfDocument.info); - // TODO DEVSIX-5292 pdfAConformanceLevel shouldn't be initialized during the document's opening - NUnit.Framework.Assert.IsNotNull(pdfDocument.reader.pdfAConformanceLevel); - pdfDocument.Close(); - NUnit.Framework.Assert.IsNotNull(pdfDocument.info); - NUnit.Framework.Assert.IsNotNull(pdfDocument.reader.pdfAConformanceLevel); - } - - private sealed class _PdfDocument_268 : PdfDocument { - public _PdfDocument_268(PdfReader baseArg1, PdfWriter baseArg2) - : base(baseArg1, baseArg2) { - } - } - [NUnit.Framework.Test] public virtual void GetDocumentInfoAlreadyClosedTest() { PdfDocument pdfDocument = new PdfDocument(new PdfReader(SOURCE_FOLDER + "pdfWithMetadata.pdf")); @@ -252,18 +195,16 @@ public virtual void GetDocumentInfoAlreadyClosedTest() { } [NUnit.Framework.Test] - public virtual void GetDocumentInfoNotInitializedTest() { + public virtual void GetDocumentInfoInitializationTest() { PdfDocument pdfDocument = new PdfDocument(new PdfReader(SOURCE_FOLDER + "pdfWithMetadata.pdf")); - NUnit.Framework.Assert.IsNull(pdfDocument.info); NUnit.Framework.Assert.IsNotNull(pdfDocument.GetDocumentInfo()); pdfDocument.Close(); } [NUnit.Framework.Test] - public virtual void GetPdfAConformanceLevelNotInitializedTest() { + public virtual void GetPdfAConformanceLevelInitializationTest() { PdfDocument pdfDocument = new PdfDocument(new PdfReader(SOURCE_FOLDER + "pdfWithMetadata.pdf")); - NUnit.Framework.Assert.IsNull(pdfDocument.reader.pdfAConformanceLevel); - NUnit.Framework.Assert.IsNotNull(pdfDocument.reader.GetPdfAConformanceLevel()); + NUnit.Framework.Assert.IsTrue(pdfDocument.reader.GetPdfConformance().IsPdfAOrUa()); pdfDocument.Close(); } @@ -410,7 +351,8 @@ public virtual void CannotSetEncryptedPayloadToEncryptedDocTest() { [NUnit.Framework.Test] public virtual void CheckEmptyIsoConformanceTest() { using (PdfDocument doc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()))) { - NUnit.Framework.Assert.DoesNotThrow(() => doc.CheckIsoConformance()); + IValidationContext validationContext = new PdfDocumentValidationContext(doc, doc.GetDocumentFonts()); + NUnit.Framework.Assert.DoesNotThrow(() => doc.CheckIsoConformance(validationContext)); } } @@ -422,7 +364,8 @@ public virtual void CheckIsoConformanceTest() { container.AddChecker(checker); doc.GetDiContainer().Register(typeof(ValidationContainer), container); NUnit.Framework.Assert.IsFalse(checker.documentValidationPerformed); - doc.CheckIsoConformance(); + IValidationContext validationContext = new PdfDocumentValidationContext(doc, doc.GetDocumentFonts()); + doc.CheckIsoConformance(validationContext); NUnit.Framework.Assert.IsTrue(checker.documentValidationPerformed); } } @@ -430,15 +373,14 @@ public virtual void CheckIsoConformanceTest() { private class CustomValidationChecker : IValidationChecker { public bool documentValidationPerformed = false; - public bool objectValidationPerformed = false; - - public virtual void ValidateDocument(ValidationContext validationContext) { - documentValidationPerformed = true; + public virtual void Validate(IValidationContext validationContext) { + if (validationContext.GetType() == ValidationType.PDF_DOCUMENT) { + documentValidationPerformed = true; + } } - public virtual void ValidateObject(Object obj, IsoKey key, PdfResources resources, PdfStream contentStream - , Object extra) { - objectValidationPerformed = true; + public virtual bool IsPdfObjectReadyToFlush(PdfObject @object) { + return true; } } } diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfEncryptionUnitTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfEncryptionUnitTest.cs index 6dd3a7a8ce..bec478a04c 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfEncryptionUnitTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfEncryptionUnitTest.cs @@ -95,7 +95,7 @@ public virtual void CreateIdNormalLength() { , 0x76, 0x30, (byte)0x83, 0x49, 0x2F, 0x07, 0x61, (byte)0xBC, (byte)0xBA, 0x04, 0x37, 0x1B, 0x0E, (byte )0x80, 0x34, 0x30, 0x4A, 0x3B, 0x0E, 0x27, 0x4F, 0x01, 0x1D, 0x36, 0x71, 0x7A, 0x42, 0x2B, 0x2C, 0x14, 0x6A, 0x52, 0x07, 0x1E, 0x4C }; - PdfObject fileId = PdfEncryption.CreateInfoId(originalId, modifiedId); + PdfObject fileId = PdfEncryption.CreateInfoId(originalId, modifiedId, false); PdfObject expectedFileId = new PdfLiteral("[<3339623865613033653239313832663139636265643233373733616" + "339653439><082704302042226a5f405657444a6e1c187671803780715c687e3541763083492f0761bcba04371b0e80343" + "04a3b0e274f011d36717a422b2c146a52071e4c>]"); NUnit.Framework.Assert.AreEqual(expectedFileId, fileId); diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfExtGStateTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfExtGStateTest.cs index 0cf635d002..29002fac10 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfExtGStateTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfExtGStateTest.cs @@ -86,5 +86,58 @@ public virtual void EgsTest1() { NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationDocument, sourceFolder + "cmp_egsTest1.pdf" , destinationFolder, "diff_")); } + + [NUnit.Framework.Test] + public virtual void BlackPointCompensationTest1() { + PdfExtGState pdfExtGState = new PdfExtGState(); + pdfExtGState.SetUseBlackPointCompensation(true); + NUnit.Framework.Assert.IsTrue(pdfExtGState.IsBlackPointCompensationUsed()); + } + + [NUnit.Framework.Test] + public virtual void BlackPointCompensationTest2() { + PdfExtGState pdfExtGState = new PdfExtGState(); + pdfExtGState.SetUseBlackPointCompensation(false); + NUnit.Framework.Assert.IsFalse(pdfExtGState.IsBlackPointCompensationUsed()); + } + + [NUnit.Framework.Test] + public virtual void BlackPointCompensationTest3() { + PdfExtGState pdfExtGState = new PdfExtGState(); + PdfObject useBlackPoint = pdfExtGState.GetPdfObject().GetAsName(PdfName.UseBlackPtComp); + NUnit.Framework.Assert.IsNull(useBlackPoint); + } + + [NUnit.Framework.Test] + public virtual void BlackPointCompensationTest4() { + PdfExtGState pdfExtGState = new PdfExtGState(); + PdfDictionary pdfExtGStateObj = pdfExtGState.GetPdfObject(); + pdfExtGStateObj.Put(PdfName.UseBlackPtComp, PdfName.ON); + NUnit.Framework.Assert.IsTrue(pdfExtGState.IsBlackPointCompensationUsed()); + } + + [NUnit.Framework.Test] + public virtual void BlackPointCompensationTest5() { + PdfExtGState pdfExtGState = new PdfExtGState(); + PdfDictionary pdfExtGStateObj = pdfExtGState.GetPdfObject(); + pdfExtGStateObj.Put(PdfName.UseBlackPtComp, PdfName.OFF); + NUnit.Framework.Assert.IsFalse(pdfExtGState.IsBlackPointCompensationUsed()); + } + + [NUnit.Framework.Test] + public virtual void BlackPointCompensationTest6() { + PdfExtGState pdfExtGState = new PdfExtGState(); + pdfExtGState.SetUseBlackPointCompensation(true); + PdfName useBlackPtComp = pdfExtGState.GetPdfObject().GetAsName(PdfName.UseBlackPtComp); + NUnit.Framework.Assert.AreEqual(PdfName.ON, useBlackPtComp, "PdfName is different from expected."); + } + + [NUnit.Framework.Test] + public virtual void BlackPointCompensationTest7() { + PdfExtGState pdfExtGState = new PdfExtGState(); + pdfExtGState.SetUseBlackPointCompensation(false); + PdfName useBlackPtComp = pdfExtGState.GetPdfObject().GetAsName(PdfName.UseBlackPtComp); + NUnit.Framework.Assert.AreEqual(PdfName.OFF, useBlackPtComp, "PdfName is different from expected."); + } } } diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfObjectTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfObjectTest.cs index 7632e22b5a..2989f2315e 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfObjectTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfObjectTest.cs @@ -154,7 +154,7 @@ public virtual void PdtIndirectReferenceLateInitializing1() { [LogMessage(iText.IO.Logs.IoLogMessageConstant.FLUSHED_OBJECT_CONTAINS_REFERENCE_WHICH_NOT_REFER_TO_ANY_OBJECT )] [LogMessage(iText.IO.Logs.IoLogMessageConstant.INDIRECT_REFERENCE_USED_IN_FLUSHED_OBJECT_MADE_FREE)] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] public virtual void PdtIndirectReferenceLateInitializing2() { MemoryStream baos = new MemoryStream(); PdfDocument document = new PdfDocument(new PdfWriter(baos)); diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfPagesTreeTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfPagesTreeTest.cs index 57753b2e27..706f96188a 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfPagesTreeTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfPagesTreeTest.cs @@ -21,7 +21,9 @@ You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ using System; +using iText.Commons.Datastructures; using iText.IO.Source; +using iText.Kernel.DI.Pagetree; using iText.Test; namespace iText.Kernel.Pdf { @@ -34,36 +36,54 @@ public virtual void GenerateTreeDocHasNoPagesTest() { } [NUnit.Framework.Test] - public virtual void NullUnlimitedListAddTest() { - PdfPagesTree.NullUnlimitedList list = new PdfPagesTree.NullUnlimitedList(); - list.Add("hey"); - list.Add("bye"); - NUnit.Framework.Assert.AreEqual(2, list.Size()); - list.Add(-1, "hello"); - list.Add(3, "goodbye"); - NUnit.Framework.Assert.AreEqual(2, list.Size()); + public virtual void DefaultImplementationIsExpectedInstance() { + PdfDocument pdfDoc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream())); + pdfDoc.GetCatalog().Put(PdfName.Count, new PdfNumber(10)); + IPageTreeListFactory factory = pdfDoc.GetDiContainer().GetInstance(); + NUnit.Framework.Assert.IsTrue(factory is DefaultPageTreeListFactory); + } + + [NUnit.Framework.Test] + public virtual void DefaultImplementationWritingOnlyReturnArrayList() { + PdfDocument pdfDoc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream())); + IPageTreeListFactory factory = pdfDoc.GetDiContainer().GetInstance(); + NUnit.Framework.Assert.IsTrue(factory.CreateList(null) is SimpleArrayList); } [NUnit.Framework.Test] - public virtual void NullUnlimitedListIndexOfTest() { - PdfPagesTree.NullUnlimitedList list = new PdfPagesTree.NullUnlimitedList(); - list.Add("hey"); - list.Add(null); - list.Add("bye"); - list.Add(null); - NUnit.Framework.Assert.AreEqual(4, list.Size()); - NUnit.Framework.Assert.AreEqual(1, list.IndexOf(null)); + public virtual void DefaultImplementationReadingAndModifyingNullUnlimitedList() { + PdfDocument pdfDoc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream())); + IPageTreeListFactory factory = pdfDoc.GetDiContainer().GetInstance(); + PdfDictionary dict = new PdfDictionary(); + dict.Put(PdfName.Count, new PdfNumber(int.MaxValue)); + NUnit.Framework.Assert.IsTrue(factory.CreateList(dict) is NullUnlimitedList); } [NUnit.Framework.Test] - public virtual void NullUnlimitedListRemoveTest() { - PdfPagesTree.NullUnlimitedList list = new PdfPagesTree.NullUnlimitedList(); - list.Add("hey"); - list.Add("bye"); - NUnit.Framework.Assert.AreEqual(2, list.Size()); - list.Remove(-1); - list.Remove(2); - NUnit.Framework.Assert.AreEqual(2, list.Size()); + public virtual void DefaultImplementationReadingAndModifyingArrayList() { + PdfDocument pdfDoc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream())); + IPageTreeListFactory factory = pdfDoc.GetDiContainer().GetInstance(); + PdfDictionary dict = new PdfDictionary(); + dict.Put(PdfName.Count, new PdfNumber(10)); + NUnit.Framework.Assert.IsTrue(factory.CreateList(dict) is SimpleArrayList); + } + + [NUnit.Framework.Test] + public virtual void DefaultImplementationReadingAndModifyingArrayListNegative() { + PdfDocument pdfDoc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream())); + IPageTreeListFactory factory = pdfDoc.GetDiContainer().GetInstance(); + PdfDictionary dict = new PdfDictionary(); + dict.Put(PdfName.Count, new PdfNumber(-10)); + NUnit.Framework.Assert.IsTrue(factory.CreateList(dict) is NullUnlimitedList); + } + + [NUnit.Framework.Test] + public virtual void DefaultImplementationReadingAndModifyingArrayListNull() { + PdfDocument pdfDoc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream())); + IPageTreeListFactory factory = pdfDoc.GetDiContainer().GetInstance(); + PdfDictionary dict = new PdfDictionary(); + dict.Put(PdfName.Count, new PdfNull()); + NUnit.Framework.Assert.IsTrue(factory.CreateList(dict) is NullUnlimitedList); } } } diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfReaderDecodeTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfReaderDecodeTest.cs index 9120f58764..45be339a58 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfReaderDecodeTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfReaderDecodeTest.cs @@ -58,7 +58,7 @@ public virtual void NoMemoryHandlerTest() { [NUnit.Framework.Test] [LogMessage(iText.IO.Logs.IoLogMessageConstant.INVALID_INDIRECT_REFERENCE)] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] public virtual void DefaultMemoryHandlerTest() { using (PdfDocument pdfDocument = new PdfDocument(new PdfReader(SOURCE_FOLDER + "timing.pdf"), new PdfWriter (new MemoryStream()))) { @@ -78,7 +78,7 @@ public virtual void DefaultMemoryHandlerTest() { [NUnit.Framework.Test] [LogMessage(iText.IO.Logs.IoLogMessageConstant.INVALID_INDIRECT_REFERENCE)] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] public virtual void CustomMemoryHandlerSingleTest() { MemoryLimitsAwareHandler handler = new MemoryLimitsAwareHandler(); handler.SetMaxSizeOfSingleDecompressedPdfStream(1000); @@ -103,7 +103,7 @@ public virtual void CustomMemoryHandlerSingleTest() { [NUnit.Framework.Test] [LogMessage(iText.IO.Logs.IoLogMessageConstant.INVALID_INDIRECT_REFERENCE)] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] public virtual void OneFilterCustomMemoryHandlerSingleTest() { MemoryLimitsAwareHandler handler = new MemoryLimitsAwareHandler(); handler.SetMaxSizeOfSingleDecompressedPdfStream(20); @@ -123,9 +123,9 @@ public virtual void OneFilterCustomMemoryHandlerSingleTest() { [NUnit.Framework.Test] [LogMessage(iText.IO.Logs.IoLogMessageConstant.INVALID_INDIRECT_REFERENCE)] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] public virtual void OverriddenMemoryHandlerAllStreamsAreSuspiciousTest() { - MemoryLimitsAwareHandler handler = new _MemoryLimitsAwareHandler_175(); + MemoryLimitsAwareHandler handler = new _MemoryLimitsAwareHandler_174(); handler.SetMaxSizeOfSingleDecompressedPdfStream(20); using (PdfDocument pdfDocument = new PdfDocument(new PdfReader(SOURCE_FOLDER + "timing.pdf", new ReaderProperties ().SetMemoryLimitsAwareHandler(handler)), new PdfWriter(new MemoryStream()))) { @@ -142,8 +142,8 @@ public virtual void OverriddenMemoryHandlerAllStreamsAreSuspiciousTest() { } } - private sealed class _MemoryLimitsAwareHandler_175 : MemoryLimitsAwareHandler { - public _MemoryLimitsAwareHandler_175() { + private sealed class _MemoryLimitsAwareHandler_174 : MemoryLimitsAwareHandler { + public _MemoryLimitsAwareHandler_174() { } public override bool IsMemoryLimitsAwarenessRequiredOnDecompression(PdfArray filters) { @@ -153,9 +153,9 @@ public override bool IsMemoryLimitsAwarenessRequiredOnDecompression(PdfArray fil [NUnit.Framework.Test] [LogMessage(iText.IO.Logs.IoLogMessageConstant.INVALID_INDIRECT_REFERENCE)] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] public virtual void OverriddenMemoryHandlerNoStreamsAreSuspiciousTest() { - MemoryLimitsAwareHandler handler = new _MemoryLimitsAwareHandler_210(); + MemoryLimitsAwareHandler handler = new _MemoryLimitsAwareHandler_209(); handler.SetMaxSizeOfSingleDecompressedPdfStream(20); using (PdfDocument pdfDocument = new PdfDocument(new PdfReader(SOURCE_FOLDER + "timing.pdf", new ReaderProperties ().SetMemoryLimitsAwareHandler(handler)), new PdfWriter(new MemoryStream()))) { @@ -170,8 +170,8 @@ public virtual void OverriddenMemoryHandlerNoStreamsAreSuspiciousTest() { } } - private sealed class _MemoryLimitsAwareHandler_210 : MemoryLimitsAwareHandler { - public _MemoryLimitsAwareHandler_210() { + private sealed class _MemoryLimitsAwareHandler_209 : MemoryLimitsAwareHandler { + public _MemoryLimitsAwareHandler_209() { } public override bool IsMemoryLimitsAwarenessRequiredOnDecompression(PdfArray filters) { @@ -194,7 +194,7 @@ public virtual void DifferentFiltersEmptyTest() { [NUnit.Framework.Test] [LogMessage(iText.IO.Logs.IoLogMessageConstant.INVALID_INDIRECT_REFERENCE)] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] public virtual void CustomMemoryHandlerSumTest() { MemoryLimitsAwareHandler handler = new MemoryLimitsAwareHandler(); handler.SetMaxSizeOfDecompressedPdfStreamsSum(100000); @@ -211,7 +211,7 @@ public virtual void CustomMemoryHandlerSumTest() { [NUnit.Framework.Test] [LogMessage(iText.IO.Logs.IoLogMessageConstant.INVALID_INDIRECT_REFERENCE)] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] public virtual void PageSumTest() { MemoryLimitsAwareHandler handler = new MemoryLimitsAwareHandler(); handler.SetMaxSizeOfDecompressedPdfStreamsSum(1500000); @@ -226,7 +226,7 @@ public virtual void PageSumTest() { [NUnit.Framework.Test] [LogMessage(iText.IO.Logs.IoLogMessageConstant.INVALID_INDIRECT_REFERENCE)] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] public virtual void PageAsSingleStreamTest() { MemoryLimitsAwareHandler handler = new MemoryLimitsAwareHandler(); handler.SetMaxSizeOfSingleDecompressedPdfStream(1500000); diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfReaderTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfReaderTest.cs index e1320af607..1d3fa66614 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfReaderTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfReaderTest.cs @@ -675,7 +675,8 @@ public virtual void PagesTest11() { } [NUnit.Framework.Test] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT, Count = 1)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE, + Count = 1)] public virtual void CorrectSimpleDoc1() { String filename = SOURCE_FOLDER + "correctSimpleDoc1.pdf"; PdfReader reader = new PdfReader(filename); @@ -702,7 +703,8 @@ public virtual void CorrectSimpleDoc2() { } [NUnit.Framework.Test] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT, Count = 1)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE, + Count = 1)] public virtual void CorrectSimpleDoc3() { String filename = SOURCE_FOLDER + "correctSimpleDoc3.pdf"; PdfReader reader = new PdfReader(filename); @@ -716,7 +718,7 @@ public virtual void CorrectSimpleDoc3() { } [NUnit.Framework.Test] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] [LogMessage(iText.IO.Logs.IoLogMessageConstant.INVALID_INDIRECT_REFERENCE)] public virtual void CorrectSimpleDoc4() { String filename = SOURCE_FOLDER + "correctSimpleDoc4.pdf"; @@ -736,7 +738,7 @@ public virtual void CorrectSimpleDoc4() { } [NUnit.Framework.Test] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] public virtual void FixPdfTest01() { String filename = SOURCE_FOLDER + "OnlyTrailer.pdf"; PdfReader reader = new PdfReader(filename); @@ -802,7 +804,7 @@ public virtual void FixPdfTest04() { } [NUnit.Framework.Test] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] public virtual void FixPdfTest05() { String filename = SOURCE_FOLDER + "CompressionWrongShift.pdf"; PdfReader reader = new PdfReader(filename); @@ -850,7 +852,7 @@ public virtual void FixPdfTest07() { } [NUnit.Framework.Test] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] public virtual void FixPdfTest08() { String filename = SOURCE_FOLDER + "XRefSectionWithFreeReferences2.pdf"; PdfReader reader = new PdfReader(filename); @@ -870,7 +872,7 @@ public virtual void FixPdfTest08() { } [NUnit.Framework.Test] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] public virtual void FixPdfTest09() { String filename = SOURCE_FOLDER + "XRefSectionWithFreeReferences3.pdf"; PdfReader reader = new PdfReader(filename); @@ -911,7 +913,7 @@ public virtual void FixPdfTest10() { } [NUnit.Framework.Test] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] public virtual void FixPdfTest11() { String filename = SOURCE_FOLDER + "XRefSectionWithoutSize.pdf"; PdfReader reader = new PdfReader(filename); @@ -928,7 +930,7 @@ public virtual void FixPdfTest11() { } [NUnit.Framework.Test] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] public virtual void FixPdfTest12() { String filename = SOURCE_FOLDER + "XRefWithBreaks.pdf"; PdfReader reader = new PdfReader(filename); @@ -1003,7 +1005,7 @@ public virtual void FixPdfTest14() { } [NUnit.Framework.Test] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] public virtual void FixPdfTest15() { String filename = SOURCE_FOLDER + "XRefWithInvalidGenerations3.pdf"; PdfReader reader = new PdfReader(filename); @@ -1037,7 +1039,7 @@ public virtual void FixPdfTest16() { } [NUnit.Framework.Test] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] public virtual void FixPdfTest17() { String filename = SOURCE_FOLDER + "XrefWithNullOffsets.pdf"; PdfReader reader = new PdfReader(filename); @@ -1054,7 +1056,7 @@ public virtual void FixPdfTest17() { } [NUnit.Framework.Test] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] public virtual void FixPdfTest18() { String filename = SOURCE_FOLDER + "noXrefAndTrailerWithInfo.pdf"; PdfReader reader = new PdfReader(filename); @@ -1148,7 +1150,7 @@ public virtual void AppendModeWith10PagesWithCompression() { } [NUnit.Framework.Test] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] public virtual void AppendModeWith10PagesFix1() { String filename = SOURCE_FOLDER + "10PagesDocumentAppendedFix1.pdf"; PdfReader reader = new PdfReader(filename); @@ -1170,7 +1172,7 @@ public virtual void AppendModeWith10PagesFix1() { } [NUnit.Framework.Test] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] public virtual void AppendModeWith10PagesFix2() { String filename = SOURCE_FOLDER + "10PagesDocumentAppendedFix2.pdf"; PdfReader reader = new PdfReader(filename); @@ -1211,10 +1213,10 @@ public virtual void IncorrectXrefSizeInTrailerAppend() { document.Close(); } + [NUnit.Framework.Test] #if !NETSTANDARD2_0 [NUnit.Framework.Timeout(1000)] #endif // !NETSTANDARD2_0 - [NUnit.Framework.Test] public virtual void StreamLengthCorrection1() { lock (this) { String filename = SOURCE_FOLDER + "10PagesDocumentWithInvalidStreamLength.pdf"; @@ -1231,10 +1233,10 @@ public virtual void StreamLengthCorrection1() { } } + [NUnit.Framework.Test] #if !NETSTANDARD2_0 [NUnit.Framework.Timeout(1000)] #endif // !NETSTANDARD2_0 - [NUnit.Framework.Test] public virtual void StreamLengthCorrection2() { lock (this) { String filename = SOURCE_FOLDER + "simpleCanvasWithDrawingLength1.pdf"; @@ -1248,10 +1250,10 @@ public virtual void StreamLengthCorrection2() { } } + [NUnit.Framework.Test] #if !NETSTANDARD2_0 [NUnit.Framework.Timeout(1000)] #endif // !NETSTANDARD2_0 - [NUnit.Framework.Test] public virtual void StreamLengthCorrection3() { lock (this) { String filename = SOURCE_FOLDER + "simpleCanvasWithDrawingLength2.pdf"; @@ -1265,10 +1267,10 @@ public virtual void StreamLengthCorrection3() { } } + [NUnit.Framework.Test] #if !NETSTANDARD2_0 [NUnit.Framework.Timeout(1000)] #endif // !NETSTANDARD2_0 - [NUnit.Framework.Test] public virtual void StreamLengthCorrection4() { lock (this) { String filename = SOURCE_FOLDER + "simpleCanvasWithDrawingLength3.pdf"; @@ -1282,10 +1284,10 @@ public virtual void StreamLengthCorrection4() { } } + [NUnit.Framework.Test] #if !NETSTANDARD2_0 [NUnit.Framework.Timeout(1000)] #endif // !NETSTANDARD2_0 - [NUnit.Framework.Test] public virtual void StreamLengthCorrection5() { lock (this) { String filename = SOURCE_FOLDER + "simpleCanvasWithDrawingLength4.pdf"; @@ -1299,10 +1301,10 @@ public virtual void StreamLengthCorrection5() { } } + [NUnit.Framework.Test] #if !NETSTANDARD2_0 [NUnit.Framework.Timeout(1000)] #endif // !NETSTANDARD2_0 - [NUnit.Framework.Test] public virtual void StreamLengthCorrection6() { lock (this) { String filename = SOURCE_FOLDER + "simpleCanvasWithDrawingWithInvalidStreamLength1.pdf"; @@ -1316,10 +1318,10 @@ public virtual void StreamLengthCorrection6() { } } + [NUnit.Framework.Test] #if !NETSTANDARD2_0 [NUnit.Framework.Timeout(1000)] #endif // !NETSTANDARD2_0 - [NUnit.Framework.Test] public virtual void StreamLengthCorrection7() { lock (this) { String filename = SOURCE_FOLDER + "simpleCanvasWithDrawingWithInvalidStreamLength2.pdf"; @@ -1333,10 +1335,10 @@ public virtual void StreamLengthCorrection7() { } } + [NUnit.Framework.Test] #if !NETSTANDARD2_0 [NUnit.Framework.Timeout(1000)] #endif // !NETSTANDARD2_0 - [NUnit.Framework.Test] public virtual void StreamLengthCorrection8() { lock (this) { String filename = SOURCE_FOLDER + "simpleCanvasWithDrawingWithInvalidStreamLength3.pdf"; @@ -1350,10 +1352,10 @@ public virtual void StreamLengthCorrection8() { } } + [NUnit.Framework.Test] #if !NETSTANDARD2_0 [NUnit.Framework.Timeout(1000)] #endif // !NETSTANDARD2_0 - [NUnit.Framework.Test] public virtual void StreamLengthCorrection9() { lock (this) { String filename = SOURCE_FOLDER + "10PagesDocumentWithInvalidStreamLength2.pdf"; @@ -1377,7 +1379,7 @@ public virtual void FreeReferencesTest() { String filename = SOURCE_FOLDER + "freeReferences.pdf"; PdfDocument pdfDoc = new PdfDocument(new PdfReader(filename)); NUnit.Framework.Assert.IsNull(pdfDoc.GetPdfObject(8)); - //Assert.assertFalse(pdfDoc.getReader().fixedXref); + //Assertions.assertFalse(pdfDoc.getReader().fixedXref); NUnit.Framework.Assert.IsFalse(pdfDoc.GetReader().rebuiltXref); pdfDoc.Close(); } @@ -1438,7 +1440,7 @@ public virtual void IncrementalUpdateWithOnlyZeroObjectUpdate() { [NUnit.Framework.Test] [LogMessage(iText.IO.Logs.IoLogMessageConstant.INVALID_INDIRECT_REFERENCE, Count = 1)] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] [LogMessage(iText.IO.Logs.IoLogMessageConstant.ENCOUNTERED_INVALID_MCR)] public virtual void WrongTagStructureFlushingTest() { //wrong /Pg number @@ -1515,12 +1517,12 @@ public virtual void HasRebuiltXrefPdfDocumentNotReadTest() { [NUnit.Framework.Test] public virtual void HasRebuiltXrefReadingNotCompletedTest() { String filename = SOURCE_FOLDER + "XrefWithNullOffsets.pdf"; - PdfReader hasRebuiltXrefReader = new _PdfReader_1779(filename); + PdfReader hasRebuiltXrefReader = new _PdfReader_1789(filename); ReadingNotCompletedTest(hasRebuiltXrefReader); } - private sealed class _PdfReader_1779 : PdfReader { - public _PdfReader_1779(String baseArg1) + private sealed class _PdfReader_1789 : PdfReader { + public _PdfReader_1789(String baseArg1) : base(baseArg1) { } @@ -1541,12 +1543,12 @@ public virtual void HasHybridXrefPdfDocumentNotReadTest() { [NUnit.Framework.Test] public virtual void HasHybridXrefReadingNotCompletedTest() { String filename = SOURCE_FOLDER + "XrefWithNullOffsets.pdf"; - PdfReader hasHybridXrefPdfReader = new _PdfReader_1802(filename); + PdfReader hasHybridXrefPdfReader = new _PdfReader_1812(filename); ReadingNotCompletedTest(hasHybridXrefPdfReader); } - private sealed class _PdfReader_1802 : PdfReader { - public _PdfReader_1802(String baseArg1) + private sealed class _PdfReader_1812 : PdfReader { + public _PdfReader_1812(String baseArg1) : base(baseArg1) { } @@ -1566,12 +1568,12 @@ public virtual void HasXrefStmPdfDocumentNotReadTest() { [NUnit.Framework.Test] public virtual void HasXrefStmReadingNotCompletedTest() { String filename = SOURCE_FOLDER + "XrefWithNullOffsets.pdf"; - PdfReader hasXrefStmReader = new _PdfReader_1825(filename); + PdfReader hasXrefStmReader = new _PdfReader_1835(filename); ReadingNotCompletedTest(hasXrefStmReader); } - private sealed class _PdfReader_1825 : PdfReader { - public _PdfReader_1825(String baseArg1) + private sealed class _PdfReader_1835 : PdfReader { + public _PdfReader_1835(String baseArg1) : base(baseArg1) { } @@ -1591,12 +1593,12 @@ public virtual void HasFixedXrefPdfDocumentNotReadTest() { [NUnit.Framework.Test] public virtual void HasFixedXrefReadingNotCompletedTest() { String filename = SOURCE_FOLDER + "XrefWithNullOffsets.pdf"; - PdfReader hasFixedXrefReader = new _PdfReader_1848(filename); + PdfReader hasFixedXrefReader = new _PdfReader_1858(filename); ReadingNotCompletedTest(hasFixedXrefReader); } - private sealed class _PdfReader_1848 : PdfReader { - public _PdfReader_1848(String baseArg1) + private sealed class _PdfReader_1858 : PdfReader { + public _PdfReader_1858(String baseArg1) : base(baseArg1) { } @@ -1616,12 +1618,12 @@ public virtual void GetLastXrefPdfDocumentNotReadTest() { [NUnit.Framework.Test] public virtual void GetLastXrefReadingNotCompletedTest() { String filename = SOURCE_FOLDER + "XrefWithNullOffsets.pdf"; - PdfReader getLastXrefReader = new _PdfReader_1871(filename); + PdfReader getLastXrefReader = new _PdfReader_1881(filename); ReadingNotCompletedTest(getLastXrefReader); } - private sealed class _PdfReader_1871 : PdfReader { - public _PdfReader_1871(String baseArg1) + private sealed class _PdfReader_1881 : PdfReader { + public _PdfReader_1881(String baseArg1) : base(baseArg1) { } @@ -1642,12 +1644,12 @@ public virtual void GetPermissionsPdfDocumentNotReadTest() { [NUnit.Framework.Test] public virtual void GetPermissionsReadingNotCompletedTest() { String filename = SOURCE_FOLDER + "XrefWithNullOffsets.pdf"; - PdfReader getPermissionsReader = new _PdfReader_1894(filename); + PdfReader getPermissionsReader = new _PdfReader_1904(filename); ReadingNotCompletedTest(getPermissionsReader); } - private sealed class _PdfReader_1894 : PdfReader { - public _PdfReader_1894(String baseArg1) + private sealed class _PdfReader_1904 : PdfReader { + public _PdfReader_1904(String baseArg1) : base(baseArg1) { } @@ -1668,12 +1670,12 @@ public virtual void IsOpenedWithFullPPdfDocumentNotReadTest() { [NUnit.Framework.Test] public virtual void IsOpenedWithFullPReadingNotCompletedTest() { String filename = SOURCE_FOLDER + "XrefWithNullOffsets.pdf"; - PdfReader isOpenedWithFullPReader = new _PdfReader_1919(filename); + PdfReader isOpenedWithFullPReader = new _PdfReader_1929(filename); ReadingNotCompletedTest(isOpenedWithFullPReader); } - private sealed class _PdfReader_1919 : PdfReader { - public _PdfReader_1919(String baseArg1) + private sealed class _PdfReader_1929 : PdfReader { + public _PdfReader_1929(String baseArg1) : base(baseArg1) { } @@ -1694,12 +1696,12 @@ public virtual void GetCryptoModePdfDocumentNotReadTest() { [NUnit.Framework.Test] public virtual void GetCryptoModeReadingNotCompletedTest() { String filename = SOURCE_FOLDER + "XrefWithNullOffsets.pdf"; - PdfReader getCryptoModeReader = new _PdfReader_1942(filename); + PdfReader getCryptoModeReader = new _PdfReader_1952(filename); ReadingNotCompletedTest(getCryptoModeReader); } - private sealed class _PdfReader_1942 : PdfReader { - public _PdfReader_1942(String baseArg1) + private sealed class _PdfReader_1952 : PdfReader { + public _PdfReader_1952(String baseArg1) : base(baseArg1) { } @@ -1720,12 +1722,12 @@ public virtual void ComputeUserPasswordPdfDocumentNotReadTest() { [NUnit.Framework.Test] public virtual void ComputeUserPasswordReadingNotCompletedTest() { String filename = SOURCE_FOLDER + "XrefWithNullOffsets.pdf"; - PdfReader computeUserPasswordReader = new _PdfReader_1967(filename); + PdfReader computeUserPasswordReader = new _PdfReader_1977(filename); ReadingNotCompletedTest(computeUserPasswordReader); } - private sealed class _PdfReader_1967 : PdfReader { - public _PdfReader_1967(String baseArg1) + private sealed class _PdfReader_1977 : PdfReader { + public _PdfReader_1977(String baseArg1) : base(baseArg1) { } @@ -1746,12 +1748,12 @@ public virtual void GetOriginalFileIdPdfDocumentNotReadTest() { [NUnit.Framework.Test] public virtual void GetOriginalFileIdReadingNotCompletedTest() { String filename = SOURCE_FOLDER + "XrefWithNullOffsets.pdf"; - PdfReader getOriginalFileIdReader = new _PdfReader_1990(filename); + PdfReader getOriginalFileIdReader = new _PdfReader_2000(filename); ReadingNotCompletedTest(getOriginalFileIdReader); } - private sealed class _PdfReader_1990 : PdfReader { - public _PdfReader_1990(String baseArg1) + private sealed class _PdfReader_2000 : PdfReader { + public _PdfReader_2000(String baseArg1) : base(baseArg1) { } @@ -1772,12 +1774,12 @@ public virtual void GetModifiedFileIdPdfDocumentNotReadTest() { [NUnit.Framework.Test] public virtual void GetModifiedFileIdReadingNotCompletedTest() { String filename = SOURCE_FOLDER + "XrefWithNullOffsets.pdf"; - PdfReader getModifiedFileIdReader = new _PdfReader_2013(filename); + PdfReader getModifiedFileIdReader = new _PdfReader_2023(filename); ReadingNotCompletedTest(getModifiedFileIdReader); } - private sealed class _PdfReader_2013 : PdfReader { - public _PdfReader_2013(String baseArg1) + private sealed class _PdfReader_2023 : PdfReader { + public _PdfReader_2023(String baseArg1) : base(baseArg1) { } @@ -1797,12 +1799,12 @@ public virtual void IsEncryptedPdfDocumentNotReadTest() { [NUnit.Framework.Test] public virtual void IsEncryptedReadingNotCompletedTest() { String filename = SOURCE_FOLDER + "XrefWithNullOffsets.pdf"; - PdfReader isEncryptedReader = new _PdfReader_2036(filename); + PdfReader isEncryptedReader = new _PdfReader_2046(filename); ReadingNotCompletedTest(isEncryptedReader); } - private sealed class _PdfReader_2036 : PdfReader { - public _PdfReader_2036(String baseArg1) + private sealed class _PdfReader_2046 : PdfReader { + public _PdfReader_2046(String baseArg1) : base(baseArg1) { } @@ -1925,7 +1927,7 @@ public virtual void EndObjInsteadOfArrayClosingBracketTest() { [NUnit.Framework.Test] [LogMessage(KernelExceptionMessageConstant.UNEXPECTED_TOKEN)] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] public virtual void NameInsteadOfArrayClosingBracketTest() { String fileName = SOURCE_FOLDER + "invalidArrayNameToken.pdf"; PdfDocument document = new PdfDocument(new PdfReader(fileName)); @@ -1974,7 +1976,7 @@ public virtual void StartArrayInsteadOfArrayClosingBracketTest() { [NUnit.Framework.Test] [LogMessage(KernelExceptionMessageConstant.UNEXPECTED_TOKEN)] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] public virtual void StringInsteadOfArrayClosingBracketTest() { String fileName = SOURCE_FOLDER + "invalidArrayStringToken.pdf"; PdfDocument document = new PdfDocument(new PdfReader(fileName)); @@ -2054,17 +2056,17 @@ private void ReadingNotCompletedTest(PdfReader reader) { } [NUnit.Framework.Test] - public virtual void GetPdfAConformanceLevelPdfDocumentNotReadTest() { + public virtual void GetPdfAConformancePdfDocumentNotReadTest() { PdfReader getModifiedFileIdReader = PdfDocumentNotReadTestInit(); - Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => getModifiedFileIdReader.GetPdfAConformanceLevel + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => getModifiedFileIdReader.GetPdfConformance ()); NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.DOCUMENT_HAS_NOT_BEEN_READ_YET, e.Message); } [NUnit.Framework.Test] - public virtual void GetPdfAConformanceLevelNoMetadataTest() { + public virtual void GetPdfConformanceNoMetadataTest() { PdfDocument pdfDoc = new PdfDocument(new PdfReader(new MemoryStream(CreatePdfDocumentForTest()))); - NUnit.Framework.Assert.IsNull(pdfDoc.GetReader().GetPdfAConformanceLevel()); + NUnit.Framework.Assert.IsFalse(pdfDoc.GetReader().GetPdfConformance().IsPdfAOrUa()); } [NUnit.Framework.Test] @@ -2092,7 +2094,7 @@ public virtual void XrefStreamPointsItselfConservativeModeTest() { } } - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] [NUnit.Framework.Test] public virtual void ExactLimitOfObjectNrSizeTest() { String fileName = SOURCE_FOLDER + "exactLimitOfObjectNr.pdf"; @@ -2104,7 +2106,7 @@ public virtual void ExactLimitOfObjectNrSizeTest() { } } - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] [NUnit.Framework.Test] public virtual void JustBeforeLimitOfObjectNrSizeTest() { String inputFile = SOURCE_FOLDER + "justBeforeLimitOfObjectNr.pdf"; @@ -2141,7 +2143,8 @@ public virtual void XrefStreamsHaveCycledReferencesConservativeModeTest() { } [NUnit.Framework.Test] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT, Count = 1)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE, + Count = 1)] public virtual void XrefTablesHaveCycledReferencesTest() { String fileName = SOURCE_FOLDER + "cycledReferencesInXrefTables.pdf"; using (PdfReader pdfReader = new PdfReader(fileName)) { @@ -2152,7 +2155,8 @@ public virtual void XrefTablesHaveCycledReferencesTest() { } [NUnit.Framework.Test] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT, Count = 1)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE, + Count = 1)] public virtual void XrefTablePointsItselfTest() { String fileName = SOURCE_FOLDER + "xrefTablePointsItself.pdf"; using (PdfReader pdfReader = new PdfReader(fileName)) { @@ -2353,14 +2357,14 @@ public virtual void StreamWithoutEndstreamKeywordTest() { using (PdfReader reader = new PdfReader(fileName)) { reader.SetStrictnessLevel(PdfReader.StrictnessLevel.LENIENT); using (PdfDocument document = new PdfDocument(reader)) { + // Initialize xmp metadata, because we in reader mode in which xmp will be initialized only during closing + byte[] metadataBytes = document.GetXmpMetadataBytes(); PdfCatalog catalog = new PdfCatalog((PdfDictionary)reader.trailer.Get(PdfName.Root, true)); PdfStream xmpMetadataStream = catalog.GetPdfObject().GetAsStream(PdfName.Metadata); int xmpMetadataStreamLength = ((PdfNumber)xmpMetadataStream.Get(PdfName.Length)).IntValue(); - // 27600 is actual invalid length of stream. In reader StrictnessLevel#LENIENT we expect, that this - // length will be fixed. - NUnit.Framework.Assert.AreNotEqual(27600, xmpMetadataStreamLength); - // 3090 is expected length of the stream after fix. + // Initial length was 27600. 3090 is expected length of the stream after the fix NUnit.Framework.Assert.AreEqual(3090, xmpMetadataStreamLength); + NUnit.Framework.Assert.AreEqual(3090, metadataBytes.Length); } } } @@ -2381,6 +2385,18 @@ public virtual void StreamWithoutEndstreamKeywordConservativeModeTest() { } } + [NUnit.Framework.Test] + public virtual void StreamWithoutEndKeyConservativeModeWithWriterTest() { + String fileName = SOURCE_FOLDER + "NoEndstreamKeyword.pdf"; + using (PdfReader reader = new PdfReader(fileName)) { + reader.SetStrictnessLevel(PdfReader.StrictnessLevel.CONSERVATIVE); + Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => new PdfDocument(reader, new + PdfWriter(new ByteArrayOutputStream()))); + NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.STREAM_SHALL_END_WITH_ENDSTREAM, exception. + Message); + } + } + [NUnit.Framework.Test] public virtual void TokensPositionIsNotUpdatedWhileReadingLengthTest() { String filename = SOURCE_FOLDER + "simpleDocWithIndirectLength.pdf"; @@ -2400,7 +2416,7 @@ public virtual void TokensPositionIsNotUpdatedWhileReadingLengthTest() { } [NUnit.Framework.Test] - public virtual void ConformanceLevelCacheTest() { + public virtual void ConformanceCacheTest() { String filename = DESTINATION_FOLDER + "simpleDoc.pdf"; PdfDocument pdfDoc = new PdfDocument(CompareTool.CreateTestPdfWriter(filename)); XMPMeta xmp = XMPMetaFactory.Create(); @@ -2412,13 +2428,14 @@ public virtual void ConformanceLevelCacheTest() { PdfReaderTest.TestPdfDocumentCache pdfTestDoc = new PdfReaderTest.TestPdfDocumentCache(this, CompareTool.CreateOutputReader (filename)); for (int i = 0; i < 1000; ++i) { - pdfTestDoc.GetReader().GetPdfAConformanceLevel(); + pdfTestDoc.GetReader().GetPdfConformance(); } - NUnit.Framework.Assert.AreEqual(2, pdfTestDoc.GetCounter()); + NUnit.Framework.Assert.AreEqual(1, pdfTestDoc.GetCounter()); } [NUnit.Framework.Test] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT, Count = 1)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE, + Count = 1)] public virtual void InvalidXrefTableRebuildsCorrectlyWhenTrailerIsBeforeObjects() { // when a pdf is Linearized the following can occur: // xref table @@ -2515,14 +2532,14 @@ public virtual void StreamObjIsNullTest() { int objNumber = pdfDictionary.GetIndirectReference().objNr; pdfDocument.catalog.GetPdfObject().Put(PdfName.StructTreeRoot, pdfDictionary); pdfDocument.Close(); - PdfReader pdfReader = new _PdfReader_2831(objNumber, new MemoryStream(bsaos.ToArray())); + PdfReader pdfReader = new _PdfReader_2851(objNumber, new MemoryStream(bsaos.ToArray())); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => new PdfDocument(pdfReader)); NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(KernelExceptionMessageConstant.INVALID_OBJECT_STREAM_NUMBER , 5, 4, 492), e.Message); } - private sealed class _PdfReader_2831 : PdfReader { - public _PdfReader_2831(int objNumber, Stream baseArg1) + private sealed class _PdfReader_2851 : PdfReader { + public _PdfReader_2851(int objNumber, Stream baseArg1) : base(baseArg1) { this.objNumber = objNumber; } @@ -2541,7 +2558,7 @@ protected internal override PdfObject ReadObject(PdfIndirectReference reference) [NUnit.Framework.Test] public virtual void InitTagTreeStructureThrowsOOMIsCatched() { FileInfo file = new FileInfo(SOURCE_FOLDER + "big_table_lot_of_mcrs.pdf"); - MemoryLimitsAwareHandler memoryLimitsAwareHandler = new _MemoryLimitsAwareHandler_2850(); + MemoryLimitsAwareHandler memoryLimitsAwareHandler = new _MemoryLimitsAwareHandler_2870(); memoryLimitsAwareHandler.SetMaxSizeOfDecompressedPdfStreamsSum(100000); NUnit.Framework.Assert.Catch(typeof(MemoryLimitsAwareException), () => { using (PdfReader reader = new PdfReader(file, new ReaderProperties().SetMemoryLimitsAwareHandler(memoryLimitsAwareHandler @@ -2553,8 +2570,8 @@ public virtual void InitTagTreeStructureThrowsOOMIsCatched() { ); } - private sealed class _MemoryLimitsAwareHandler_2850 : MemoryLimitsAwareHandler { - public _MemoryLimitsAwareHandler_2850() { + private sealed class _MemoryLimitsAwareHandler_2870 : MemoryLimitsAwareHandler { + public _MemoryLimitsAwareHandler_2870() { } public override bool IsMemoryLimitsAwarenessRequiredOnDecompression(PdfArray filters) { @@ -2562,6 +2579,50 @@ public override bool IsMemoryLimitsAwarenessRequiredOnDecompression(PdfArray fil } } + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] + [NUnit.Framework.Test] + public virtual void IncorrectFilePositionInSubsectionCauseTest() { + PdfReader pdfReader = new PdfReader(SOURCE_FOLDER + "incorrectFilePositionInSubsection.pdf").SetStrictnessLevel + (PdfReader.StrictnessLevel.LENIENT); + new PdfDocument(pdfReader); + NUnit.Framework.Assert.IsTrue(pdfReader.HasRebuiltXref(), "Need rebuildXref()"); + } + + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] + [NUnit.Framework.Test] + public virtual void NoSubsectionCauseTest() { + PdfReader pdfReader = new PdfReader(SOURCE_FOLDER + "noSubsection.pdf").SetStrictnessLevel(PdfReader.StrictnessLevel + .LENIENT); + new PdfDocument(pdfReader); + NUnit.Framework.Assert.IsTrue(pdfReader.HasRebuiltXref(), "Need rebuildXref()"); + } + + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] + [NUnit.Framework.Test] + public virtual void InvalidRefCauseXrefRebuildTest() { + PdfReader pdfReader = new PdfReader(SOURCE_FOLDER + "invalidRefCauseXrefRebuild.pdf").SetStrictnessLevel(PdfReader.StrictnessLevel + .LENIENT); + new PdfDocument(pdfReader); + NUnit.Framework.Assert.IsTrue(pdfReader.HasRebuiltXref(), "Need rebuildXref()"); + } + + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] + [NUnit.Framework.Test] + public virtual void StartxrefNotFoundCauseTest() { + PdfReader pdfReader = new PdfReader(SOURCE_FOLDER + "startxrefNotFound.pdf").SetStrictnessLevel(PdfReader.StrictnessLevel + .LENIENT); + new PdfDocument(pdfReader); + NUnit.Framework.Assert.IsTrue(pdfReader.HasRebuiltXref(), "Need rebuildXref()"); + } + + [NUnit.Framework.Test] + public virtual void ReadAandUaDocumentTest() { + using (PdfDocument pdfDoc = new PdfDocument(new PdfReader(SOURCE_FOLDER + "bothAandUa.pdf"))) { + NUnit.Framework.Assert.AreEqual(PdfAConformance.PDF_A_2B, pdfDoc.GetConformance().GetAConformance()); + NUnit.Framework.Assert.AreEqual(PdfUAConformance.PDF_UA_1, pdfDoc.GetConformance().GetUAConformance()); + } + } + private static PdfDictionary GetTestPdfDictionary() { Dictionary tmpMap = new Dictionary(); tmpMap.Put(new PdfName("b"), new PdfName("c")); @@ -2585,9 +2646,9 @@ public TestPdfDocumentCache(PdfReaderTest _enclosing, PdfReader pdfReader) this._enclosing = _enclosing; } - public override byte[] GetXmpMetadata(bool createNew) { + public override byte[] GetXmpMetadataBytes(bool createdNew) { ++this.getXmpMetadataCounter; - return base.GetXmpMetadata(createNew); + return base.GetXmpMetadataBytes(createdNew); } public virtual int GetCounter() { diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfRevisionsReaderTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfRevisionsReaderTest.cs index 5396fc6ac0..11af6b9809 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfRevisionsReaderTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfRevisionsReaderTest.cs @@ -66,10 +66,10 @@ public virtual void MultipleRevisionsDocument() { NUnit.Framework.Assert.AreEqual(3, documentRevisions.Count); DocumentRevision firstRevision = documentRevisions[0]; AssertResultingRevision(firstRevision, 1, 2, 3, 4, 5, 6); - NUnit.Framework.Assert.AreEqual(929, firstRevision.GetEofOffset()); + NUnit.Framework.Assert.AreEqual(930, firstRevision.GetEofOffset()); DocumentRevision secondRevision = documentRevisions[1]; AssertResultingRevision(secondRevision, 1, 3, 4, 7, 8, 9, 10, 11, 12, 13, 14, 15); - NUnit.Framework.Assert.AreEqual(28119, secondRevision.GetEofOffset()); + NUnit.Framework.Assert.AreEqual(28120, secondRevision.GetEofOffset()); DocumentRevision thirdRevision = documentRevisions[2]; AssertResultingRevision(thirdRevision, 1, 3, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28); NUnit.Framework.Assert.AreEqual(36207, thirdRevision.GetEofOffset()); @@ -85,16 +85,16 @@ public virtual void FreeReferencesDocument() { NUnit.Framework.Assert.AreEqual(5, documentRevisions.Count); DocumentRevision firstRevision = documentRevisions[0]; AssertResultingRevision(firstRevision, 1, 2, 3, 4, 5, 6); - NUnit.Framework.Assert.AreEqual(929, firstRevision.GetEofOffset()); + NUnit.Framework.Assert.AreEqual(930, firstRevision.GetEofOffset()); DocumentRevision secondRevision = documentRevisions[1]; AssertResultingRevision(secondRevision, 1, 3, 4, 7, 8, 9, 10, 11, 12, 13, 14, 15); - NUnit.Framework.Assert.AreEqual(28119, secondRevision.GetEofOffset()); + NUnit.Framework.Assert.AreEqual(28120, secondRevision.GetEofOffset()); DocumentRevision thirdRevision = documentRevisions[2]; AssertResultingRevision(thirdRevision, 1, 3, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28); - NUnit.Framework.Assert.AreEqual(36207, thirdRevision.GetEofOffset()); + NUnit.Framework.Assert.AreEqual(36208, thirdRevision.GetEofOffset()); DocumentRevision fourthRevision = documentRevisions[3]; AssertResultingRevision(fourthRevision, new int[] { 1, 3, 23, 24 }, new int[] { 0, 0, 1, 1 }); - NUnit.Framework.Assert.AreEqual(37006, fourthRevision.GetEofOffset()); + NUnit.Framework.Assert.AreEqual(37007, fourthRevision.GetEofOffset()); DocumentRevision fifthRevision = documentRevisions[4]; AssertResultingRevision(fifthRevision, new int[] { 1, 3, 19, 20, 21, 22, 23, 25 }, new int[] { 0, 0, 1, 1, 1, 1, 1, 1 }); @@ -111,10 +111,10 @@ public virtual void MultipleRevisionsWithXrefStreamTest() { NUnit.Framework.Assert.AreEqual(3, documentRevisions.Count); DocumentRevision firstRevision = documentRevisions[0]; AssertResultingRevision(firstRevision, 1, 2, 3, 4, 5, 6, 7, 8); - NUnit.Framework.Assert.AreEqual(1085, firstRevision.GetEofOffset()); + NUnit.Framework.Assert.AreEqual(1086, firstRevision.GetEofOffset()); DocumentRevision secondRevision = documentRevisions[1]; AssertResultingRevision(secondRevision, 1, 3, 4, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19); - NUnit.Framework.Assert.AreEqual(28137, secondRevision.GetEofOffset()); + NUnit.Framework.Assert.AreEqual(28138, secondRevision.GetEofOffset()); DocumentRevision thirdRevision = documentRevisions[2]; AssertResultingRevision(thirdRevision, 1, 3, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34); NUnit.Framework.Assert.AreEqual(36059, thirdRevision.GetEofOffset()); @@ -130,16 +130,16 @@ public virtual void FreeReferencesWithXrefStream() { NUnit.Framework.Assert.AreEqual(5, documentRevisions.Count); DocumentRevision firstRevision = documentRevisions[0]; AssertResultingRevision(firstRevision, 1, 2, 3, 4, 5, 6, 7, 8); - NUnit.Framework.Assert.AreEqual(1085, firstRevision.GetEofOffset()); + NUnit.Framework.Assert.AreEqual(1086, firstRevision.GetEofOffset()); DocumentRevision secondRevision = documentRevisions[1]; AssertResultingRevision(secondRevision, 1, 3, 4, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19); - NUnit.Framework.Assert.AreEqual(28137, secondRevision.GetEofOffset()); + NUnit.Framework.Assert.AreEqual(28138, secondRevision.GetEofOffset()); DocumentRevision thirdRevision = documentRevisions[2]; AssertResultingRevision(thirdRevision, 1, 3, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34); - NUnit.Framework.Assert.AreEqual(36059, thirdRevision.GetEofOffset()); + NUnit.Framework.Assert.AreEqual(36060, thirdRevision.GetEofOffset()); DocumentRevision fourthRevision = documentRevisions[3]; AssertResultingRevision(fourthRevision, new int[] { 1, 3, 27, 28, 35 }, new int[] { 0, 0, 1, 1, 0 }); - NUnit.Framework.Assert.AreEqual(36975, fourthRevision.GetEofOffset()); + NUnit.Framework.Assert.AreEqual(36976, fourthRevision.GetEofOffset()); DocumentRevision fifthRevision = documentRevisions[4]; AssertResultingRevision(fifthRevision, new int[] { 1, 3, 23, 24, 25, 26, 27, 29, 36 }, new int[] { 0, 0, 1 , 1, 1, 1, 1, 1, 0 }); diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfStampingTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfStampingTest.cs index 265c121127..390c9ab661 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfStampingTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfStampingTest.cs @@ -24,14 +24,13 @@ You should have received a copy of the GNU Affero General Public License using System.IO; using iText.Commons.Utils; using iText.IO.Source; -using iText.Kernel.Events; using iText.Kernel.Font; using iText.Kernel.Logs; using iText.Kernel.Pdf.Canvas; using iText.Kernel.Pdf.Canvas.Parser; using iText.Kernel.Pdf.Canvas.Parser.Listener; +using iText.Kernel.Pdf.Event; using iText.Kernel.Utils; -using iText.Kernel.XMP; using iText.Test; using iText.Test.Attributes; @@ -75,13 +74,13 @@ public virtual void Stamping1() { for (int i = 0; i < pdfDoc3.GetNumberOfPages(); i++) { pdfDoc3.GetPage(i + 1); } - NUnit.Framework.Assert.AreEqual(false, reader3.HasRebuiltXref(), "Rebuilt"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasFixedXref(), "Fixed"); + NUnit.Framework.Assert.IsFalse(reader3.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader3.HasFixedXref(), "Fixed"); VerifyPdfPagesCount(pdfDoc3.GetCatalog().GetPageTree().GetRoot().GetPdfObject()); pdfDoc3.Close(); PdfReader reader = CompareTool.CreateOutputReader(destinationFolder + "stamping1_2.pdf"); PdfDocument document = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); PdfDictionary trailer = document.GetTrailer(); PdfDictionary info = trailer.GetAsDictionary(PdfName.Info); PdfString creator = info.GetAsString(PdfName.Creator); @@ -117,13 +116,13 @@ public virtual void Stamping2() { for (int i = 0; i < pdfDoc3.GetNumberOfPages(); i++) { pdfDoc3.GetPage(i + 1); } - NUnit.Framework.Assert.AreEqual(false, reader3.HasRebuiltXref(), "Rebuilt"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasFixedXref(), "Fixed"); + NUnit.Framework.Assert.IsFalse(reader3.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader3.HasFixedXref(), "Fixed"); VerifyPdfPagesCount(pdfDoc3.GetCatalog().GetPageTree().GetRoot().GetPdfObject()); pdfDoc3.Close(); PdfReader reader = CompareTool.CreateOutputReader(destinationFolder + "stamping2_2.pdf"); PdfDocument pdfDocument = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); byte[] bytes = pdfDocument.GetPage(1).GetContentBytes(); NUnit.Framework.Assert.AreEqual("%page 1\n", iText.Commons.Utils.JavaUtil.GetStringForBytes(bytes)); bytes = pdfDocument.GetPage(2).GetContentBytes(); @@ -155,13 +154,13 @@ public virtual void Stamping3() { for (int i = 0; i < pdfDoc3.GetNumberOfPages(); i++) { pdfDoc3.GetPage(i + 1); } - NUnit.Framework.Assert.AreEqual(false, reader3.HasRebuiltXref(), "Rebuilt"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasFixedXref(), "Fixed"); + NUnit.Framework.Assert.IsFalse(reader3.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader3.HasFixedXref(), "Fixed"); VerifyPdfPagesCount(pdfDoc3.GetCatalog().GetPageTree().GetRoot().GetPdfObject()); pdfDoc3.Close(); PdfReader reader = CompareTool.CreateOutputReader(filename2); PdfDocument pdfDocument = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); byte[] bytes = pdfDocument.GetPage(1).GetContentBytes(); NUnit.Framework.Assert.AreEqual("%page 1\n", iText.Commons.Utils.JavaUtil.GetStringForBytes(bytes)); bytes = pdfDocument.GetPage(2).GetContentBytes(); @@ -192,13 +191,13 @@ public virtual void Stamping4() { for (int i = 0; i < pdfDoc3.GetNumberOfPages(); i++) { pdfDoc3.GetPage(i + 1); } - NUnit.Framework.Assert.AreEqual(false, reader3.HasRebuiltXref(), "Rebuilt"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasFixedXref(), "Fixed"); + NUnit.Framework.Assert.IsFalse(reader3.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader3.HasFixedXref(), "Fixed"); VerifyPdfPagesCount(pdfDoc3.GetCatalog().GetPageTree().GetRoot().GetPdfObject()); pdfDoc3.Close(); PdfReader reader = CompareTool.CreateOutputReader(filename2); PdfDocument pdfDocument = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); NUnit.Framework.Assert.AreEqual(pageCount, pdfDocument.GetNumberOfPages(), "Page count"); for (int i = 1; i < pdfDocument.GetNumberOfPages(); i++) { byte[] bytes = pdfDocument.GetPage(i).GetContentBytes(); @@ -233,13 +232,13 @@ public virtual void Stamping5() { for (int i = 0; i < pdfDoc3.GetNumberOfPages(); i++) { pdfDoc3.GetPage(i + 1); } - NUnit.Framework.Assert.AreEqual(false, reader3.HasRebuiltXref(), "Rebuilt"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasFixedXref(), "Fixed"); + NUnit.Framework.Assert.IsFalse(reader3.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader3.HasFixedXref(), "Fixed"); VerifyPdfPagesCount(pdfDoc3.GetCatalog().GetPageTree().GetRoot().GetPdfObject()); pdfDoc3.Close(); PdfReader reader = CompareTool.CreateOutputReader(filename2); PdfDocument pdfDocument = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); NUnit.Framework.Assert.AreEqual(pageCount, pdfDocument.GetNumberOfPages(), "Page count"); for (int i = 1; i < pdfDocument.GetNumberOfPages(); i++) { byte[] bytes = pdfDocument.GetPage(i).GetContentBytes(); @@ -270,13 +269,13 @@ public virtual void Stamping6() { for (int i = 0; i < pdfDoc3.GetNumberOfPages(); i++) { pdfDoc3.GetPage(i + 1); } - NUnit.Framework.Assert.AreEqual(false, reader3.HasRebuiltXref(), "Rebuilt"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasFixedXref(), "Fixed"); + NUnit.Framework.Assert.IsFalse(reader3.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader3.HasFixedXref(), "Fixed"); VerifyPdfPagesCount(pdfDoc3.GetCatalog().GetPageTree().GetRoot().GetPdfObject()); pdfDoc3.Close(); PdfReader reader = CompareTool.CreateOutputReader(filename2); PdfDocument pdfDocument = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); byte[] bytes = pdfDocument.GetPage(1).GetContentBytes(); NUnit.Framework.Assert.AreEqual("%page 1\n", iText.Commons.Utils.JavaUtil.GetStringForBytes(bytes)); bytes = pdfDocument.GetPage(2).GetContentBytes(); @@ -306,13 +305,13 @@ public virtual void Stamping7() { for (int i = 0; i < pdfDoc3.GetNumberOfPages(); i++) { pdfDoc3.GetPage(i + 1); } - NUnit.Framework.Assert.AreEqual(false, reader3.HasRebuiltXref(), "Rebuilt"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasFixedXref(), "Fixed"); + NUnit.Framework.Assert.IsFalse(reader3.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader3.HasFixedXref(), "Fixed"); VerifyPdfPagesCount(pdfDoc3.GetCatalog().GetPageTree().GetRoot().GetPdfObject()); pdfDoc3.Close(); PdfReader reader = CompareTool.CreateOutputReader(filename2); PdfDocument pdfDocument = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); byte[] bytes = pdfDocument.GetPage(1).GetContentBytes(); NUnit.Framework.Assert.AreEqual("%page 1\n", iText.Commons.Utils.JavaUtil.GetStringForBytes(bytes)); bytes = pdfDocument.GetPage(2).GetContentBytes(); @@ -345,13 +344,13 @@ public virtual void Stamping8() { pdfDoc3.GetPage(i + 1); } NUnit.Framework.Assert.AreEqual(pageCount, pdfDoc3.GetNumberOfPages(), "Number of pages"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasRebuiltXref(), "Rebuilt"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasFixedXref(), "Fixed"); + NUnit.Framework.Assert.IsFalse(reader3.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader3.HasFixedXref(), "Fixed"); VerifyPdfPagesCount(pdfDoc3.GetCatalog().GetPageTree().GetRoot().GetPdfObject()); pdfDoc3.Close(); PdfReader reader = CompareTool.CreateOutputReader(filename2); PdfDocument pdfDocument = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); for (int i = 1; i <= pageCount; i++) { byte[] bytes = pdfDocument.GetPage(i).GetContentBytes(); NUnit.Framework.Assert.AreEqual("%page " + i + "\n", iText.Commons.Utils.JavaUtil.GetStringForBytes(bytes) @@ -385,13 +384,13 @@ public virtual void Stamping9() { pdfDoc3.GetPage(i + 1); } NUnit.Framework.Assert.AreEqual(pageCount, pdfDoc3.GetNumberOfPages(), "Number of pages"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasRebuiltXref(), "Rebuilt"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasFixedXref(), "Fixed"); + NUnit.Framework.Assert.IsFalse(reader3.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader3.HasFixedXref(), "Fixed"); VerifyPdfPagesCount(pdfDoc3.GetCatalog().GetPageTree().GetRoot().GetPdfObject()); pdfDoc3.Close(); PdfReader reader = CompareTool.CreateOutputReader(filename2); PdfDocument pdfDocument = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); for (int i = 1; i <= pageCount; i++) { byte[] bytes = pdfDocument.GetPage(i).GetContentBytes(); NUnit.Framework.Assert.AreEqual("%page " + i + "\n", iText.Commons.Utils.JavaUtil.GetStringForBytes(bytes) @@ -425,13 +424,13 @@ public virtual void Stamping10() { pdfDoc3.GetPage(i + 1); } NUnit.Framework.Assert.AreEqual(pageCount, pdfDoc3.GetNumberOfPages(), "Number of pages"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasRebuiltXref(), "Rebuilt"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasFixedXref(), "Fixed"); + NUnit.Framework.Assert.IsFalse(reader3.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader3.HasFixedXref(), "Fixed"); VerifyPdfPagesCount(pdfDoc3.GetCatalog().GetPageTree().GetRoot().GetPdfObject()); pdfDoc3.Close(); PdfReader reader = CompareTool.CreateOutputReader(filename2); PdfDocument pdfDocument = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); for (int i = 1; i <= pageCount; i++) { byte[] bytes = pdfDocument.GetPage(i).GetContentBytes(); NUnit.Framework.Assert.AreEqual("%page " + i + "\n", iText.Commons.Utils.JavaUtil.GetStringForBytes(bytes) @@ -465,13 +464,13 @@ public virtual void Stamping11() { pdfDoc3.GetPage(i + 1); } NUnit.Framework.Assert.AreEqual(pageCount, pdfDoc3.GetNumberOfPages(), "Number of pages"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasRebuiltXref(), "Rebuilt"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasFixedXref(), "Fixed"); + NUnit.Framework.Assert.IsFalse(reader3.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader3.HasFixedXref(), "Fixed"); VerifyPdfPagesCount(pdfDoc3.GetCatalog().GetPageTree().GetRoot().GetPdfObject()); pdfDoc3.Close(); PdfReader reader = CompareTool.CreateOutputReader(filename2); PdfDocument pdfDocument = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); for (int i = 1; i <= pageCount; i++) { byte[] bytes = pdfDocument.GetPage(i).GetContentBytes(); NUnit.Framework.Assert.AreEqual("%page " + i + "\n", iText.Commons.Utils.JavaUtil.GetStringForBytes(bytes) @@ -508,13 +507,13 @@ public virtual void Stamping12() { PdfDictionary root = pdfPage.GetPdfObject().GetAsDictionary(PdfName.Parent); NUnit.Framework.Assert.AreEqual(newPageCount, root.GetAsArray(PdfName.Kids).Size(), "PdfPages kids count"); NUnit.Framework.Assert.AreEqual(newPageCount, pdfDoc3.GetNumberOfPages(), "Number of pages"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasRebuiltXref(), "Rebuilt"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasFixedXref(), "Fixed"); + NUnit.Framework.Assert.IsFalse(reader3.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader3.HasFixedXref(), "Fixed"); VerifyPdfPagesCount(pdfDoc3.GetCatalog().GetPageTree().GetRoot().GetPdfObject()); pdfDoc3.Close(); PdfReader reader = CompareTool.CreateOutputReader(filename2); PdfDocument pdfDocument = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); for (int i = 1; i <= pdfDocument.GetNumberOfPages(); i++) { byte[] bytes = pdfDocument.GetPage(i).GetContentBytes(); NUnit.Framework.Assert.AreEqual("%page " + i + "\n", iText.Commons.Utils.JavaUtil.GetStringForBytes(bytes) @@ -555,13 +554,13 @@ public virtual void Stamping13() { PdfArray rootKids = pdfDoc3.GetCatalog().GetPageTree().GetRoot().GetPdfObject().GetAsArray(PdfName.Kids); NUnit.Framework.Assert.AreEqual(2, rootKids.Size(), "Page root kids count"); NUnit.Framework.Assert.AreEqual(pageCount, pdfDoc3.GetNumberOfPages(), "Number of pages"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasRebuiltXref(), "Rebuilt"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasFixedXref(), "Fixed"); + NUnit.Framework.Assert.IsFalse(reader3.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader3.HasFixedXref(), "Fixed"); VerifyPdfPagesCount(pdfDoc3.GetCatalog().GetPageTree().GetRoot().GetPdfObject()); pdfDoc3.Close(); PdfReader reader = CompareTool.CreateOutputReader(filename2); PdfDocument pdfDocument = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); for (int i = 1; i <= pageCount; i++) { byte[] bytes = pdfDocument.GetPage(i).GetContentBytes(); NUnit.Framework.Assert.AreEqual("%page " + i + "\n", iText.Commons.Utils.JavaUtil.GetStringForBytes(bytes) @@ -594,7 +593,7 @@ public virtual void Stamping14() { pdfDoc3.Close(); PdfReader reader = CompareTool.CreateOutputReader(filename2); PdfDocument pdfDocument = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); for (int i = 1; i <= pdfDocument.GetNumberOfPages(); i++) { byte[] bytes = pdfDocument.GetPage(i).GetContentBytes(); NUnit.Framework.Assert.AreEqual("%page " + i + "\n", iText.Commons.Utils.JavaUtil.GetStringForBytes(bytes) @@ -689,16 +688,15 @@ public virtual void StampingXmp1() { for (int i = 0; i < pdfDoc3.GetNumberOfPages(); i++) { pdfDoc3.GetPage(i + 1); } - NUnit.Framework.Assert.IsNotNull(XMPMetaFactory.ParseFromBuffer(pdfDoc3.GetXmpMetadata()), "XmpMetadata not found" - ); + NUnit.Framework.Assert.IsNotNull(pdfDoc3.GetXmpMetadata(), "XmpMetadata not found"); NUnit.Framework.Assert.AreEqual(pageCount, pdfDoc3.GetNumberOfPages(), "Number of pages"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasRebuiltXref(), "Rebuilt"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasFixedXref(), "Fixed"); + NUnit.Framework.Assert.IsFalse(reader3.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader3.HasFixedXref(), "Fixed"); VerifyPdfPagesCount(pdfDoc3.GetCatalog().GetPageTree().GetRoot().GetPdfObject()); pdfDoc3.Close(); PdfReader reader = CompareTool.CreateOutputReader(filename2); PdfDocument pdfDocument = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); for (int i = 1; i <= pageCount; i++) { byte[] bytes = pdfDocument.GetPage(i).GetContentBytes(); NUnit.Framework.Assert.AreEqual("%page " + i + "\n", iText.Commons.Utils.JavaUtil.GetStringForBytes(bytes) @@ -732,16 +730,15 @@ public virtual void StampingXmp2() { for (int i = 0; i < pdfDoc3.GetNumberOfPages(); i++) { pdfDoc3.GetPage(i + 1); } - NUnit.Framework.Assert.IsNotNull(XMPMetaFactory.ParseFromBuffer(pdfDoc3.GetXmpMetadata()), "XmpMetadata not found" - ); + NUnit.Framework.Assert.IsNotNull(pdfDoc3.GetXmpMetadata(), "XmpMetadata not found"); NUnit.Framework.Assert.AreEqual(pageCount, pdfDoc3.GetNumberOfPages(), "Number of pages"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasRebuiltXref(), "Rebuilt"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasFixedXref(), "Fixed"); + NUnit.Framework.Assert.IsFalse(reader3.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader3.HasFixedXref(), "Fixed"); VerifyPdfPagesCount(pdfDoc3.GetCatalog().GetPageTree().GetRoot().GetPdfObject()); pdfDoc3.Close(); PdfReader reader = CompareTool.CreateOutputReader(filename2); PdfDocument pdfDocument = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); for (int i = 1; i <= pageCount; i++) { byte[] bytes = pdfDocument.GetPage(i).GetContentBytes(); NUnit.Framework.Assert.AreEqual("%page " + i + "\n", iText.Commons.Utils.JavaUtil.GetStringForBytes(bytes) @@ -770,13 +767,13 @@ public virtual void StampingAppend1() { for (int i = 0; i < pdfDoc3.GetNumberOfPages(); i++) { pdfDoc3.GetPage(i + 1); } - NUnit.Framework.Assert.AreEqual(false, reader3.HasRebuiltXref(), "Rebuilt"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasFixedXref(), "Fixed"); + NUnit.Framework.Assert.IsFalse(reader3.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader3.HasFixedXref(), "Fixed"); VerifyPdfPagesCount(pdfDoc3.GetCatalog().GetPageTree().GetRoot().GetPdfObject()); pdfDoc3.Close(); PdfReader reader = CompareTool.CreateOutputReader(filename2); PdfDocument pdfDocument = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); PdfDictionary trailer = pdfDocument.GetTrailer(); PdfDictionary info = trailer.GetAsDictionary(PdfName.Info); PdfString creator = info.GetAsString(PdfName.Creator); @@ -812,13 +809,13 @@ public virtual void StampingAppend2() { for (int i = 0; i < pdfDoc3.GetNumberOfPages(); i++) { pdfDoc3.GetPage(i + 1); } - NUnit.Framework.Assert.AreEqual(false, reader3.HasRebuiltXref(), "Rebuilt"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasFixedXref(), "Fixed"); + NUnit.Framework.Assert.IsFalse(reader3.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader3.HasFixedXref(), "Fixed"); VerifyPdfPagesCount(pdfDoc3.GetCatalog().GetPageTree().GetRoot().GetPdfObject()); pdfDoc3.Close(); PdfReader reader = CompareTool.CreateOutputReader(filename2); PdfDocument pdfDocument = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); byte[] bytes = pdfDocument.GetPage(1).GetContentBytes(); NUnit.Framework.Assert.AreEqual("%page 1\n", iText.Commons.Utils.JavaUtil.GetStringForBytes(bytes)); bytes = pdfDocument.GetPage(2).GetContentBytes(); @@ -848,13 +845,13 @@ public virtual void StampingAppend3() { for (int i = 0; i < pdfDoc3.GetNumberOfPages(); i++) { pdfDoc3.GetPage(i + 1); } - NUnit.Framework.Assert.AreEqual(false, reader3.HasRebuiltXref(), "Rebuilt"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasFixedXref(), "Fixed"); + NUnit.Framework.Assert.IsFalse(reader3.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader3.HasFixedXref(), "Fixed"); VerifyPdfPagesCount(pdfDoc3.GetCatalog().GetPageTree().GetRoot().GetPdfObject()); pdfDoc3.Close(); PdfReader reader = CompareTool.CreateOutputReader(filename2); PdfDocument pdfDocument = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); byte[] bytes = pdfDocument.GetPage(1).GetContentBytes(); NUnit.Framework.Assert.AreEqual("%page 1\n", iText.Commons.Utils.JavaUtil.GetStringForBytes(bytes)); bytes = pdfDocument.GetPage(2).GetContentBytes(); @@ -885,13 +882,13 @@ public virtual void StampingAppend4() { for (int i = 0; i < pdfDoc3.GetNumberOfPages(); i++) { pdfDoc3.GetPage(i + 1); } - NUnit.Framework.Assert.AreEqual(false, reader3.HasRebuiltXref(), "Rebuilt"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasFixedXref(), "Fixed"); + NUnit.Framework.Assert.IsFalse(reader3.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader3.HasFixedXref(), "Fixed"); VerifyPdfPagesCount(pdfDoc3.GetCatalog().GetPageTree().GetRoot().GetPdfObject()); pdfDoc3.Close(); PdfReader reader = CompareTool.CreateOutputReader(filename2); PdfDocument pdfDocument = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); NUnit.Framework.Assert.AreEqual(pageCount, pdfDocument.GetNumberOfPages(), "Page count"); for (int i = 1; i < pdfDocument.GetNumberOfPages(); i++) { byte[] bytes = pdfDocument.GetPage(i).GetContentBytes(); @@ -927,13 +924,13 @@ public virtual void StampingAppend5() { for (int i = 0; i < pdfDoc3.GetNumberOfPages(); i++) { pdfDoc3.GetPage(i + 1); } - NUnit.Framework.Assert.AreEqual(false, reader3.HasRebuiltXref(), "Rebuilt"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasFixedXref(), "Fixed"); + NUnit.Framework.Assert.IsFalse(reader3.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader3.HasFixedXref(), "Fixed"); VerifyPdfPagesCount(pdfDoc3.GetCatalog().GetPageTree().GetRoot().GetPdfObject()); pdfDoc3.Close(); PdfReader reader = CompareTool.CreateOutputReader(filename2); PdfDocument pdfDocument = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); NUnit.Framework.Assert.AreEqual(pageCount, pdfDocument.GetNumberOfPages(), "Page count"); for (int i = 1; i < pdfDocument.GetNumberOfPages(); i++) { byte[] bytes = pdfDocument.GetPage(i).GetContentBytes(); @@ -966,13 +963,13 @@ public virtual void StampingAppend8() { pdfDoc3.GetPage(i + 1); } NUnit.Framework.Assert.AreEqual(pageCount, pdfDoc3.GetNumberOfPages(), "Number of pages"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasRebuiltXref(), "Rebuilt"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasFixedXref(), "Fixed"); + NUnit.Framework.Assert.IsFalse(reader3.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader3.HasFixedXref(), "Fixed"); VerifyPdfPagesCount(pdfDoc3.GetCatalog().GetPageTree().GetRoot().GetPdfObject()); pdfDoc3.Close(); PdfReader reader = CompareTool.CreateOutputReader(filename2); PdfDocument pdfDocument = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); for (int i = 1; i <= pageCount; i++) { byte[] bytes = pdfDocument.GetPage(i).GetContentBytes(); NUnit.Framework.Assert.AreEqual("%page " + i + "\n", iText.Commons.Utils.JavaUtil.GetStringForBytes(bytes) @@ -1007,13 +1004,13 @@ public virtual void StampingAppend9() { pdfDoc3.GetPage(i + 1); } NUnit.Framework.Assert.AreEqual(pageCount, pdfDoc3.GetNumberOfPages(), "Number of pages"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasRebuiltXref(), "Rebuilt"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasFixedXref(), "Fixed"); + NUnit.Framework.Assert.IsFalse(reader3.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader3.HasFixedXref(), "Fixed"); VerifyPdfPagesCount(pdfDoc3.GetCatalog().GetPageTree().GetRoot().GetPdfObject()); pdfDoc3.Close(); PdfReader reader = CompareTool.CreateOutputReader(filename2); PdfDocument pdfDocument = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); for (int i = 1; i <= pageCount; i++) { byte[] bytes = pdfDocument.GetPage(i).GetContentBytes(); NUnit.Framework.Assert.AreEqual("%page " + i + "\n", iText.Commons.Utils.JavaUtil.GetStringForBytes(bytes) @@ -1048,13 +1045,13 @@ public virtual void StampingAppend10() { pdfDoc3.GetPage(i + 1); } NUnit.Framework.Assert.AreEqual(pageCount, pdfDoc3.GetNumberOfPages(), "Number of pages"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasRebuiltXref(), "Rebuilt"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasFixedXref(), "Fixed"); + NUnit.Framework.Assert.IsFalse(reader3.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader3.HasFixedXref(), "Fixed"); VerifyPdfPagesCount(pdfDoc3.GetCatalog().GetPageTree().GetRoot().GetPdfObject()); pdfDoc3.Close(); PdfReader reader = CompareTool.CreateOutputReader(filename2); PdfDocument pdfDocument = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); for (int i = 1; i <= pageCount; i++) { byte[] bytes = pdfDocument.GetPage(i).GetContentBytes(); NUnit.Framework.Assert.AreEqual("%page " + i + "\n", iText.Commons.Utils.JavaUtil.GetStringForBytes(bytes) @@ -1088,13 +1085,13 @@ public virtual void StampingAppend11() { pdfDoc3.GetPage(i + 1); } NUnit.Framework.Assert.AreEqual(pageCount, pdfDoc3.GetNumberOfPages(), "Number of pages"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasRebuiltXref(), "Rebuilt"); - NUnit.Framework.Assert.AreEqual(false, reader3.HasFixedXref(), "Fixed"); + NUnit.Framework.Assert.IsFalse(reader3.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader3.HasFixedXref(), "Fixed"); VerifyPdfPagesCount(pdfDoc3.GetCatalog().GetPageTree().GetRoot().GetPdfObject()); pdfDoc3.Close(); PdfReader reader = CompareTool.CreateOutputReader(filename2); PdfDocument pdfDocument = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); for (int i = 1; i <= pageCount; i++) { byte[] bytes = pdfDocument.GetPage(i).GetContentBytes(); NUnit.Framework.Assert.AreEqual("%page " + i + "\n", iText.Commons.Utils.JavaUtil.GetStringForBytes(bytes) @@ -1242,8 +1239,8 @@ internal static void VerifyPdfPagesCount(PdfObject root) { //\endcond //\cond DO_NOT_DOCUMENT - internal class WatermarkEventHandler : iText.Kernel.Events.IEventHandler { - public virtual void HandleEvent(Event @event) { + internal class WatermarkEventHandler : AbstractPdfDocumentEventHandler { + protected internal override void OnAcceptedEvent(AbstractPdfDocumentEvent @event) { PdfDocumentEvent pdfEvent = (PdfDocumentEvent)@event; PdfPage page = pdfEvent.GetPage(); PdfCanvas pdfCanvas = new PdfCanvas(page); diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfTokenizerTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfTokenizerTest.cs index e0a2d47ab2..2d79494145 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfTokenizerTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfTokenizerTest.cs @@ -79,7 +79,7 @@ public virtual void EncodingTest() { } [NUnit.Framework.Test] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] public virtual void ReadPdfStringTest() { String author = "This string9078 contains \u00A5two octal characters\u00C7"; String creator = "iText\r 6\n"; diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfType0FontIntegrationTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfType0FontIntegrationTest.cs index 76dc82b9e6..bd42d0c9ec 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfType0FontIntegrationTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfType0FontIntegrationTest.cs @@ -112,5 +112,41 @@ public virtual void NotoSansTcFontTest() { NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpFilename, DESTINATION_FOLDER )); } + + [NUnit.Framework.Test] + public virtual void CmapPlatform0PlatEnc3Format4FontTest() { + String filename = DESTINATION_FOLDER + "cmapPlatform0PlatEnc3Format4FontTest.pdf"; + String cmpFilename = SOURCE_FOLDER + "cmp_cmapPlatform0PlatEnc3Format4FontTest.pdf"; + PdfWriter writer = CompareTool.CreateTestPdfWriter(filename); + writer.SetCompressionLevel(CompressionConstants.NO_COMPRESSION); + PdfDocument pdfDoc = new PdfDocument(writer); + PdfFont font = PdfFontFactory.CreateFont(FONTS_FOLDER + "glyphs.ttf"); + PdfCanvas canvas = new PdfCanvas(pdfDoc.AddNewPage()); + canvas.SaveState().BeginText().SetFontAndSize(font, 20).MoveText(36, 700).ShowText("===fff===iii===fi").EndText + ().RestoreState(); + canvas.Rectangle(100, 500, 100, 100).Fill(); + canvas.Release(); + pdfDoc.Close(); + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpFilename, DESTINATION_FOLDER + )); + } + + [NUnit.Framework.Test] + public virtual void CmapPlatform0PlatEnc3Format6FontTest() { + String filename = DESTINATION_FOLDER + "cmapPlatform0PlatEnc3Format6FontTest.pdf"; + String cmpFilename = SOURCE_FOLDER + "cmp_cmapPlatform0PlatEnc3Format6FontTest.pdf"; + PdfWriter writer = CompareTool.CreateTestPdfWriter(filename); + writer.SetCompressionLevel(CompressionConstants.NO_COMPRESSION); + PdfDocument pdfDoc = new PdfDocument(writer); + PdfFont font = PdfFontFactory.CreateFont(FONTS_FOLDER + "glyphs-fmt-6.ttf"); + PdfCanvas canvas = new PdfCanvas(pdfDoc.AddNewPage()); + canvas.SaveState().BeginText().SetFontAndSize(font, 20).MoveText(36, 700).ShowText("===fff===iii===").EndText + ().RestoreState(); + canvas.Rectangle(100, 500, 100, 100).Fill(); + canvas.Release(); + pdfDoc.Close(); + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpFilename, DESTINATION_FOLDER + )); + } } } diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfWriterTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfWriterTest.cs index f6091f9d61..e17a811f67 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfWriterTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfWriterTest.cs @@ -530,13 +530,13 @@ public virtual void CreatePdfStreamByInputStream() { int streamIndirectNumber = stream.GetIndirectReference().GetObjNumber(); document.Close(); // com.itextpdf.text.pdf.PdfReader reader = new PdfReader(filename); - // Assert.assertEquals("Rebuilt", false, reader.isRebuilt()); - // Assert.assertNotNull(reader.getPageN(1)); + // Assertions.assertEquals("Rebuilt", false, reader.isRebuilt()); + // Assertions.assertNotNull(reader.getPageN(1)); // String date = reader.getDocumentInfo().get("CreationDate"); // Calendar cl = com.itextpdf.text.pdf.PdfDate.decode(date); // long diff = new GregorianCalendar().getTimeInMillis() - cl.getTimeInMillis(); // String message = "Unexpected creation date. Different from now is " + (float)diff/1000 + "s"; - // Assert.assertTrue(message, diff < 5000); + // Assertions.assertTrue(diff < 5000, message); // reader.close(); PdfReader reader6 = CompareTool.CreateOutputReader(filename); document = new PdfDocument(reader6); diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfXrefTableTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfXrefTableTest.cs index 03bd5d6681..f3b6bb7619 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfXrefTableTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/PdfXrefTableTest.cs @@ -48,17 +48,17 @@ public static void AfterClass() { } [NUnit.Framework.Test] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT, LogLevel = - LogLevelConstants.ERROR)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE, + LogLevel = LogLevelConstants.ERROR)] public virtual void OpenInvalidDocWithHugeRefTest() { String inputFile = SOURCE_FOLDER + "invalidDocWithHugeRef.pdf"; - MemoryLimitsAwareHandler memoryLimitsAwareHandler = new _MemoryLimitsAwareHandler_67(); + MemoryLimitsAwareHandler memoryLimitsAwareHandler = new _MemoryLimitsAwareHandler_68(); NUnit.Framework.Assert.DoesNotThrow(() => new PdfDocument(new PdfReader(inputFile, new ReaderProperties(). SetMemoryLimitsAwareHandler(memoryLimitsAwareHandler)))); } - private sealed class _MemoryLimitsAwareHandler_67 : MemoryLimitsAwareHandler { - public _MemoryLimitsAwareHandler_67() { + private sealed class _MemoryLimitsAwareHandler_68 : MemoryLimitsAwareHandler { + public _MemoryLimitsAwareHandler_68() { } public override void CheckIfXrefStructureExceedsTheLimit(int requestedCapacity) { @@ -66,8 +66,8 @@ public override void CheckIfXrefStructureExceedsTheLimit(int requestedCapacity) } [NUnit.Framework.Test] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT, LogLevel = - LogLevelConstants.ERROR)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE, + LogLevel = LogLevelConstants.ERROR)] public virtual void OpenInvalidDocWithHugeRefTestDefaultMemoryLimitAwareHandler() { String inputFile = SOURCE_FOLDER + "invalidDocWithHugeRef.pdf"; NUnit.Framework.Assert.Catch(typeof(MemoryLimitsAwareException), () => new PdfDocument(new PdfReader(inputFile @@ -75,8 +75,8 @@ public virtual void OpenInvalidDocWithHugeRefTestDefaultMemoryLimitAwareHandler( } [NUnit.Framework.Test] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT, LogLevel = - LogLevelConstants.ERROR)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE, + LogLevel = LogLevelConstants.ERROR)] public virtual void OpenWithWriterInvalidDocWithHugeRefTest() { String inputFile = SOURCE_FOLDER + "invalidDocWithHugeRef.pdf"; MemoryStream outputStream = new ByteArrayOutputStream(); diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/ReaderPropertiesTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/ReaderPropertiesTest.cs new file mode 100644 index 0000000000..e0be025dee --- /dev/null +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/ReaderPropertiesTest.cs @@ -0,0 +1,42 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Test; + +namespace iText.Kernel.Pdf { + [NUnit.Framework.Category("UnitTest")] + public class ReaderPropertiesTest : ExtendedITextTest { + [NUnit.Framework.Test] + public virtual void CopyConstructorTest() { + MemoryLimitsAwareHandler handler = new MemoryLimitsAwareHandler(); + handler.SetMaxXObjectsSizePerPage(10); + ReaderProperties properties = new ReaderProperties().SetPassword("123".GetBytes(iText.Commons.Utils.EncodingUtil.ISO_8859_1 + )).SetMemoryLimitsAwareHandler(handler); + ReaderProperties copy = new ReaderProperties(properties); + NUnit.Framework.Assert.AreEqual(copy.password, properties.password); + NUnit.Framework.Assert.AreNotEqual(copy.memoryLimitsAwareHandler, properties.memoryLimitsAwareHandler); + NUnit.Framework.Assert.AreEqual(copy.memoryLimitsAwareHandler.GetMaxXObjectsSizePerPage(), properties.memoryLimitsAwareHandler + .GetMaxXObjectsSizePerPage()); + NUnit.Framework.Assert.AreEqual(10, copy.memoryLimitsAwareHandler.GetMaxXObjectsSizePerPage()); + } + } +} diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/TrailerTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/TrailerTest.cs index 6eefd9a09e..c122a28648 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/TrailerTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/TrailerTest.cs @@ -27,8 +27,10 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Utils; using iText.Kernel.Actions.Data; using iText.Kernel.Font; +using iText.Kernel.Logs; using iText.Kernel.Pdf.Canvas; using iText.Test; +using iText.Test.Attributes; namespace iText.Kernel.Pdf { [NUnit.Framework.Category("IntegrationTest")] @@ -137,6 +139,35 @@ public virtual void ExistingTrailerValuesWithStandardizedNameTest() { } } + [NUnit.Framework.Test] + public virtual void EnableFingerprintInAGPLModeTest() { + PdfDocument pdf = new PdfDocument(new PdfWriter(destinationFolder + "enableFingerprintInAGPLMode.pdf")); + pdf.RegisterProduct(this.productData); + PdfPage page = pdf.AddNewPage(); + PdfCanvas canvas = new PdfCanvas(page); + canvas.BeginText().SetFontAndSize(PdfFontFactory.CreateFont(), 12f).ShowText("Hello World").EndText(); + pdf.Close(); + NUnit.Framework.Assert.IsTrue(DoesTrailerContainFingerprint(new FileInfo(destinationFolder + "enableFingerprintInAGPLMode.pdf" + ), MessageFormatUtil.Format("%iText-{0}-{1}\n", productData.GetProductName(), productData.GetVersion() + ))); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.FINGERPRINT_DISABLED_BUT_NO_REQUIRED_LICENCE)] + public virtual void TryDisablingFingerprintInAGPLModeTest() { + PdfDocument pdf = new PdfDocument(new PdfWriter(destinationFolder + "tryDisablingFingerprintInAGPLMode.pdf" + )); + pdf.RegisterProduct(this.productData); + PdfPage page = pdf.AddNewPage(); + PdfCanvas canvas = new PdfCanvas(page); + canvas.BeginText().SetFontAndSize(PdfFontFactory.CreateFont(), 12f).ShowText("Hello World").EndText(); + pdf.GetFingerPrint().DisableFingerPrint(); + pdf.Close(); + NUnit.Framework.Assert.IsTrue(DoesTrailerContainFingerprint(new FileInfo(destinationFolder + "tryDisablingFingerprintInAGPLMode.pdf" + ), MessageFormatUtil.Format("%iText-{0}-{1}\n", productData.GetProductName(), productData.GetVersion() + ))); + } + private bool DoesTrailerContainFingerprint(FileInfo file, String fingerPrint) { using (FileStream raf = FileUtil.GetRandomAccessFile(file)) { // put the pointer at the end of the file @@ -145,6 +176,9 @@ private bool DoesTrailerContainFingerprint(FileInfo file, String fingerPrint) { String coreProductData = "%iText-Core-" + ITextCoreProductData.GetInstance().GetVersion(); String templine = ""; while (!templine.Contains(coreProductData)) { + if (raf.Position <= 2) { + return false; + } templine = (char)raf.ReadByte() + templine; raf.Seek(raf.Position - 2); } @@ -152,6 +186,9 @@ private bool DoesTrailerContainFingerprint(FileInfo file, String fingerPrint) { char read = ' '; templine = ""; while (read != '%') { + if (raf.Position <= 2) { + return false; + } read = (char)raf.ReadByte(); templine = read + templine; raf.Seek(raf.Position - 2); diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/XMPMetadataTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/XMPMetadataTest.cs index 6789b0a23c..61b85a8634 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/XMPMetadataTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/XMPMetadataTest.cs @@ -31,26 +31,26 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Kernel.Pdf { [NUnit.Framework.Category("IntegrationTest")] public class XMPMetadataTest : ExtendedITextTest { - public static readonly String sourceFolder = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + public static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext .CurrentContext.TestDirectory) + "/resources/itext/kernel/pdf/XmpWriterTest/"; - public static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory + public static readonly String DESTINATION_FOLDER = NUnit.Framework.TestContext.CurrentContext.TestDirectory + "/test/itext/kernel/pdf/XmpWriterTest/"; [NUnit.Framework.OneTimeSetUp] public static void BeforeClass() { - CreateOrClearDestinationFolder(destinationFolder); + CreateOrClearDestinationFolder(DESTINATION_FOLDER); } [NUnit.Framework.OneTimeTearDown] public static void AfterClass() { - CompareTool.Cleanup(destinationFolder); + CompareTool.Cleanup(DESTINATION_FOLDER); } [NUnit.Framework.Test] public virtual void CreateEmptyDocumentWithXmp() { String filename = "emptyDocumentWithXmp.pdf"; - PdfWriter writer = CompareTool.CreateTestPdfWriter(destinationFolder + filename, new WriterProperties().AddXmpMetadata + PdfWriter writer = CompareTool.CreateTestPdfWriter(DESTINATION_FOLDER + filename, new WriterProperties().AddXmpMetadata ()); PdfDocument pdfDoc = new PdfDocument(writer); pdfDoc.GetDocumentInfo().SetAuthor("Alexander Chingarev").SetCreator("iText").SetTitle("Empty iText Document" @@ -60,12 +60,12 @@ public virtual void CreateEmptyDocumentWithXmp() { PdfPage page = pdfDoc.AddNewPage(); page.Flush(); pdfDoc.Close(); - PdfReader reader = CompareTool.CreateOutputReader(destinationFolder + filename); + PdfReader reader = CompareTool.CreateOutputReader(DESTINATION_FOLDER + filename); PdfDocument pdfDocument = new PdfDocument(reader); NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); - byte[] outBytes = pdfDocument.GetXmpMetadata(); + byte[] outBytes = pdfDocument.GetXmpMetadataBytes(); pdfDocument.Close(); - byte[] cmpBytes = ReadFile(sourceFolder + "emptyDocumentWithXmp.xml"); + byte[] cmpBytes = ReadFile(SOURCE_FOLDER + "emptyDocumentWithXmp.xml"); cmpBytes = RemoveAlwaysDifferentEntries(cmpBytes); outBytes = RemoveAlwaysDifferentEntries(outBytes); NUnit.Framework.Assert.IsTrue(new CompareTool().CompareXmls(outBytes, cmpBytes)); @@ -73,9 +73,9 @@ public virtual void CreateEmptyDocumentWithXmp() { [NUnit.Framework.Test] public virtual void EmptyDocumentWithXmpAppendMode01() { - String created = destinationFolder + "emptyDocumentWithXmpAppendMode01.pdf"; - String updated = destinationFolder + "emptyDocumentWithXmpAppendMode01_updated.pdf"; - String updatedAgain = destinationFolder + "emptyDocumentWithXmpAppendMode01_updatedAgain.pdf"; + String created = DESTINATION_FOLDER + "emptyDocumentWithXmpAppendMode01.pdf"; + String updated = DESTINATION_FOLDER + "emptyDocumentWithXmpAppendMode01_updated.pdf"; + String updatedAgain = DESTINATION_FOLDER + "emptyDocumentWithXmpAppendMode01_updatedAgain.pdf"; PdfDocument pdfDocument = new PdfDocument(CompareTool.CreateTestPdfWriter(created)); pdfDocument.AddNewPage(); // create XMP metadata @@ -95,9 +95,9 @@ public virtual void EmptyDocumentWithXmpAppendMode01() { (); NUnit.Framework.Assert.AreEqual(6, metadataRef.GetObjNumber()); NUnit.Framework.Assert.AreEqual(0, metadataRef.GetGenNumber()); - byte[] outBytes = pdfDocument.GetXmpMetadata(); + byte[] outBytes = pdfDocument.GetXmpMetadataBytes(); pdfDocument.Close(); - byte[] cmpBytes = ReadFile(sourceFolder + "emptyDocumentWithXmpAppendMode01.xml"); + byte[] cmpBytes = ReadFile(SOURCE_FOLDER + "emptyDocumentWithXmpAppendMode01.xml"); cmpBytes = RemoveAlwaysDifferentEntries(cmpBytes); outBytes = RemoveAlwaysDifferentEntries(outBytes); NUnit.Framework.Assert.IsTrue(new CompareTool().CompareXmls(outBytes, cmpBytes)); @@ -105,9 +105,9 @@ public virtual void EmptyDocumentWithXmpAppendMode01() { [NUnit.Framework.Test] public virtual void EmptyDocumentWithXmpAppendMode02() { - String created = destinationFolder + "emptyDocumentWithXmpAppendMode02.pdf"; - String updated = destinationFolder + "emptyDocumentWithXmpAppendMode02_updated.pdf"; - String updatedAgain = destinationFolder + "emptyDocumentWithXmpAppendMode02_updatedAgain.pdf"; + String created = DESTINATION_FOLDER + "emptyDocumentWithXmpAppendMode02.pdf"; + String updated = DESTINATION_FOLDER + "emptyDocumentWithXmpAppendMode02_updated.pdf"; + String updatedAgain = DESTINATION_FOLDER + "emptyDocumentWithXmpAppendMode02_updatedAgain.pdf"; PdfDocument pdfDocument = new PdfDocument(CompareTool.CreateTestPdfWriter(created)); pdfDocument.AddNewPage(); pdfDocument.Close(); @@ -127,16 +127,16 @@ public virtual void EmptyDocumentWithXmpAppendMode02() { (); NUnit.Framework.Assert.AreEqual(6, metadataRef.GetObjNumber()); NUnit.Framework.Assert.AreEqual(0, metadataRef.GetGenNumber()); - byte[] outBytes = pdfDocument.GetXmpMetadata(); + byte[] outBytes = pdfDocument.GetXmpMetadataBytes(); pdfDocument.Close(); - byte[] cmpBytes = ReadFile(sourceFolder + "emptyDocumentWithXmpAppendMode02.xml"); + byte[] cmpBytes = ReadFile(SOURCE_FOLDER + "emptyDocumentWithXmpAppendMode02.xml"); cmpBytes = RemoveAlwaysDifferentEntries(cmpBytes); outBytes = RemoveAlwaysDifferentEntries(outBytes); NUnit.Framework.Assert.IsTrue(new CompareTool().CompareXmls(outBytes, cmpBytes)); } [NUnit.Framework.Test] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.EXCEPTION_WHILE_UPDATING_XMPMETADATA)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.EXCEPTION_WHILE_UPDATING_XMPMETADATA, Count = 2)] public virtual void CreateEmptyDocumentWithAbcXmp() { MemoryStream fos = new MemoryStream(); PdfWriter writer = new PdfWriter(fos); @@ -151,8 +151,8 @@ public virtual void CreateEmptyDocumentWithAbcXmp() { pdfDoc.Close(); PdfReader reader = new PdfReader(new MemoryStream(fos.ToArray())); PdfDocument pdfDocument = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); - NUnit.Framework.Assert.AreEqual("abc".GetBytes(iText.Commons.Utils.EncodingUtil.ISO_8859_1), pdfDocument.GetXmpMetadata + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.AreEqual("abc".GetBytes(iText.Commons.Utils.EncodingUtil.ISO_8859_1), pdfDocument.GetXmpMetadataBytes ()); NUnit.Framework.Assert.IsNotNull(pdfDocument.GetPage(1)); reader.Close(); @@ -181,16 +181,16 @@ public virtual void CustomXmpTest02() { } private void RunCustomXmpTest(String name, String xmp) { - String outPath = destinationFolder + name + ".pdf"; - String cmpPath = sourceFolder + "cmp_" + name + ".pdf"; + String outPath = DESTINATION_FOLDER + name + ".pdf"; + String cmpPath = SOURCE_FOLDER + "cmp_" + name + ".pdf"; PdfDocument pdfDoc = new PdfDocument(CompareTool.CreateTestPdfWriter(outPath)); PdfPage page = pdfDoc.AddNewPage(); page.Flush(); pdfDoc.SetXmpMetadata(xmp.GetBytes(iText.Commons.Utils.EncodingUtil.ISO_8859_1)); pdfDoc.Close(); CompareTool compareTool = new CompareTool(); - NUnit.Framework.Assert.IsNull(compareTool.CompareByContent(outPath, cmpPath, destinationFolder, "diff_" + - name + "_")); + NUnit.Framework.Assert.IsNull(compareTool.CompareByContent(outPath, cmpPath, DESTINATION_FOLDER, "diff_" + + name + "_")); NUnit.Framework.Assert.IsNull(compareTool.CompareDocumentInfo(outPath, cmpPath)); } diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/PdfCanvasColorTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/PdfCanvasColorTest.cs index 12a466409f..b0950e1d10 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/PdfCanvasColorTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/PdfCanvasColorTest.cs @@ -29,6 +29,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Kernel.Font; using iText.Kernel.Pdf; using iText.Kernel.Pdf.Colorspace; +using iText.Kernel.Pdf.Colorspace.Shading; using iText.Kernel.Pdf.Function; using iText.Kernel.Utils; using iText.Test; @@ -332,8 +333,8 @@ public virtual void PatternColorColoredAxialPatternTest() { PdfDocument document = new PdfDocument(writer); PdfPage page = document.AddNewPage(); PdfCanvas canvas = new PdfCanvas(page); - PdfShading axial = new PdfShading.Axial(new PdfDeviceCs.Rgb(), 36, 716, new float[] { 1, .784f, 0 }, 396, - 788, new float[] { 0, 0, 1 }, new bool[] { true, true }); + AbstractPdfShading axial = new PdfAxialShading(new PdfDeviceCs.Rgb(), 36, 716, new float[] { 1, .784f, 0 } + , 396, 788, new float[] { 0, 0, 1 }, new bool[] { true, true }); canvas.SetFillColor(new PatternColor(new PdfPattern.Shading(axial))); canvas.Rectangle(30, 300, 400, 400).Fill(); canvas.Release(); @@ -350,8 +351,8 @@ public virtual void PatternColorColoredRadialPatternTest() { PdfDocument document = new PdfDocument(writer); PdfPage page = document.AddNewPage(); PdfCanvas canvas = new PdfCanvas(page); - PdfShading radial = new PdfShading.Radial(new PdfDeviceCs.Rgb(), 200, 700, 50, new float[] { 1, 0.968f, 0.58f - }, 300, 700, 100, new float[] { 0.968f, 0.541f, 0.42f }); + AbstractPdfShading radial = new PdfRadialShading(new PdfDeviceCs.Rgb(), 200, 700, 50, new float[] { 1, 0.968f + , 0.58f }, 300, 700, 100, new float[] { 0.968f, 0.541f, 0.42f }); canvas.SetFillColor(new PatternColor(new PdfPattern.Shading(radial))); canvas.Rectangle(30, 300, 400, 400).Fill(); canvas.Release(); @@ -500,10 +501,10 @@ private void SetColorSameColorSpacesTest(String pdfName, bool pattern) { ); float[] colorValue1 = pattern ? null : new float[] { 1.0f, 0.6f, 0.7f }; float[] colorValue2 = pattern ? null : new float[] { 0.1f, 0.9f, 0.9f }; - PdfPattern pattern1 = pattern ? new PdfPattern.Shading(new PdfShading.Axial(new PdfDeviceCs.Rgb(), 45, 750 - , ColorConstants.PINK.GetColorValue(), 100, 760, ColorConstants.MAGENTA.GetColorValue())) : null; - PdfPattern pattern2 = pattern ? new PdfPattern.Shading(new PdfShading.Axial(new PdfDeviceCs.Rgb(), 45, 690 - , ColorConstants.BLUE.GetColorValue(), 100, 710, ColorConstants.CYAN.GetColorValue())) : null; + PdfPattern pattern1 = pattern ? new PdfPattern.Shading(new PdfAxialShading(new PdfDeviceCs.Rgb(), 45, 750, + ColorConstants.PINK.GetColorValue(), 100, 760, ColorConstants.MAGENTA.GetColorValue())) : null; + PdfPattern pattern2 = pattern ? new PdfPattern.Shading(new PdfAxialShading(new PdfDeviceCs.Rgb(), 45, 690, + ColorConstants.BLUE.GetColorValue(), 100, 710, ColorConstants.CYAN.GetColorValue())) : null; canvas.SetColor(space, colorValue1, pattern1, true); canvas.SaveState(); canvas.BeginText().MoveText(50, 750).SetFontAndSize(PdfFontFactory.CreateFont(), 16).ShowText("pinkish").EndText diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/PdfCanvasInlineImagesTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/PdfCanvasInlineImagesTest.cs index 464d0daa72..cf938b4852 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/PdfCanvasInlineImagesTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/PdfCanvasInlineImagesTest.cs @@ -145,7 +145,6 @@ public virtual void InlineImagesTest03() { [NUnit.Framework.Test] public virtual void InlineImagesPngTest() { - //TODO update cmp-files after DEVSIX-3564 will be fixed String filename = "inlineImagePng.pdf"; PdfDocument document = new PdfDocument(CompareTool.CreateTestPdfWriter(destinationFolder + filename)); PdfPage page = document.AddNewPage(); @@ -159,7 +158,6 @@ public virtual void InlineImagesPngTest() { [NUnit.Framework.Test] public virtual void InlineImagesPngErrorWhileOpenTest() { - //TODO update cmp-files after DEVSIX-3564 will be fixed String filename = "inlineImagePngErrorWhileOpen.pdf"; PdfDocument document = new PdfDocument(CompareTool.CreateTestPdfWriter(destinationFolder + filename)); PdfPage page = document.AddNewPage(); diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/PdfCanvasTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/PdfCanvasTest.cs index b854a92231..0c29fa788a 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/PdfCanvasTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/PdfCanvasTest.cs @@ -24,7 +24,9 @@ You should have received a copy of the GNU Affero General Public License using System.Collections.Generic; using System.IO; using iText.Commons.Utils; +using iText.IO.Font; using iText.IO.Font.Constants; +using iText.IO.Font.Otf; using iText.IO.Image; using iText.IO.Source; using iText.IO.Util; @@ -51,14 +53,17 @@ public class PdfCanvasTest : ExtendedITextTest { private static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext .CurrentContext.TestDirectory) + "/resources/itext/kernel/pdf/canvas/PdfCanvasTest/"; + private static readonly String FONTS_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + .CurrentContext.TestDirectory) + "/resources/itext/kernel/pdf/fonts/"; + private const String AUTHOR = "iText Software"; private const String CREATOR = "iText"; private const String TITLE = "Empty iText Document"; - private sealed class _ContentProvider_78 : PdfCanvasTest.ContentProvider { - public _ContentProvider_78() { + private sealed class _ContentProvider_86 : PdfCanvasTest.ContentProvider { + public _ContentProvider_86() { } public void DrawOnCanvas(PdfCanvas canvas, int pageNumber) { @@ -68,7 +73,7 @@ public void DrawOnCanvas(PdfCanvas canvas, int pageNumber) { } } - private static readonly PdfCanvasTest.ContentProvider DEFAULT_CONTENT_PROVIDER = new _ContentProvider_78(); + private static readonly PdfCanvasTest.ContentProvider DEFAULT_CONTENT_PROVIDER = new _ContentProvider_86(); [NUnit.Framework.OneTimeSetUp] public static void BeforeClass() { @@ -242,12 +247,12 @@ public virtual void Create1000PagesDocumentWithText() { int pageCount = 1000; String filename = DESTINATION_FOLDER + "1000PagesDocumentWithText.pdf"; PdfWriter writer = CompareTool.CreateTestPdfWriter(filename); - CreateStandardDocument(writer, pageCount, new _ContentProvider_379()); + CreateStandardDocument(writer, pageCount, new _ContentProvider_387()); AssertStandardDocument(filename, pageCount); } - private sealed class _ContentProvider_379 : PdfCanvasTest.ContentProvider { - public _ContentProvider_379() { + private sealed class _ContentProvider_387 : PdfCanvasTest.ContentProvider { + public _ContentProvider_387() { } public void DrawOnCanvas(PdfCanvas canvas, int pageNumber) { @@ -860,7 +865,7 @@ public virtual void CanvasInitializationStampingExistingStream() { [NUnit.Framework.Test] public virtual void CanvasStreamFlushedNoException() { PdfDocument doc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream())); - PdfStream stream = new _PdfStream_1113(); + PdfStream stream = new _PdfStream_1121(); stream.Put(PdfName.Filter, new PdfName("FlateDecode")); NUnit.Framework.Assert.DoesNotThrow(() => { new PdfCanvas(stream, new PdfResources(), doc); @@ -868,8 +873,8 @@ public virtual void CanvasStreamFlushedNoException() { ); } - private sealed class _PdfStream_1113 : PdfStream { - public _PdfStream_1113() { + private sealed class _PdfStream_1121 : PdfStream { + public _PdfStream_1121() { this.isFlushed = false; } @@ -889,7 +894,7 @@ public override bool IsFlushed() { public virtual void CanvasInitializationStampingExistingStreamMemoryLimitAware() { String srcFile = SOURCE_FOLDER + "pageWithContent.pdf"; ReaderProperties properties = new ReaderProperties(); - MemoryLimitsAwareHandler handler = new _MemoryLimitsAwareHandler_1136(); + MemoryLimitsAwareHandler handler = new _MemoryLimitsAwareHandler_1144(); handler.SetMaxSizeOfSingleDecompressedPdfStream(1); properties.SetMemoryLimitsAwareHandler(handler); PdfDocument document = new PdfDocument(new PdfReader(srcFile, properties)); @@ -900,8 +905,8 @@ public virtual void CanvasInitializationStampingExistingStreamMemoryLimitAware() ); } - private sealed class _MemoryLimitsAwareHandler_1136 : MemoryLimitsAwareHandler { - public _MemoryLimitsAwareHandler_1136() { + private sealed class _MemoryLimitsAwareHandler_1144 : MemoryLimitsAwareHandler { + public _MemoryLimitsAwareHandler_1144() { } public override bool IsMemoryLimitsAwarenessRequiredOnDecompression(PdfArray filters) { @@ -1212,6 +1217,84 @@ public virtual void CreateSimpleCanvasWithPdfArrayText() { )); } + [NUnit.Framework.Test] + public virtual void IgnorePageRotationForContentTest() { + String outPdf = DESTINATION_FOLDER + "ignorePageRotationForContent.pdf"; + String cmpPdf = SOURCE_FOLDER + "cmp_ignorePageRotationForContent.pdf"; + using (PdfDocument pdfDoc = new PdfDocument(CompareTool.CreateTestPdfWriter(outPdf))) { + pdfDoc.GetDocumentInfo().SetAuthor(AUTHOR).SetCreator(CREATOR).SetTitle(TITLE); + PdfPage page = pdfDoc.AddNewPage().SetRotation(270); + // When "true": in case the page has a rotation, then new content will be automatically rotated in the + // opposite direction. On the rotated page this would look as if new content ignores page rotation. + page.SetIgnorePageRotationForContent(true); + PdfCanvas canvas = new PdfCanvas(page, false); + canvas.SaveState().BeginText().MoveText(180, 350).SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.HELVETICA + ), 30).ShowText("Page rotation is set to 270 degrees,").EndText().RestoreState(); + PdfCanvas canvas2 = new PdfCanvas(page, false); + canvas2.SaveState().BeginText().MoveText(180, 250).SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts. + HELVETICA), 30).ShowText("but new content ignores page rotation").EndText().RestoreState(); + page.Flush(); + } + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, DESTINATION_FOLDER, "diff_" + )); + } + + [NUnit.Framework.Test] + public virtual void GetResourcesTest() { + String outPdf = DESTINATION_FOLDER + "getResourcesDoc.pdf"; + PdfDocument pdfDoc = new PdfDocument(CompareTool.CreateTestPdfWriter(outPdf)); + PdfPage page1 = pdfDoc.AddNewPage(); + PdfCanvas canvas = new PdfCanvas(page1); + canvas.SaveState().BeginText().MoveText(150, 400).SetFontAndSize(PdfFontFactory.CreateFont(), 8).ShowText( + "test text").EndText().RestoreState(); + PdfResources resources = canvas.GetResources(); + pdfDoc.Close(); + NUnit.Framework.Assert.AreEqual(1, resources.GetResourceNames().Count); + } + + [NUnit.Framework.Test] + public virtual void AttachContentStreamTest() { + String outPdf = DESTINATION_FOLDER + "attachContentStreamDoc.pdf"; + PdfDocument pdfDoc = new PdfDocument(CompareTool.CreateTestPdfWriter(outPdf)); + PdfPage page1 = pdfDoc.AddNewPage(); + PdfCanvas canvas = new PdfCanvas(page1); + canvas.AttachContentStream(new PdfStream("test".GetBytes(System.Text.Encoding.UTF8))); + String contentFromStream = iText.Commons.Utils.JavaUtil.GetStringForBytes(canvas.GetContentStream().GetBytes + (), System.Text.Encoding.UTF8); + pdfDoc.Close(); + NUnit.Framework.Assert.AreEqual("test", contentFromStream); + } + + [NUnit.Framework.Test] + public virtual void GraphicStateFontNullTest() { + String outPdf = DESTINATION_FOLDER + "showTextDoc.pdf"; + using (PdfDocument pdfDoc = new PdfDocument(CompareTool.CreateTestPdfWriter(outPdf))) { + PdfPage page1 = pdfDoc.AddNewPage(); + PdfCanvas canvas = new PdfCanvas(page1); + GlyphLine glyphLine = new GlyphLine(); + canvas.GetGraphicsState().SetFont(null); + ActualTextIterator actualTextIterator = new ActualTextIterator(glyphLine); + NUnit.Framework.Assert.Catch(typeof(PdfException), () => canvas.ShowText(glyphLine, actualTextIterator)); + } + } + + [NUnit.Framework.Test] + public virtual void GlyphlineActualTextTest() { + String outFileName = DESTINATION_FOLDER + "glyphlineActualText.pdf"; + using (PdfDocument pdfDocument = new PdfDocument(CompareTool.CreateTestPdfWriter(outFileName))) { + PdfFont font = PdfFontFactory.CreateFont(FONTS_FOLDER + "NotoSansCJKjp-Bold.otf", PdfEncodings.IDENTITY_H); + IList glyphs = JavaCollectionsUtil.SingletonList(font.GetGlyph((int)'\u65E0')); + GlyphLine glyphLine = new GlyphLine(glyphs); + glyphLine.SetActualText(0, 1, "TEST"); + PdfCanvas canvas = new PdfCanvas(pdfDocument.AddNewPage()); + canvas.SaveState().BeginText().SetFontAndSize(font, 7).ShowText(glyphLine).EndText().RestoreState(); + String contentstream = iText.Commons.Utils.JavaUtil.GetStringForBytes(canvas.GetContentStream().GetBytes() + , System.Text.Encoding.UTF8); + canvas.Release(); + NUnit.Framework.Assert.IsTrue(contentstream.Contains("/ActualText")); + } + } + private void CreateStandardDocument(PdfWriter writer, int pageCount, PdfCanvasTest.ContentProvider contentProvider ) { PdfDocument pdfDoc = new PdfDocument(writer); @@ -1229,7 +1312,7 @@ private void CreateStandardDocument(PdfWriter writer, int pageCount, PdfCanvasTe private void AssertStandardDocument(String filename, int pageCount) { PdfReader reader = CompareTool.CreateOutputReader(filename); PdfDocument pdfDocument = new PdfDocument(reader); - NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt"); + NUnit.Framework.Assert.IsFalse(reader.HasRebuiltXref(), "Rebuilt"); PdfDictionary info = pdfDocument.GetTrailer().GetAsDictionary(PdfName.Info); NUnit.Framework.Assert.AreEqual(AUTHOR, info.Get(PdfName.Author).ToString(), "Author"); NUnit.Framework.Assert.AreEqual(CREATOR, info.Get(PdfName.Creator).ToString(), "Creator"); diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/PdfCanvasUnitTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/PdfCanvasUnitTest.cs index d945b92b97..56a11c1db6 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/PdfCanvasUnitTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/PdfCanvasUnitTest.cs @@ -21,9 +21,16 @@ You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ using System; +using System.Collections.Generic; +using iText.Commons.Datastructures; +using iText.IO.Font.Constants; using iText.IO.Source; using iText.Kernel.Exceptions; +using iText.Kernel.Font; using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Extgstate; +using iText.Kernel.Validation; +using iText.Kernel.Validation.Context; using iText.Test; namespace iText.Kernel.Pdf.Canvas { @@ -85,5 +92,111 @@ public virtual void FontAndSizeShouldBeSetBeforeShowTextTest02() { NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.FONT_AND_SIZE_MUST_BE_SET_BEFORE_WRITING_ANY_TEXT , exception.Message); } + + [NUnit.Framework.Test] + public virtual void RenderingIntentValidationTest() { + using (PdfDocument doc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()))) { + ValidationContainer container = new ValidationContainer(); + PdfCanvasUnitTest.CustomValidationChecker checker = new PdfCanvasUnitTest.CustomValidationChecker(); + container.AddChecker(checker); + doc.GetDiContainer().Register(typeof(ValidationContainer), container); + NUnit.Framework.Assert.IsNull(checker.intent); + PdfPage pdfPage = doc.AddNewPage(); + PdfCanvas pdfCanvas = new PdfCanvas(pdfPage); + PdfName intent = new PdfName("Test"); + pdfCanvas.SetRenderingIntent(intent); + NUnit.Framework.Assert.AreSame(intent, checker.intent); + } + } + + [NUnit.Framework.Test] + public virtual void BmcValidationTest() { + using (PdfDocument doc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()))) { + ValidationContainer container = new ValidationContainer(); + PdfCanvasUnitTest.CustomValidationChecker checker = new PdfCanvasUnitTest.CustomValidationChecker(); + container.AddChecker(checker); + doc.GetDiContainer().Register(typeof(ValidationContainer), container); + NUnit.Framework.Assert.IsNull(checker.intent); + PdfPage pdfPage = doc.AddNewPage(); + PdfCanvas pdfCanvas = new PdfCanvas(pdfPage); + PdfName tag = new PdfName("Test"); + pdfCanvas.BeginMarkedContent(tag); + NUnit.Framework.Assert.AreSame(tag, checker.currentBmc.GetFirst()); + NUnit.Framework.Assert.IsNull(checker.currentBmc.GetSecond()); + NUnit.Framework.Assert.AreEqual(1, checker.tagStructureStack.Count); + } + } + + [NUnit.Framework.Test] + public virtual void FontGlyphsValidationTest() { + using (PdfDocument doc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()))) { + ValidationContainer container = new ValidationContainer(); + PdfCanvasUnitTest.CustomValidationChecker checker = new PdfCanvasUnitTest.CustomValidationChecker(); + container.AddChecker(checker); + doc.GetDiContainer().Register(typeof(ValidationContainer), container); + NUnit.Framework.Assert.IsNull(checker.intent); + PdfPage pdfPage = doc.AddNewPage(); + PdfCanvas pdfCanvas = new PdfCanvas(pdfPage); + pdfCanvas.BeginText(); + pdfCanvas.SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.COURIER), 24); + pdfCanvas.ShowText("Test"); + pdfCanvas.EndText(); + NUnit.Framework.Assert.IsNotNull(checker.gState); + NUnit.Framework.Assert.IsNotNull(checker.contentStream); + } + } + + [NUnit.Framework.Test] + public virtual void ExtendedGStateValidationTest() { + using (PdfDocument doc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()))) { + ValidationContainer container = new ValidationContainer(); + PdfCanvasUnitTest.CustomValidationChecker checker = new PdfCanvasUnitTest.CustomValidationChecker(); + container.AddChecker(checker); + doc.GetDiContainer().Register(typeof(ValidationContainer), container); + NUnit.Framework.Assert.IsNull(checker.intent); + PdfPage pdfPage = doc.AddNewPage(); + PdfCanvas pdfCanvas = new PdfCanvas(pdfPage); + pdfCanvas.SetExtGState(new PdfExtGState()); + NUnit.Framework.Assert.IsNotNull(checker.gState); + NUnit.Framework.Assert.IsNotNull(checker.contentStream); + } + } + + private class CustomValidationChecker : IValidationChecker { + public PdfName intent; + + public Stack> tagStructureStack; + + public Tuple2 currentBmc; + + public PdfStream contentStream; + + public CanvasGraphicsState gState; + + public virtual void Validate(IValidationContext validationContext) { + if (validationContext.GetType() == ValidationType.RENDERING_INTENT) { + intent = ((RenderingIntentValidationContext)validationContext).GetIntent(); + } + if (validationContext.GetType() == ValidationType.CANVAS_BEGIN_MARKED_CONTENT) { + CanvasBmcValidationContext bmcContext = (CanvasBmcValidationContext)validationContext; + tagStructureStack = bmcContext.GetTagStructureStack(); + currentBmc = bmcContext.GetCurrentBmc(); + } + if (validationContext.GetType() == ValidationType.EXTENDED_GRAPHICS_STATE) { + ExtendedGStateValidationContext gContext = (ExtendedGStateValidationContext)validationContext; + contentStream = gContext.GetContentStream(); + gState = gContext.GetGraphicsState(); + } + if (validationContext.GetType() == ValidationType.FONT_GLYPHS) { + FontGlyphsGStateValidationContext glyphsContext = (FontGlyphsGStateValidationContext)validationContext; + contentStream = glyphsContext.GetContentStream(); + gState = glyphsContext.GetGraphicsState(); + } + } + + public virtual bool IsPdfObjectReadyToFlush(PdfObject @object) { + return true; + } + } } } diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest.cs index 0a03ac0bf3..15691590f1 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest.cs @@ -98,21 +98,150 @@ public virtual void ParseInlineImageTest() { NUnit.Framework.Assert.AreEqual(cmpImgBytes, data); } + [NUnit.Framework.Test] + public virtual void ParseInlineImageCalRGBColorSpaceTest() { + using (PdfDocument pdf = new PdfDocument(new PdfReader(sourceFolder + "inlineImageCalRGBColorSpace.pdf"))) { + PdfCanvasProcessor pdfCanvasProcessor = new PdfCanvasProcessor(new SimpleTextExtractionStrategy()); + pdfCanvasProcessor.ProcessPageContent(pdf.GetPage(1)); + PdfName name = new PdfName("Cs1"); + PdfColorSpace colorSpace = pdf.GetPage(1).GetResources().GetColorSpace(name); + PdfArray pdfArray = (PdfArray)colorSpace.GetPdfObject(); + PdfName actualName = (PdfName)pdfArray.Get(0); + NUnit.Framework.Assert.AreEqual(PdfName.CalRGB, actualName); + } + } + + [NUnit.Framework.Test] + public virtual void ParseInlineImageCalGrayColorSpaceTest() { + using (PdfDocument pdf = new PdfDocument(new PdfReader(sourceFolder + "inlineImageCalGrayColorSpace.pdf")) + ) { + PdfCanvasProcessor pdfCanvasProcessor = new PdfCanvasProcessor(new SimpleTextExtractionStrategy()); + pdfCanvasProcessor.ProcessPageContent(pdf.GetPage(1)); + PdfName name = new PdfName("Cs1"); + PdfColorSpace colorSpace = pdf.GetPage(1).GetResources().GetColorSpace(name); + PdfArray pdfArray = (PdfArray)colorSpace.GetPdfObject(); + PdfName actualName = (PdfName)pdfArray.Get(0); + NUnit.Framework.Assert.AreEqual(PdfName.CalGray, actualName); + } + } + + [NUnit.Framework.Test] + public virtual void ParseInlineImageLabColorSpaceTest() { + using (PdfDocument pdf = new PdfDocument(new PdfReader(sourceFolder + "inlineImageLabColorSpace.pdf"))) { + PdfCanvasProcessor pdfCanvasProcessor = new PdfCanvasProcessor(new SimpleTextExtractionStrategy()); + pdfCanvasProcessor.ProcessPageContent(pdf.GetPage(1)); + PdfName name = new PdfName("Cs1"); + PdfColorSpace colorSpace = pdf.GetPage(1).GetResources().GetColorSpace(name); + PdfArray pdfArray = (PdfArray)colorSpace.GetPdfObject(); + PdfName actualName = (PdfName)pdfArray.Get(0); + NUnit.Framework.Assert.AreEqual(PdfName.Lab, actualName); + } + } + + [NUnit.Framework.Test] + public virtual void ParseInlineImageICCBasedColorSpaceTest() { + using (PdfDocument pdf = new PdfDocument(new PdfReader(sourceFolder + "inlineImageICCBasedColorSpace.pdf") + )) { + PdfCanvasProcessor pdfCanvasProcessor = new PdfCanvasProcessor(new SimpleTextExtractionStrategy()); + pdfCanvasProcessor.ProcessPageContent(pdf.GetPage(1)); + PdfName name = new PdfName("Cs1"); + PdfColorSpace colorSpace = pdf.GetPage(1).GetResources().GetColorSpace(name); + PdfArray pdfArray = (PdfArray)colorSpace.GetPdfObject(); + PdfName actualName = (PdfName)pdfArray.Get(0); + NUnit.Framework.Assert.AreEqual(PdfName.ICCBased, actualName); + } + } + + [NUnit.Framework.Test] + public virtual void ParseInlineImageDeviceRGBColorSpaceTest() { + using (PdfDocument pdf = new PdfDocument(new PdfReader(sourceFolder + "inlineImageDeviceRGBColorSpace.pdf" + ))) { + PdfCanvasProcessor pdfCanvasProcessor = new PdfCanvasProcessor(new SimpleTextExtractionStrategy()); + pdfCanvasProcessor.ProcessPageContent(pdf.GetPage(1)); + PdfStream stream = pdf.GetPage(1).GetContentStream(0); + String firstPageData = iText.Commons.Utils.JavaUtil.GetStringForBytes(stream.GetBytes()); + NUnit.Framework.Assert.IsTrue(firstPageData.Contains(PdfName.DeviceRGB.GetValue())); + } + } + + [NUnit.Framework.Test] + public virtual void ParseInlineImageDeviceCMYKColorSpaceTest() { + using (PdfDocument pdf = new PdfDocument(new PdfReader(sourceFolder + "inlineImageDeviceCMYKColorSpace.pdf" + ))) { + PdfCanvasProcessor pdfCanvasProcessor = new PdfCanvasProcessor(new SimpleTextExtractionStrategy()); + pdfCanvasProcessor.ProcessPageContent(pdf.GetPage(1)); + PdfStream stream = pdf.GetPage(1).GetContentStream(0); + String firstPageData = iText.Commons.Utils.JavaUtil.GetStringForBytes(stream.GetBytes()); + NUnit.Framework.Assert.IsTrue(firstPageData.Contains(PdfName.DeviceCMYK.GetValue())); + } + } + + [NUnit.Framework.Test] + public virtual void ParseInlineImageDeviceGrayColorSpaceTest() { + using (PdfDocument pdf = new PdfDocument(new PdfReader(sourceFolder + "inlineImageDeviceGrayColorSpace.pdf" + ))) { + PdfCanvasProcessor pdfCanvasProcessor = new PdfCanvasProcessor(new SimpleTextExtractionStrategy()); + pdfCanvasProcessor.ProcessPageContent(pdf.GetPage(1)); + PdfStream stream = pdf.GetPage(1).GetContentStream(0); + String firstPageData = iText.Commons.Utils.JavaUtil.GetStringForBytes(stream.GetBytes()); + NUnit.Framework.Assert.IsTrue(firstPageData.Contains(PdfName.DeviceGray.GetValue())); + } + } + + [NUnit.Framework.Test] + public virtual void ParseInlineImageSeparationColorSpaceTest() { + using (PdfDocument pdf = new PdfDocument(new PdfReader(sourceFolder + "inlineImageSeparationColorSpace.pdf" + ))) { + PdfCanvasProcessor pdfCanvasProcessor = new PdfCanvasProcessor(new SimpleTextExtractionStrategy()); + pdfCanvasProcessor.ProcessPageContent(pdf.GetPage(1)); + PdfName name = new PdfName("Cs1"); + PdfColorSpace colorSpace = pdf.GetPage(1).GetResources().GetColorSpace(name); + PdfArray pdfArray = (PdfArray)colorSpace.GetPdfObject(); + PdfName actualName = (PdfName)pdfArray.Get(0); + NUnit.Framework.Assert.AreEqual(PdfName.Separation, actualName); + } + } + + [NUnit.Framework.Test] + public virtual void ParseInlineImageDeviceNColorSpaceTest() { + using (PdfDocument pdf = new PdfDocument(new PdfReader(sourceFolder + "inlineImageDeviceNColorSpace.pdf")) + ) { + PdfCanvasProcessor pdfCanvasProcessor = new PdfCanvasProcessor(new SimpleTextExtractionStrategy()); + pdfCanvasProcessor.ProcessPageContent(pdf.GetPage(1)); + PdfName name = new PdfName("Cs1"); + PdfColorSpace colorSpace = pdf.GetPage(1).GetResources().GetColorSpace(name); + PdfArray pdfArray = (PdfArray)colorSpace.GetPdfObject(); + PdfName actualName = (PdfName)pdfArray.Get(0); + NUnit.Framework.Assert.AreEqual(PdfName.DeviceN, actualName); + } + } + + [NUnit.Framework.Test] + public virtual void ParseInlineImageIndexedColorSpaceTest() { + using (PdfDocument pdf = new PdfDocument(new PdfReader(sourceFolder + "inlineImageIndexedColorSpace.pdf")) + ) { + PdfCanvasProcessor pdfCanvasProcessor = new PdfCanvasProcessor(new SimpleTextExtractionStrategy()); + pdfCanvasProcessor.ProcessPageContent(pdf.GetPage(1)); + PdfName name = new PdfName("Cs1"); + PdfColorSpace colorSpace = pdf.GetPage(1).GetResources().GetColorSpace(name); + PdfArray pdfArray = (PdfArray)colorSpace.GetPdfObject(); + PdfName actualName = (PdfName)pdfArray.Get(0); + NUnit.Framework.Assert.AreEqual(PdfName.Indexed, actualName); + } + } + private class InlineImageEventListener : IEventListener { - private IList inlineImages = new List(); + private readonly IList inlineImages = new List(); public virtual IList GetInlineImages() { return inlineImages; } public virtual void EventOccurred(IEventData data, EventType type) { - switch (type) { - case EventType.RENDER_IMAGE: { - ImageRenderInfo imageEventData = (ImageRenderInfo)data; - if (((ImageRenderInfo)data).IsInline()) { - inlineImages.Add(imageEventData.GetImage().GetPdfObject()); - } - break; + if (type == EventType.RENDER_IMAGE) { + ImageRenderInfo imageEventData = (ImageRenderInfo)data; + if (((ImageRenderInfo)data).IsInline()) { + inlineImages.Add(imageEventData.GetImage().GetPdfObject()); } } } diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/parser/PdfCanvasProcessorUnitTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/parser/PdfCanvasProcessorUnitTest.cs index 54e6bbcb33..8f8520eef7 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/parser/PdfCanvasProcessorUnitTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/parser/PdfCanvasProcessorUnitTest.cs @@ -30,14 +30,14 @@ namespace iText.Kernel.Pdf.Canvas.Parser { public class PdfCanvasProcessorUnitTest : ExtendedITextTest { [NUnit.Framework.Test] public virtual void BeginMarkerContentOperatorTest() { - PdfCanvasProcessor processor = new _PdfCanvasProcessor_42(new FilteredEventListener()); + PdfCanvasProcessor processor = new _PdfCanvasProcessor_41(new FilteredEventListener()); IContentOperator contentOperator = processor.RegisterContentOperator("BMC", null); processor.RegisterContentOperator("BMC", contentOperator); contentOperator.Invoke(processor, null, JavaCollectionsUtil.SingletonList((PdfObject)null)); } - private sealed class _PdfCanvasProcessor_42 : PdfCanvasProcessor { - public _PdfCanvasProcessor_42(IEventListener baseArg1) + private sealed class _PdfCanvasProcessor_41 : PdfCanvasProcessor { + public _PdfCanvasProcessor_41(IEventListener baseArg1) : base(baseArg1) { } diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/parser/PdfContentExtractionTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/parser/PdfContentExtractionTest.cs index 2cbb139509..40f98d54f7 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/parser/PdfContentExtractionTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/parser/PdfContentExtractionTest.cs @@ -29,22 +29,38 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Kernel.Pdf.Canvas.Parser { [NUnit.Framework.Category("IntegrationTest")] public class PdfContentExtractionTest : ExtendedITextTest { - private static readonly String sourceFolder = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + private static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext .CurrentContext.TestDirectory) + "/resources/itext/kernel/parser/PdfContentExtractionTest/"; [NUnit.Framework.Test] public virtual void ContentExtractionInDocWithBigCoordinatesTest() { - //TODO: remove the expected exception construct once the issue is fixed (DEVSIX-1279) - String inputFileName = sourceFolder + "docWithBigCoordinates.pdf"; - //In this document the CTM shrinks coordinates and this coordinates are large numbers. + String inputFileName = SOURCE_FOLDER + "docWithBigCoordinates.pdf"; + // In this document the CTM shrinks coordinates and these coordinates are large numbers. // At the moment creation of this test clipper has a problem with handling large numbers // since internally it deals with integers and has to multiply large numbers even more // for internal purposes - PdfDocument pdfDocument = new PdfDocument(new PdfReader(inputFileName)); - PdfDocumentContentParser contentParser = new PdfDocumentContentParser(pdfDocument); - Exception e = NUnit.Framework.Assert.Catch(typeof(ClipperException), () => contentParser.ProcessContent(1, - new LocationTextExtractionStrategy())); - NUnit.Framework.Assert.AreEqual(ClipperExceptionConstant.COORDINATE_OUTSIDE_ALLOWED_RANGE, e.Message); + using (PdfDocument pdfDocument = new PdfDocument(new PdfReader(inputFileName))) { + PdfDocumentContentParser contentParser = new PdfDocumentContentParser(pdfDocument); + NUnit.Framework.Assert.DoesNotThrow(() => contentParser.ProcessContent(1, new LocationTextExtractionStrategy + ())); + } + } + + [NUnit.Framework.Test] + public virtual void ContentExtractionInDocWithStaticFloatMultiplierTest() { + String inputFileName = SOURCE_FOLDER + "docWithBigCoordinates.pdf"; + // In this document the CTM shrinks coordinates and these coordinates are large numbers. + // At the moment creation of this test clipper has a problem with handling large numbers + // since internally it deals with integers and has to multiply large numbers even more + // for internal purposes + using (PdfDocument pdfDocument = new PdfDocument(new PdfReader(inputFileName))) { + PdfDocumentContentParser contentParser = new PdfDocumentContentParser(pdfDocument); + ClipperBridge.floatMultiplier = Math.Pow(10, 14); + Exception e = NUnit.Framework.Assert.Catch(typeof(ClipperException), () => contentParser.ProcessContent(1, + new LocationTextExtractionStrategy())); + NUnit.Framework.Assert.AreEqual(ClipperExceptionConstant.COORDINATE_OUTSIDE_ALLOWED_RANGE, e.Message); + ClipperBridge.floatMultiplier = null; + } } } } diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/parser/clipperlib/ClipperBridgeTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/parser/clipperlib/ClipperBridgeTest.cs index 1791781011..7659abeca4 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/parser/clipperlib/ClipperBridgeTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/parser/clipperlib/ClipperBridgeTest.cs @@ -22,6 +22,7 @@ You should have received a copy of the GNU Affero General Public License */ using System.Collections.Generic; using System.Linq; +using iText.Commons.Utils; using iText.Kernel.Geom; using iText.Kernel.Pdf.Canvas; using iText.Test; @@ -48,11 +49,12 @@ public virtual void SquareClippingTest() { Path rectanglePath = new Path(); rectanglePath.AddSubpath(rectangleSubpath); Clipper clipper = new Clipper(); - ClipperBridge.AddPath(clipper, squarePath, PolyType.SUBJECT); - ClipperBridge.AddPath(clipper, rectanglePath, PolyType.CLIP); + ClipperBridge clipperBridge = new ClipperBridge(squarePath, rectanglePath); + clipperBridge.AddPath(clipper, squarePath, PolyType.SUBJECT); + clipperBridge.AddPath(clipper, rectanglePath, PolyType.CLIP); PolyTree polyTree = new PolyTree(); clipper.Execute(ClipType.UNION, polyTree); - Path result = ClipperBridge.ConvertToPath(polyTree); + Path result = clipperBridge.ConvertToPath(polyTree); NUnit.Framework.Assert.AreEqual(new Point(20, 40), result.GetCurrentPoint()); NUnit.Framework.Assert.AreEqual(2, result.GetSubpaths().Count); Subpath closedPath = result.GetSubpaths()[0]; @@ -95,14 +97,34 @@ public virtual void GetEndTypeTest() { public virtual void LongRectWidthTest() { IntRect longRect = new IntRect(14900000000000000L, 21275000000000000L, 71065802001953128L, 71075000000000000L ); - NUnit.Framework.Assert.AreEqual(561.658, ClipperBridge.LongRectCalculateWidth(longRect), 0.001f); + NUnit.Framework.Assert.AreEqual(561.658, new ClipperBridge().LongRectCalculateWidth(longRect), 0.001f); } [NUnit.Framework.Test] public virtual void LongRectHeightTest() { IntRect longRect = new IntRect(14900000000000000L, 21275000000000000L, 71065802001953128L, 71075000000000000L ); - NUnit.Framework.Assert.AreEqual(498, ClipperBridge.LongRectCalculateHeight(longRect), 0.001f); + NUnit.Framework.Assert.AreEqual(498, new ClipperBridge().LongRectCalculateHeight(longRect), 0.001f); + } + + [NUnit.Framework.Test] + public virtual void DynamicFloatMultiplierCalculationsSmallValuesTest() { + Point[] points = new Point[] { new Point(1e-10, 0), new Point(0, 1e-13) }; + NUnit.Framework.Assert.AreEqual(1.8014398509481984e26, new ClipperBridge(points).GetFloatMultiplier(), 0e+10 + ); + } + + [NUnit.Framework.Test] + public virtual void DynamicFloatMultiplierCalculationsBigValuesTest() { + Point[] points = new Point[] { new Point(1e+11, 10), new Point(10, 1e+10) }; + NUnit.Framework.Assert.AreEqual(180143, new ClipperBridge(points).GetFloatMultiplier(), 0.001f); + } + + [NUnit.Framework.Test] + public virtual void SmallFloatMultiplierCoefficientTest() { + Point[] points = new Point[] { new Point(1e-10, 1e+10) }; + NUnit.Framework.Assert.AreEqual(new IntPoint(0, 18014390000000000L), new ClipperBridge(points).ConvertToLongPoints + (JavaUtil.ArraysAsList(points))[0]); } private bool AreShapesEqual(IShape expected, IShape actual) { diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/parser/listener/RegexBasedLocationExtractionStrategyTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/parser/listener/RegexBasedLocationExtractionStrategyTest.cs index 2e2cfeb2ca..950660f732 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/parser/listener/RegexBasedLocationExtractionStrategyTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/parser/listener/RegexBasedLocationExtractionStrategyTest.cs @@ -23,7 +23,6 @@ You should have received a copy of the GNU Affero General Public License using System; using System.Collections.Generic; using System.IO; -using System.Text.RegularExpressions; using iText.Kernel.Geom; using iText.Kernel.Pdf; using iText.Kernel.Pdf.Canvas.Parser; @@ -36,20 +35,47 @@ public class RegexBasedLocationExtractionStrategyTest : ExtendedITextTest { .CurrentContext.TestDirectory) + "/resources/itext/kernel/parser/RegexBasedLocationExtractionStrategyTest/"; [NUnit.Framework.Test] - public virtual void Test01() { - System.Console.Out.WriteLine(new FileInfo(sourceFolder).FullName); - PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + "in01.pdf")); - // build strategy - RegexBasedLocationExtractionStrategy extractionStrategy = new RegexBasedLocationExtractionStrategy(iText.Commons.Utils.StringUtil.RegexCompile - ("\\{\\{Signature\\}\\}")); + public virtual void Test00() { + PdfDocument document = new PdfDocument(new PdfReader(sourceFolder + "in00.pdf")); // get locations IList locationList = new List(); - for (int x = 1; x <= pdfDocument.GetNumberOfPages(); x++) { - new PdfCanvasProcessor(extractionStrategy).ProcessPageContent(pdfDocument.GetPage(x)); + for (int i = 1; i <= document.GetNumberOfPages(); ++i) { + RegexBasedLocationExtractionStrategy extractionStrategy = new RegexBasedLocationExtractionStrategy("cillum" + ); + PdfCanvasProcessor processor = new PdfCanvasProcessor(extractionStrategy); + processor.ProcessPageContent(document.GetPage(i)); foreach (IPdfTextLocation location in extractionStrategy.GetResultantLocations()) { - if (location != null) { - locationList.Add(location); - } + locationList.Add(location); + } + } + // compare + NUnit.Framework.Assert.AreEqual(2, locationList.Count); + IPdfTextLocation loc = locationList[0]; + NUnit.Framework.Assert.AreEqual("cillum", loc.GetText()); + NUnit.Framework.Assert.AreEqual(64, (int)loc.GetRectangle().GetX()); + NUnit.Framework.Assert.AreEqual(732, (int)loc.GetRectangle().GetY()); + NUnit.Framework.Assert.AreEqual(30, (int)loc.GetRectangle().GetWidth()); + NUnit.Framework.Assert.AreEqual(11, (int)loc.GetRectangle().GetHeight()); + IPdfTextLocation loc2 = locationList[1]; + NUnit.Framework.Assert.AreEqual(64, (int)loc2.GetRectangle().GetX()); + NUnit.Framework.Assert.AreEqual(732, (int)loc2.GetRectangle().GetY()); + NUnit.Framework.Assert.AreEqual(30, (int)loc2.GetRectangle().GetWidth()); + NUnit.Framework.Assert.AreEqual(11, (int)loc2.GetRectangle().GetHeight()); + document.Close(); + } + + [NUnit.Framework.Test] + public virtual void Test02() { + PdfDocument document = new PdfDocument(new PdfReader(sourceFolder + "in01.pdf")); + // get locations + IList locationList = new List(); + for (int i = 1; i <= document.GetNumberOfPages(); ++i) { + RegexBasedLocationExtractionStrategy extractionStrategy = new RegexBasedLocationExtractionStrategy("\\{\\{Signature\\}\\}" + ); + PdfCanvasProcessor processor = new PdfCanvasProcessor(extractionStrategy); + processor.ProcessPageContent(document.GetPage(i)); + foreach (IPdfTextLocation location in extractionStrategy.GetResultantLocations()) { + locationList.Add(location); } } // compare @@ -60,8 +86,7 @@ public virtual void Test01() { NUnit.Framework.Assert.AreEqual(375, (int)loc.GetRectangle().GetY()); NUnit.Framework.Assert.AreEqual(55, (int)loc.GetRectangle().GetWidth()); NUnit.Framework.Assert.AreEqual(11, (int)loc.GetRectangle().GetHeight()); - // close - pdfDocument.Close(); + document.Close(); } // https://jira.itextsupport.com/browse/DEVSIX-1940 @@ -70,11 +95,11 @@ public virtual void Test01() { public virtual void TestLigatureBeforeLigature() { System.Console.Out.WriteLine(new FileInfo(sourceFolder).FullName); PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + "ligature.pdf")); - // build strategy - RegexBasedLocationExtractionStrategy extractionStrategy = new RegexBasedLocationExtractionStrategy("ca"); // get locations IList locationList = new List(); for (int x = 1; x <= pdfDocument.GetNumberOfPages(); x++) { + // build strategy + RegexBasedLocationExtractionStrategy extractionStrategy = new RegexBasedLocationExtractionStrategy("ca"); new PdfCanvasProcessor(extractionStrategy).ProcessPageContent(pdfDocument.GetPage(x)); foreach (IPdfTextLocation location in extractionStrategy.GetResultantLocations()) { if (location != null) { @@ -98,11 +123,11 @@ public virtual void TestLigatureBeforeLigature() { public virtual void TestLigatureCrossLigature() { System.Console.Out.WriteLine(new FileInfo(sourceFolder).FullName); PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + "ligature.pdf")); - // build strategy - RegexBasedLocationExtractionStrategy extractionStrategy = new RegexBasedLocationExtractionStrategy("al"); // get locations IList locationList = new List(); for (int x = 1; x <= pdfDocument.GetNumberOfPages(); x++) { + // build strategy + RegexBasedLocationExtractionStrategy extractionStrategy = new RegexBasedLocationExtractionStrategy("al"); new PdfCanvasProcessor(extractionStrategy).ProcessPageContent(pdfDocument.GetPage(x)); foreach (IPdfTextLocation location in extractionStrategy.GetResultantLocations()) { if (location != null) { @@ -126,11 +151,11 @@ public virtual void TestLigatureCrossLigature() { public virtual void TestLigatureInLigature() { System.Console.Out.WriteLine(new FileInfo(sourceFolder).FullName); PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + "ligature.pdf")); - // build strategy - RegexBasedLocationExtractionStrategy extractionStrategy = new RegexBasedLocationExtractionStrategy("l"); // get locations IList locationList = new List(); for (int x = 1; x <= pdfDocument.GetNumberOfPages(); x++) { + // build strategy + RegexBasedLocationExtractionStrategy extractionStrategy = new RegexBasedLocationExtractionStrategy("l"); new PdfCanvasProcessor(extractionStrategy).ProcessPageContent(pdfDocument.GetPage(x)); foreach (IPdfTextLocation location in extractionStrategy.GetResultantLocations()) { if (location != null) { @@ -153,11 +178,11 @@ public virtual void TestLigatureInLigature() { [NUnit.Framework.Test] public virtual void TestRotatedText() { PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + "rotatedText.pdf")); - // build strategy - RegexBasedLocationExtractionStrategy extractionStrategy = new RegexBasedLocationExtractionStrategy("abc"); // get locations IList locationList = new List(); for (int x = 1; x <= pdfDocument.GetNumberOfPages(); x++) { + // build strategy + RegexBasedLocationExtractionStrategy extractionStrategy = new RegexBasedLocationExtractionStrategy("abc"); new PdfCanvasProcessor(extractionStrategy).ProcessPageContent(pdfDocument.GetPage(x)); foreach (IPdfTextLocation location in extractionStrategy.GetResultantLocations()) { if (location != null) { diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/parser/util/InlineImageParsingUtilsTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/parser/util/InlineImageParsingUtilsTest.cs index 0e49cf4756..34b7ed5f68 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/parser/util/InlineImageParsingUtilsTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/canvas/parser/util/InlineImageParsingUtilsTest.cs @@ -21,7 +21,10 @@ You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ using System; +using System.Collections.Generic; +using System.IO; using iText.Commons.Utils; +using iText.IO.Source; using iText.Kernel.Exceptions; using iText.Kernel.Pdf; using iText.Test; @@ -29,6 +32,9 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Kernel.Pdf.Canvas.Parser.Util { [NUnit.Framework.Category("UnitTest")] public class InlineImageParsingUtilsTest : ExtendedITextTest { + private static readonly String RESOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + .CurrentContext.TestDirectory) + "/resources/itext/kernel/pdf/canvas/parser/InlineImageParsingUtilsTest/"; + [NUnit.Framework.Test] public virtual void IccBasedCsTest() { PdfName colorSpace = PdfName.ICCBased; @@ -70,22 +76,6 @@ public virtual void CsInDictAsNameNullTest() { , "/ICCBased"), exception.Message); } - [NUnit.Framework.Test] - public virtual void NotSupportedCsWithCsDictionaryTest() { - PdfName colorSpace = PdfName.ICCBased; - PdfDictionary dictionary = new PdfDictionary(); - PdfArray array = new PdfArray(); - array.Add(PdfName.Pattern); - PdfStream stream = new PdfStream(); - stream.Put(PdfName.N, new PdfNumber(4)); - array.Add(stream); - dictionary.Put(colorSpace, array); - Exception exception = NUnit.Framework.Assert.Catch(typeof(InlineImageParsingUtils.InlineImageParseException - ), () => InlineImageParsingUtils.GetComponentsPerPixel(colorSpace, dictionary)); - NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(KernelExceptionMessageConstant.UNEXPECTED_COLOR_SPACE - , "/ICCBased"), exception.Message); - } - [NUnit.Framework.Test] public virtual void NullCsTest() { NUnit.Framework.Assert.AreEqual(1, InlineImageParsingUtils.GetComponentsPerPixel(null, null)); @@ -108,5 +98,60 @@ public virtual void DeviceCMYKCsTest() { PdfName colorSpace = PdfName.DeviceCMYK; NUnit.Framework.Assert.AreEqual(4, InlineImageParsingUtils.GetComponentsPerPixel(colorSpace, null)); } + + [NUnit.Framework.Test] + public virtual void ParseLargeImageWithEndMarkerInDataTest() { + PdfTokenizer tokenizer = new PdfTokenizer(new RandomAccessFileOrArray(new RandomAccessSourceFactory().CreateSource + (File.ReadAllBytes(System.IO.Path.Combine(RESOURCE_FOLDER + "img.dat"))))); + PdfCanvasParser ps = new PdfCanvasParser(tokenizer, new PdfResources()); + IList objects = ps.Parse(null); + NUnit.Framework.Assert.AreEqual(2, objects.Count); + NUnit.Framework.Assert.IsTrue(objects[0] is PdfStream); + NUnit.Framework.Assert.AreEqual(new PdfLiteral("EI"), objects[1]); + //Getting encoded bytes of an image, can't use PdfStream#getBytes() here because it decodes an image + byte[] image = ((ByteArrayOutputStream)((PdfStream)objects[0]).GetOutputStream().GetOutputStream()).ToArray + (); + byte[] cmpImage = File.ReadAllBytes(System.IO.Path.Combine(RESOURCE_FOLDER, "cmp_img.dat")); + NUnit.Framework.Assert.AreEqual(cmpImage, image); + } + + [NUnit.Framework.Test] + public virtual void BinaryDataProbationTest() { + TestInlineImage("ID\nBl7a$DIjr)D..'g+Cno&@/EI Q", "inline image data"); + TestInlineImage("ID\nBl7a$DIjr)D..'g+Cno&@/EI EMC", "inline image data"); + TestInlineImage("ID\nBl7a$DIjr)D..'g+Cno&@/EI S", "inline image data"); + TestInlineImage("ID\nBl7a$DIjr)D..'g+Cno&@/EI EMC", "inline image data"); + TestInlineImage("ID\nBl7a$DIjr)D..'g+Cno&@/EI \x0Q", "inline image data"); + TestInlineImage("ID\nBl7a$DIjr)D..'g+Cno&@/EI Q ", "inline image data"); + TestInlineImage("ID\nBl7a$DIjr)D..'g+Cno&@/EI EMC ", "inline image data"); + TestInlineImage("ID\nBl7a$DIjr)D..'g+Cno&@/EI ", "inline image data"); + TestInlineImage("ID\nBl7a$DIjr)D..'g+Cno&@/EI Q ", "inline image data"); + TestInlineImage("ID\nBl7a$DIjr)D..'g+Cno&@/EI EMC ", "inline image data"); + TestInlineImage("ID\nBl7a$DIjr)D..'g+Cno&@/EI ", "inline image data"); + TestInlineImage("ID\nBl7a$DIjr)D..'g+Cno&@/EI QEI", "inline image data"); + TestInlineImage("ID\nBl7a$DIjr)D..'g+Cno&@/ EI ", "inline image data"); + // 2nd EI is taken into account + TestInlineImage("ID\nBl7a$DIjr)D..'g+Cno&@/ EI DDDEI ", "inline image dat`ûGÔn"); + TestInlineImage("ID\nBl7a$DIjr)D..'g+Cno&@/EI SEI Q", "inline image data"); + TestInlineImage("ID\nBl7a$DIjr)D..'g+Cno&@/EI \u0000", "inline image data"); + TestInlineImage("ID\nBl7a$DIjr)D..'g+Cno&@/EI \u007f", "inline image data"); + TestInlineImage("ID\nBl7a$DIjr)D..'g+Cno&@/EI \u0000pdf", "inline image data"); + TestInlineImage("ID\nBl7a$DIjr)D..'g+Cno&@/EI \u0000pdf\u0000\u0000\u0000", "inline image data"); + } + + private void TestInlineImage(String imgData, String cmpImgData) { + String data = "BI\n" + "/Width 10\n" + "/Height 10\n" + "/BitsPerComponent 8\n" + "/ColorSpace /DeviceRGB\n" + + "/Filter [/ASCII85Decode]\n" + imgData; + PdfTokenizer tokenizer = new PdfTokenizer(new RandomAccessFileOrArray(new RandomAccessSourceFactory().CreateSource + (data.GetBytes(iText.Commons.Utils.EncodingUtil.ISO_8859_1)))); + PdfCanvasParser ps = new PdfCanvasParser(tokenizer, new PdfResources()); + IList objects = ps.Parse(null); + NUnit.Framework.Assert.AreEqual(2, objects.Count); + NUnit.Framework.Assert.IsTrue(objects[0] is PdfStream); + NUnit.Framework.Assert.AreEqual(new PdfLiteral("EI"), objects[1]); + String image = iText.Commons.Utils.JavaUtil.GetStringForBytes(((PdfStream)objects[0]).GetBytes(), iText.Commons.Utils.EncodingUtil.ISO_8859_1 + ); + NUnit.Framework.Assert.AreEqual(image, cmpImgData); + } } } diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/colorspace/CreateShadingTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/colorspace/CreateShadingTest.cs index f94e694553..1b88bc04be 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/colorspace/CreateShadingTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/colorspace/CreateShadingTest.cs @@ -25,6 +25,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Utils; using iText.Kernel.Pdf; using iText.Kernel.Pdf.Canvas; +using iText.Kernel.Pdf.Colorspace.Shading; using iText.Kernel.Pdf.Function; using iText.Kernel.Utils; using iText.Test; @@ -61,7 +62,7 @@ public virtual void CreateAxialShadingWithStitchingFunctionTest() { int y1 = 400; PdfArray shadingVector = new PdfArray(new int[] { x0, y0, x1, y1 }); PdfType3Function stitchingFunction = CreateStitchingCmykShadingFunction(); - PdfShading.Axial axialShading = new PdfShading.Axial(new PdfDeviceCs.Cmyk(), shadingVector, stitchingFunction + PdfAxialShading axialShading = new PdfAxialShading(new PdfDeviceCs.Cmyk(), shadingVector, stitchingFunction ); pdfCanvas.PaintShading(axialShading); pdfDocument.Close(); @@ -78,9 +79,9 @@ public virtual void ModifyAxialShadingTest() { new StampingProperties().UseAppendMode()); PdfResources resources = pdfDocument.GetPage(1).GetResources(); foreach (PdfName resName in resources.GetResourceNames()) { - PdfShading shading = resources.GetShading(resName); - if (shading != null && shading.GetShadingType() == PdfShading.ShadingType.AXIAL) { - PdfShading.Axial axialShading = (PdfShading.Axial)shading; + AbstractPdfShading shading = resources.GetShading(resName); + if (shading != null && shading.GetShadingType() == ShadingType.AXIAL) { + PdfAxialShading axialShading = (PdfAxialShading)shading; // "cut" shading and extend colors axialShading.SetDomain(0.1f, 0.8f); axialShading.SetExtend(true, true); @@ -103,8 +104,8 @@ public virtual void CreateSimpleRadialShadingTest() { int x1 = x0; int y1 = y0; int r1 = 50; - PdfShading.Radial radialShading = new PdfShading.Radial(new PdfDeviceCs.Gray(), x0, y0, r0, new float[] { - 0.9f }, x1, y1, r1, new float[] { 0.2f }, new bool[] { false, false }); + PdfRadialShading radialShading = new PdfRadialShading(new PdfDeviceCs.Gray(), x0, y0, r0, new float[] { 0.9f + }, x1, y1, r1, new float[] { 0.2f }, new bool[] { false, false }); pdfCanvas.PaintShading(radialShading); pdfDocument.Close(); AssertShadingDictionaryResult(outName, cmpName, "Sh1"); @@ -125,7 +126,7 @@ public virtual void CreateRadialShadingWithStitchingFunctionTest() { int r1 = 50; PdfArray shadingVector = new PdfArray(new int[] { x0, y0, r0, x1, y1, r1 }); PdfType3Function stitchingFunction = CreateStitchingCmykShadingFunction(); - PdfShading.Radial radialShading = new PdfShading.Radial(new PdfDeviceCs.Cmyk(), shadingVector, stitchingFunction + PdfRadialShading radialShading = new PdfRadialShading(new PdfDeviceCs.Cmyk(), shadingVector, stitchingFunction ); pdfCanvas.PaintShading(radialShading); pdfDocument.Close(); @@ -142,9 +143,9 @@ public virtual void ModifyRadialShadingTest() { new StampingProperties().UseAppendMode()); PdfResources resources = pdfDocument.GetPage(1).GetResources(); foreach (PdfName resName in resources.GetResourceNames()) { - PdfShading shading = resources.GetShading(resName); - if (shading != null && shading.GetShadingType() == PdfShading.ShadingType.RADIAL) { - PdfShading.Radial radialShading = (PdfShading.Radial)shading; + AbstractPdfShading shading = resources.GetShading(resName); + if (shading != null && shading.GetShadingType() == ShadingType.RADIAL) { + PdfRadialShading radialShading = (PdfRadialShading)shading; // "cut" shading and extend colors radialShading.SetDomain(0.1f, 0.8f); radialShading.SetExtend(true, true); diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/colorspace/PdfShadingDocumentTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/colorspace/PdfShadingDocumentTest.cs new file mode 100644 index 0000000000..ad9677f1c0 --- /dev/null +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/colorspace/PdfShadingDocumentTest.cs @@ -0,0 +1,63 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Canvas; +using iText.Kernel.Pdf.Colorspace.Shading; +using iText.Test; + +namespace iText.Kernel.Pdf.Colorspace { + [NUnit.Framework.Category("IntegrationTest")] + public class PdfShadingDocumentTest : ExtendedITextTest { + public static readonly String DESTINATION_FOLDER = NUnit.Framework.TestContext.CurrentContext.TestDirectory + + "/test/itext/kernel/pdf/colorspace/PdfShadingDocumentTest/"; + + [NUnit.Framework.OneTimeSetUp] + public static void BeforeClass() { + CreateOrClearDestinationFolder(DESTINATION_FOLDER); + } + + [NUnit.Framework.Test] + public virtual void AxialDocumentTest() { + String dest = DESTINATION_FOLDER + "axialDoc.pdf"; + using (PdfDocument pdfDocument = new PdfDocument(new PdfWriter(dest))) { + PdfPage pdfPage = pdfDocument.AddNewPage(); + PdfCanvas canvas = new PdfCanvas(pdfPage); + int x = 36; + int y = 400; + int side = 500; + float[] green = new float[] { 0, 255, 0 }; + float[] blue = new float[] { 0, 0, 255 }; + PdfAxialShading axial = new PdfAxialShading(new PdfDeviceCs.Rgb(), x, y, green, x + side, y, blue); + PdfPattern.Shading shading = new PdfPattern.Shading(axial); + canvas.SetFillColorShading(shading); + canvas.MoveTo(x, y); + canvas.LineTo(x + side, y); + canvas.LineTo(x + (side / 2), (float)(y + (side * Math.Sin(Math.PI / 3)))); + canvas.ClosePathFillStroke(); + PdfDictionary pdfObject = pdfDocument.GetPage(1).GetResources().GetPdfObject(); + NUnit.Framework.Assert.IsTrue(pdfObject.ContainsKey(PdfName.Pattern)); + } + } + } +} diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/colorspace/PdfShadingParameterizedTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/colorspace/PdfShadingParameterizedTest.cs index 845580bcf1..78861365fd 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/colorspace/PdfShadingParameterizedTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/colorspace/PdfShadingParameterizedTest.cs @@ -22,46 +22,28 @@ You should have received a copy of the GNU Affero General Public License */ using System; using System.Collections.Generic; -using System.Linq; using iText.Commons.Utils; using iText.Kernel.Exceptions; using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Colorspace.Shading; using iText.Test; namespace iText.Kernel.Pdf.Colorspace { [NUnit.Framework.Category("UnitTest")] - [NUnit.Framework.TestFixtureSource("ParametersTestFixtureData")] public class PdfShadingParameterizedTest : ExtendedITextTest { - private readonly String shadingName; - - private readonly int shadingType; - - public PdfShadingParameterizedTest(Object name, Object type) { - shadingName = (String)name; - shadingType = (int)type; - } - - public PdfShadingParameterizedTest(Object[] array) - : this(array[0], array[1]) { - } - public static IEnumerable Parameters() { return JavaUtil.ArraysAsList(new Object[][] { new Object[] { "FreeFormGouraudShadedTriangleMesh", 4 }, new Object[] { "LatticeFormGouraudShadedTriangleMesh", 5 }, new Object[] { "CoonsPatchMesh", 6 }, new Object [] { "TensorProductPatchMesh", 7 } }); } - public static ICollection ParametersTestFixtureData() { - return Parameters().Select(array => new NUnit.Framework.TestFixtureData(array)).ToList(); - } - - [NUnit.Framework.Test] - public virtual void AllAboveType3FromDictionaryShouldFailTest() { + [NUnit.Framework.TestCaseSource("Parameters")] + public virtual void AllAboveType3FromDictionaryShouldFailTest(String shadingName, int shadingType) { PdfDictionary dict = new PdfDictionary(); dict.Put(PdfName.ShadingType, new PdfNumber(shadingType)); dict.Put(PdfName.ColorSpace, PdfName.DeviceRGB); - Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => PdfShading.MakeShading(dict), "Creating " - + shadingName + " should throw PdfException."); + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => AbstractPdfShading.MakeShading(dict + ), "Creating " + shadingName + " should throw PdfException."); NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.UNEXPECTED_SHADING_TYPE, e.Message); } } diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/colorspace/PdfShadingTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/colorspace/PdfShadingTest.cs index fed9ffc8d5..13a23f698f 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/colorspace/PdfShadingTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/colorspace/PdfShadingTest.cs @@ -23,6 +23,7 @@ You should have received a copy of the GNU Affero General Public License using System; using iText.Kernel.Exceptions; using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Colorspace.Shading; using iText.Kernel.Pdf.Function; using iText.Test; @@ -33,8 +34,8 @@ public class PdfShadingTest : ExtendedITextTest { public virtual void AxialShadingConstructorNullExtendArgumentTest() { bool[] extendArray = null; PdfDeviceCs.Rgb color = new PdfDeviceCs.Rgb(); - Exception e = NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => new PdfShading.Axial(color, 0f - , 0f, new float[] { 0f, 0f, 0f }, 0.5f, 0.5f, new float[] { 0.5f, 0.5f, 0.5f }, extendArray)); + Exception e = NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => new PdfAxialShading(color, 0f, + 0f, new float[] { 0f, 0f, 0f }, 0.5f, 0.5f, new float[] { 0.5f, 0.5f, 0.5f }, extendArray)); NUnit.Framework.Assert.AreEqual("extend", e.Message); } @@ -42,8 +43,8 @@ public virtual void AxialShadingConstructorNullExtendArgumentTest() { public virtual void AxialShadingConstructorInvalidExtendArgumentTest() { bool[] extendArray = new bool[] { true }; PdfDeviceCs.Rgb color = new PdfDeviceCs.Rgb(); - Exception e = NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => new PdfShading.Axial(color, 0f - , 0f, new float[] { 0f, 0f, 0f }, 0.5f, 0.5f, new float[] { 0.5f, 0.5f, 0.5f }, extendArray)); + Exception e = NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => new PdfAxialShading(color, 0f, + 0f, new float[] { 0f, 0f, 0f }, 0.5f, 0.5f, new float[] { 0.5f, 0.5f, 0.5f }, extendArray)); NUnit.Framework.Assert.AreEqual("extend", e.Message); } @@ -51,7 +52,7 @@ public virtual void AxialShadingConstructorInvalidExtendArgumentTest() { public virtual void RadialShadingConstructorNullExtendArgumentTest() { bool[] extendArray = null; PdfDeviceCs.Rgb color = new PdfDeviceCs.Rgb(); - Exception e = NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => new PdfShading.Radial(color, 0f + Exception e = NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => new PdfRadialShading(color, 0f , 0f, 0f, new float[] { 0f, 0f, 0f }, 0.5f, 0.5f, 10f, new float[] { 0.5f, 0.5f, 0.5f }, extendArray)); NUnit.Framework.Assert.AreEqual("extend", e.Message); } @@ -60,7 +61,7 @@ public virtual void RadialShadingConstructorNullExtendArgumentTest() { public virtual void RadialShadingConstructorInvalidExtendArgumentTest() { bool[] extendArray = new bool[] { true, false, false }; PdfDeviceCs.Rgb color = new PdfDeviceCs.Rgb(); - Exception e = NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => new PdfShading.Radial(color, 0f + Exception e = NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => new PdfRadialShading(color, 0f , 0f, 0f, new float[] { 0f, 0f, 0f }, 0.5f, 0.5f, 10f, new float[] { 0.5f, 0.5f, 0.5f }, extendArray)); NUnit.Framework.Assert.AreEqual("extend", e.Message); } @@ -70,13 +71,13 @@ public virtual void AxialShadingGettersTest() { float[] coordsArray = new float[] { 0f, 0f, 0.5f, 0.5f }; float[] domainArray = new float[] { 0f, 0.8f }; bool[] extendArray = new bool[] { true, false }; - PdfDictionary axialShadingDictionary = InitShadingDictionary(coordsArray, domainArray, extendArray, PdfShading.ShadingType + PdfDictionary axialShadingDictionary = InitShadingDictionary(coordsArray, domainArray, extendArray, ShadingType .AXIAL); - PdfShading.Axial axial = new PdfShading.Axial(axialShadingDictionary); + PdfAxialShading axial = new PdfAxialShading(axialShadingDictionary); iText.Test.TestUtil.AreEqual(coordsArray, axial.GetCoords().ToFloatArray(), 0f); iText.Test.TestUtil.AreEqual(domainArray, axial.GetDomain().ToFloatArray(), 0f); NUnit.Framework.Assert.AreEqual(extendArray, axial.GetExtend().ToBooleanArray()); - NUnit.Framework.Assert.AreEqual(PdfShading.ShadingType.AXIAL, axial.GetShadingType()); + NUnit.Framework.Assert.AreEqual(ShadingType.AXIAL, axial.GetShadingType()); NUnit.Framework.Assert.AreEqual(PdfName.DeviceRGB, axial.GetColorSpace()); } @@ -85,9 +86,9 @@ public virtual void SetFunctionsTest() { float[] coordsArray = new float[] { 0f, 0f, 0.5f, 0.5f }; float[] domainArray = new float[] { 0f, 0.8f }; bool[] extendArray = new bool[] { true, false }; - PdfDictionary axialShadingDictionary = InitShadingDictionary(coordsArray, domainArray, extendArray, PdfShading.ShadingType + PdfDictionary axialShadingDictionary = InitShadingDictionary(coordsArray, domainArray, extendArray, ShadingType .AXIAL); - PdfShading.Axial axial = new PdfShading.Axial(axialShadingDictionary); + PdfAxialShading axial = new PdfAxialShading(axialShadingDictionary); NUnit.Framework.Assert.IsTrue(axial.GetFunction() is PdfDictionary); byte[] ps = "{2 copy sin abs sin abs 3 index 10 mul sin 1 sub abs}".GetBytes(iText.Commons.Utils.EncodingUtil.ISO_8859_1 ); @@ -106,13 +107,13 @@ public virtual void AxialShadingViaPdfObjectTest() { float[] coordsArray = new float[] { 0f, 0f, 0.5f, 0.5f }; float[] domainArray = new float[] { 0f, 0.8f }; bool[] extendArray = new bool[] { true, false }; - PdfDictionary axialShadingDictionary = InitShadingDictionary(coordsArray, domainArray, extendArray, PdfShading.ShadingType + PdfDictionary axialShadingDictionary = InitShadingDictionary(coordsArray, domainArray, extendArray, ShadingType .AXIAL); - PdfShading.Axial axial = (PdfShading.Axial)PdfShading.MakeShading(axialShadingDictionary); + PdfAxialShading axial = (PdfAxialShading)AbstractPdfShading.MakeShading(axialShadingDictionary); iText.Test.TestUtil.AreEqual(coordsArray, axial.GetCoords().ToFloatArray(), 0f); iText.Test.TestUtil.AreEqual(domainArray, axial.GetDomain().ToFloatArray(), 0f); NUnit.Framework.Assert.AreEqual(extendArray, axial.GetExtend().ToBooleanArray()); - NUnit.Framework.Assert.AreEqual(PdfShading.ShadingType.AXIAL, axial.GetShadingType()); + NUnit.Framework.Assert.AreEqual(ShadingType.AXIAL, axial.GetShadingType()); } [NUnit.Framework.Test] @@ -120,13 +121,12 @@ public virtual void AxialShadingGettersWithDomainExtendDefaultValuesTest() { float[] coordsArray = new float[] { 0f, 0f, 0.5f, 0.5f }; float[] defaultDomainArray = new float[] { 0f, 1f }; bool[] defaultExtendArray = new bool[] { false, false }; - PdfDictionary axialShadingDictionary = InitShadingDictionary(coordsArray, null, null, PdfShading.ShadingType - .AXIAL); - PdfShading.Axial axial = new PdfShading.Axial(axialShadingDictionary); + PdfDictionary axialShadingDictionary = InitShadingDictionary(coordsArray, null, null, ShadingType.AXIAL); + PdfAxialShading axial = new PdfAxialShading(axialShadingDictionary); iText.Test.TestUtil.AreEqual(coordsArray, axial.GetCoords().ToFloatArray(), 0f); iText.Test.TestUtil.AreEqual(defaultDomainArray, axial.GetDomain().ToFloatArray(), 0f); NUnit.Framework.Assert.AreEqual(defaultExtendArray, axial.GetExtend().ToBooleanArray()); - NUnit.Framework.Assert.AreEqual(PdfShading.ShadingType.AXIAL, axial.GetShadingType()); + NUnit.Framework.Assert.AreEqual(ShadingType.AXIAL, axial.GetShadingType()); } [NUnit.Framework.Test] @@ -134,13 +134,13 @@ public virtual void RadialShadingGettersTest() { float[] coordsArray = new float[] { 0f, 0f, 0f, 0.5f, 0.5f, 10f }; float[] domainArray = new float[] { 0f, 0.8f }; bool[] extendArray = new bool[] { true, false }; - PdfDictionary radialShadingDictionary = InitShadingDictionary(coordsArray, domainArray, extendArray, PdfShading.ShadingType + PdfDictionary radialShadingDictionary = InitShadingDictionary(coordsArray, domainArray, extendArray, ShadingType .RADIAL); - PdfShading.Radial radial = new PdfShading.Radial(radialShadingDictionary); + PdfRadialShading radial = new PdfRadialShading(radialShadingDictionary); iText.Test.TestUtil.AreEqual(coordsArray, radial.GetCoords().ToFloatArray(), 0f); iText.Test.TestUtil.AreEqual(domainArray, radial.GetDomain().ToFloatArray(), 0f); NUnit.Framework.Assert.AreEqual(extendArray, radial.GetExtend().ToBooleanArray()); - NUnit.Framework.Assert.AreEqual(PdfShading.ShadingType.RADIAL, radial.GetShadingType()); + NUnit.Framework.Assert.AreEqual(ShadingType.RADIAL, radial.GetShadingType()); } [NUnit.Framework.Test] @@ -148,13 +148,13 @@ public virtual void RadialShadingViaMakeShadingTest() { float[] coordsArray = new float[] { 0f, 0f, 0f, 0.5f, 0.5f, 10f }; float[] domainArray = new float[] { 0f, 0.8f }; bool[] extendArray = new bool[] { true, false }; - PdfDictionary radialShadingDictionary = InitShadingDictionary(coordsArray, domainArray, extendArray, PdfShading.ShadingType + PdfDictionary radialShadingDictionary = InitShadingDictionary(coordsArray, domainArray, extendArray, ShadingType .RADIAL); - PdfShading.Radial radial = (PdfShading.Radial)PdfShading.MakeShading(radialShadingDictionary); + PdfRadialShading radial = (PdfRadialShading)AbstractPdfShading.MakeShading(radialShadingDictionary); iText.Test.TestUtil.AreEqual(coordsArray, radial.GetCoords().ToFloatArray(), 0f); iText.Test.TestUtil.AreEqual(domainArray, radial.GetDomain().ToFloatArray(), 0f); NUnit.Framework.Assert.AreEqual(extendArray, radial.GetExtend().ToBooleanArray()); - NUnit.Framework.Assert.AreEqual(PdfShading.ShadingType.RADIAL, radial.GetShadingType()); + NUnit.Framework.Assert.AreEqual(ShadingType.RADIAL, radial.GetShadingType()); } [NUnit.Framework.Test] @@ -162,20 +162,20 @@ public virtual void RadialShadingGettersWithDomainExtendDefaultValuesTest() { float[] coordsArray = new float[] { 0f, 0f, 0f, 0.5f, 0.5f, 10f }; float[] defaultDomainArray = new float[] { 0f, 1f }; bool[] defaultExtendArray = new bool[] { false, false }; - PdfDictionary radialShadingDictionary = InitShadingDictionary(coordsArray, null, null, PdfShading.ShadingType - .RADIAL); - PdfShading.Radial radial = new PdfShading.Radial(radialShadingDictionary); + PdfDictionary radialShadingDictionary = InitShadingDictionary(coordsArray, null, null, ShadingType.RADIAL); + PdfRadialShading radial = new PdfRadialShading(radialShadingDictionary); iText.Test.TestUtil.AreEqual(coordsArray, radial.GetCoords().ToFloatArray(), 0f); iText.Test.TestUtil.AreEqual(defaultDomainArray, radial.GetDomain().ToFloatArray(), 0f); NUnit.Framework.Assert.AreEqual(defaultExtendArray, radial.GetExtend().ToBooleanArray()); - NUnit.Framework.Assert.AreEqual(PdfShading.ShadingType.RADIAL, radial.GetShadingType()); + NUnit.Framework.Assert.AreEqual(ShadingType.RADIAL, radial.GetShadingType()); } [NUnit.Framework.Test] public virtual void MakeShadingShouldFailOnMissingShadeType() { PdfDictionary shade = new PdfDictionary(); shade.Put(PdfName.ColorSpace, new PdfArray()); - Exception error = NUnit.Framework.Assert.Catch(typeof(PdfException), () => PdfShading.MakeShading(shade)); + Exception error = NUnit.Framework.Assert.Catch(typeof(PdfException), () => AbstractPdfShading.MakeShading( + shade)); NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.SHADING_TYPE_NOT_FOUND, error.Message); } @@ -183,7 +183,8 @@ public virtual void MakeShadingShouldFailOnMissingShadeType() { public virtual void MakeShadingShouldFailOnMissingColorSpace() { PdfDictionary shade = new PdfDictionary(); shade.Put(PdfName.ShadingType, new PdfArray()); - Exception error = NUnit.Framework.Assert.Catch(typeof(PdfException), () => PdfShading.MakeShading(shade)); + Exception error = NUnit.Framework.Assert.Catch(typeof(PdfException), () => AbstractPdfShading.MakeShading( + shade)); NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.COLOR_SPACE_NOT_FOUND, error.Message); } @@ -194,8 +195,8 @@ public virtual void UsingPatternColorSpaceThrowsException() { IPdfFunction function = new PdfType4Function(new float[] { 0, 1000, 0, 1000 }, new float[] { 0, 1, 0, 1, 0 , 1 }, ps); PdfSpecialCs.Pattern colorSpace = new PdfSpecialCs.Pattern(); - Exception ex = NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => new PdfShading.FunctionBased( - colorSpace, function)); + Exception ex = NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => new PdfFunctionBasedShading(colorSpace + , function)); NUnit.Framework.Assert.AreEqual("colorSpace", ex.Message); } @@ -206,7 +207,7 @@ public virtual void MakeShadingFunctionBased1Test() { float[] domain = new float[] { 0, 1000, 0, 1000 }; float[] range = new float[] { 0, 1, 0, 1, 0, 1 }; IPdfFunction function = new PdfType4Function(domain, range, ps); - PdfShading.FunctionBased shade = new PdfShading.FunctionBased(new PdfDeviceCs.Rgb(), function); + PdfFunctionBasedShading shade = new PdfFunctionBasedShading(new PdfDeviceCs.Rgb(), function); PdfDictionary @object = shade.GetPdfObject(); NUnit.Framework.Assert.AreEqual(1, @object.GetAsInt(PdfName.ShadingType).Value); NUnit.Framework.Assert.AreEqual(PdfName.DeviceRGB, @object.GetAsName(PdfName.ColorSpace)); @@ -234,7 +235,7 @@ public virtual void MakeShadingFunctionBased2Test() { shadingDict.Put(PdfName.Function, stream); stream.SetData(ps); shadingDict.Put(PdfName.Function, stream); - PdfShading shade = PdfShading.MakeShading(shadingDict); + AbstractPdfShading shade = AbstractPdfShading.MakeShading(shadingDict); PdfDictionary @object = shade.GetPdfObject(); NUnit.Framework.Assert.AreEqual(1, @object.GetAsInt(PdfName.ShadingType).Value); NUnit.Framework.Assert.AreEqual(PdfName.DeviceRGB, @object.GetAsName(PdfName.ColorSpace)); @@ -251,7 +252,7 @@ public virtual void MakeShadingFunctionBased2Test() { public virtual void MakeShadingWithInvalidShadeType() { float[] coordsArray = new float[] { 0f, 0f, 0f, 0.5f, 0.5f, 10f }; PdfDictionary radialShadingDictionary = InitShadingDictionary(coordsArray, null, null, 21); - Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => PdfShading.MakeShading(radialShadingDictionary + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => AbstractPdfShading.MakeShading(radialShadingDictionary )); NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.UNEXPECTED_SHADING_TYPE, e.Message); } @@ -273,7 +274,7 @@ public virtual void MakeFreeFormGouraudShadedTriangleMeshTest() { stream.Put(PdfName.Decode, new PdfArray(new float[] { x, x + side, y, y + (int)(side * Math.Sin(Math.PI / 3)), 0, 1, 0, 1, 0, 1 })); stream.Put(PdfName.Matrix, new PdfArray(new float[] { 1, 0, 0, -1, 0, 0 })); - PdfShading.FreeFormGouraudShadedTriangleMesh shade = (PdfShading.FreeFormGouraudShadedTriangleMesh)PdfShading + PdfFreeFormGouraudShadedTriangleShading shade = (PdfFreeFormGouraudShadedTriangleShading)AbstractPdfShading .MakeShading(stream); NUnit.Framework.Assert.AreEqual(PdfName.DeviceRGB, shade.GetColorSpace()); NUnit.Framework.Assert.AreEqual(4, shade.GetShadingType()); @@ -300,7 +301,7 @@ public virtual void MakeLatticeFormGouraudShadedTriangleMeshTest() { stream.Put(PdfName.Decode, new PdfArray(new float[] { x, x + side, y, y + (int)(side * Math.Sin(Math.PI / 3)), 0, 1, 0, 1, 0, 1 })); stream.Put(PdfName.Matrix, new PdfArray(new float[] { 1, 0, 0, -1, 0, 0 })); - PdfShading.LatticeFormGouraudShadedTriangleMesh shade = (PdfShading.LatticeFormGouraudShadedTriangleMesh)PdfShading + PdfLatticeFormGouraudShadedTriangleShading shade = (PdfLatticeFormGouraudShadedTriangleShading)AbstractPdfShading .MakeShading(stream); NUnit.Framework.Assert.AreEqual(PdfName.DeviceRGB, shade.GetColorSpace()); NUnit.Framework.Assert.AreEqual(5, shade.GetShadingType()); @@ -385,7 +386,7 @@ public virtual void CoonsPatchMeshGradientTest() { stream.Put(PdfName.Decode, new PdfArray(new float[] { x, x + side, y, y + (int)(side * Math.Sin(Math.PI / 3)), 0, 1, 0, 1, 0, 1 })); stream.Put(PdfName.Matrix, new PdfArray(new float[] { 1, 0, 0, -1, 0, 0 })); - PdfShading.CoonsPatchMesh shade = (PdfShading.CoonsPatchMesh)PdfShading.MakeShading(stream); + PdfCoonsPatchShading shade = (PdfCoonsPatchShading)AbstractPdfShading.MakeShading(stream); NUnit.Framework.Assert.AreEqual(PdfName.DeviceRGB, shade.GetColorSpace()); NUnit.Framework.Assert.AreEqual(6, shade.GetShadingType()); NUnit.Framework.Assert.AreEqual(32, shade.GetBitsPerCoordinate()); @@ -485,8 +486,7 @@ public virtual void TensorProductPatchMeshShadingTest() { stream.Put(PdfName.Decode, new PdfArray(new float[] { x, x + side, y, y + (int)(side * Math.Sin(Math.PI / 3)), 0, 1, 0, 1, 0, 1 })); stream.Put(PdfName.Matrix, new PdfArray(new float[] { -1, 0, 0, 1, 0, 0 })); - PdfShading.TensorProductPatchMesh shade = (PdfShading.TensorProductPatchMesh)PdfShading.MakeShading(stream - ); + PdfTensorProductPatchShading shade = (PdfTensorProductPatchShading)AbstractPdfShading.MakeShading(stream); NUnit.Framework.Assert.AreEqual(PdfName.DeviceRGB, shade.GetColorSpace()); NUnit.Framework.Assert.AreEqual(7, shade.GetShadingType()); NUnit.Framework.Assert.AreEqual(32, shade.GetBitsPerCoordinate()); @@ -500,10 +500,133 @@ public virtual void InvalidShadingTypeShouldFailTest() { PdfDictionary dict = new PdfDictionary(); dict.Put(PdfName.ShadingType, new PdfNumber(8)); dict.Put(PdfName.ColorSpace, PdfName.DeviceRGB); - Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => PdfShading.MakeShading(dict)); + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => AbstractPdfShading.MakeShading(dict + )); NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.UNEXPECTED_SHADING_TYPE, e.Message); } + [NUnit.Framework.Test] + public virtual void BasicCoonsPathMeshTest() { + int x = 36; + int y = 400; + int side = 500; + PdfArray decode = new PdfArray(new float[] { x, x + side, y, y + (int)(side * Math.Sin(Math.PI / 3)), 0, 1 + , 0, 1, 0, 1 }); + PdfColorSpace cs = PdfColorSpace.MakeColorSpace(PdfName.DeviceRGB); + PdfCoonsPatchShading coonsPatchMesh = new PdfCoonsPatchShading(cs, 32, 16, 8, decode); + NUnit.Framework.Assert.AreEqual(PdfName.DeviceRGB, coonsPatchMesh.GetColorSpace()); + NUnit.Framework.Assert.AreEqual(6, coonsPatchMesh.GetShadingType()); + NUnit.Framework.Assert.AreEqual(32, coonsPatchMesh.GetBitsPerCoordinate()); + NUnit.Framework.Assert.AreEqual(16, coonsPatchMesh.GetBitsPerComponent()); + NUnit.Framework.Assert.AreEqual(8, coonsPatchMesh.GetBitsPerFlag()); + NUnit.Framework.Assert.AreEqual(y, coonsPatchMesh.GetDecode().GetAsNumber(2).IntValue()); + } + + [NUnit.Framework.Test] + public virtual void BasicFreeFormGouraudShadedTriangleMeshTest() { + int x = 36; + int y = 400; + int side = 500; + PdfArray pdfArray = new PdfArray(new float[] { x, x + side, y, y + (int)(side * Math.Sin(Math.PI / 3)), 0, + 1, 0, 1, 0, 1 }); + PdfColorSpace cs = PdfColorSpace.MakeColorSpace(PdfName.DeviceRGB); + PdfFreeFormGouraudShadedTriangleShading shade = new PdfFreeFormGouraudShadedTriangleShading(cs, 32, 8, 8, + pdfArray); + NUnit.Framework.Assert.AreEqual(PdfName.DeviceRGB, shade.GetColorSpace()); + NUnit.Framework.Assert.AreEqual(4, shade.GetShadingType()); + NUnit.Framework.Assert.AreEqual(32, shade.GetBitsPerCoordinate()); + NUnit.Framework.Assert.AreEqual(8, shade.GetBitsPerComponent()); + NUnit.Framework.Assert.AreEqual(8, shade.GetBitsPerFlag()); + NUnit.Framework.Assert.AreEqual(y, shade.GetDecode().GetAsNumber(2).IntValue()); + } + + [NUnit.Framework.Test] + public virtual void BasicTensorProductPatchMeshTest() { + int x = 36; + int y = 400; + int side = 500; + PdfArray pdfArray = new PdfArray(new float[] { x, x + side, y, y + (int)(side * Math.Sin(Math.PI / 3)), 0, + 1, 0, 1, 0, 1 }); + PdfColorSpace cs = PdfColorSpace.MakeColorSpace(PdfName.DeviceRGB); + PdfTensorProductPatchShading shade = new PdfTensorProductPatchShading(cs, 32, 8, 8, pdfArray); + NUnit.Framework.Assert.AreEqual(PdfName.DeviceRGB, shade.GetColorSpace()); + NUnit.Framework.Assert.AreEqual(7, shade.GetShadingType()); + NUnit.Framework.Assert.AreEqual(32, shade.GetBitsPerCoordinate()); + NUnit.Framework.Assert.AreEqual(8, shade.GetBitsPerComponent()); + NUnit.Framework.Assert.AreEqual(8, shade.GetBitsPerFlag()); + NUnit.Framework.Assert.AreEqual(y, shade.GetDecode().GetAsNumber(2).IntValue()); + } + + [NUnit.Framework.Test] + public virtual void BasicLatticeFormGouraudShadedTriangleMeshTest() { + int x = 36; + int y = 400; + int side = 500; + PdfArray pdfArray = new PdfArray(new float[] { x, x + side, y, y + (int)(side * Math.Sin(Math.PI / 3)), 0, + 1, 0, 1, 0, 1 }); + PdfColorSpace cs = PdfColorSpace.MakeColorSpace(PdfName.DeviceRGB); + PdfLatticeFormGouraudShadedTriangleShading shade = new PdfLatticeFormGouraudShadedTriangleShading(cs, 32, + 8, 2, pdfArray); + NUnit.Framework.Assert.AreEqual(PdfName.DeviceRGB, shade.GetColorSpace()); + NUnit.Framework.Assert.AreEqual(5, shade.GetShadingType()); + NUnit.Framework.Assert.AreEqual(32, shade.GetBitsPerCoordinate()); + NUnit.Framework.Assert.AreEqual(8, shade.GetBitsPerComponent()); + NUnit.Framework.Assert.AreEqual(2, shade.GetVerticesPerRow()); + NUnit.Framework.Assert.AreEqual(y, shade.GetDecode().GetAsNumber(2).IntValue()); + } + + [NUnit.Framework.Test] + public virtual void BasicFunctionBasedShadingTest() { + byte[] ps = "{2 copy sin abs sin abs 3 index 10 mul sin 1 sub abs}".GetBytes(iText.Commons.Utils.EncodingUtil.ISO_8859_1 + ); + float[] domain = new float[] { 0, 1000, 0, 1000 }; + float[] range = new float[] { 0, 1, 0, 1, 0, 1 }; + float[] transformMatrix = new float[] { 1, 0, 0, 1, 0, 0 }; + IPdfFunction function = new PdfType4Function(domain, range, ps); + PdfColorSpace cs = PdfColorSpace.MakeColorSpace(PdfName.DeviceRGB); + PdfFunctionBasedShading shade = new PdfFunctionBasedShading(cs, function); + shade.SetDomain(1, 4, 1, 4); + shade.SetMatrix(transformMatrix); + NUnit.Framework.Assert.AreEqual(PdfName.DeviceRGB, shade.GetColorSpace()); + NUnit.Framework.Assert.AreEqual(1, shade.GetShadingType()); + NUnit.Framework.Assert.AreEqual(transformMatrix, shade.GetMatrix().ToFloatArray()); + NUnit.Framework.Assert.AreEqual(new float[] { 1, 4, 1, 4 }, shade.GetDomain().ToFloatArray()); + } + + [NUnit.Framework.Test] + public virtual void ChangeFreeFormGouraudShadedTriangleMeshTest() { + int x = 36; + int y = 400; + int side = 500; + float[] decode = new float[] { x, x + side, y, y + (int)(side * Math.Sin(Math.PI / 3)), 0, 1, 0, 1, 0, 1 }; + PdfColorSpace cs = PdfColorSpace.MakeColorSpace(PdfName.DeviceRGB); + PdfFreeFormGouraudShadedTriangleShading shade = new PdfFreeFormGouraudShadedTriangleShading(cs, 16, 8, 8, + new PdfArray()); + shade.SetDecode(decode); + shade.SetBitsPerComponent(16); + shade.SetBitsPerCoordinate(32); + shade.SetBitsPerFlag(4); + NUnit.Framework.Assert.AreEqual(PdfName.DeviceRGB, shade.GetColorSpace()); + NUnit.Framework.Assert.AreEqual(4, shade.GetShadingType()); + NUnit.Framework.Assert.AreEqual(32, shade.GetBitsPerCoordinate()); + NUnit.Framework.Assert.AreEqual(16, shade.GetBitsPerComponent()); + NUnit.Framework.Assert.AreEqual(4, shade.GetBitsPerFlag()); + NUnit.Framework.Assert.AreEqual(y, shade.GetDecode().GetAsNumber(2).IntValue()); + } + + [NUnit.Framework.Test] + public virtual void SetDecodeCoonsPatchMeshTest() { + int x = 36; + int y = 400; + int side = 500; + PdfArray decode = new PdfArray(new float[] { x, x + side, y, y + (int)(side * Math.Sin(Math.PI / 3)), 0, 1 + , 0, 1, 0, 1 }); + PdfColorSpace cs = PdfColorSpace.MakeColorSpace(PdfName.DeviceRGB); + PdfCoonsPatchShading coonsPatchMesh = new PdfCoonsPatchShading(cs, 32, 16, 16, new PdfArray()); + coonsPatchMesh.SetDecode(decode); + NUnit.Framework.Assert.AreEqual(y, coonsPatchMesh.GetDecode().GetAsNumber(2).IntValue()); + } + private static PdfDictionary InitShadingDictionary(float[] coordsArray, float[] domainArray, bool[] extendArray , int radial2) { PdfDictionary axialShadingDictionary = new PdfDictionary(); diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/event/PdfDocumentEventHandlingTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/event/PdfDocumentEventHandlingTest.cs new file mode 100644 index 0000000000..07e8de34fd --- /dev/null +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/event/PdfDocumentEventHandlingTest.cs @@ -0,0 +1,101 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System.IO; +using iText.Commons.Actions; +using iText.Kernel.Pdf; +using iText.Test; + +namespace iText.Kernel.Pdf.Event { + [NUnit.Framework.Category("UnitTest")] + public class PdfDocumentEventHandlingTest : ExtendedITextTest { + [NUnit.Framework.Test] + public virtual void SimplePdfDocumentEventTest() { + using (PdfDocument document = new PdfDocument(new PdfWriter(new MemoryStream()))) { + PdfDocumentEventHandlingTest.InsertPageHandler insertPageHandler = new PdfDocumentEventHandlingTest.InsertPageHandler + (); + document.AddEventHandler(PdfDocumentEvent.INSERT_PAGE, insertPageHandler); + document.AddNewPage(); + document.AddNewPage(); + NUnit.Framework.Assert.AreEqual(2, insertPageHandler.GetInsertedPagesCounter()); + } + } + + [NUnit.Framework.Test] + public virtual void GloballyRegisteredAbstractPdfDocumentEventHandlerTest() { + PdfDocumentEventHandlingTest.InsertPageHandler insertPageHandler = new PdfDocumentEventHandlingTest.InsertPageHandler + (); + insertPageHandler.AddType(PdfDocumentEvent.INSERT_PAGE); + EventManager.GetInstance().Register(insertPageHandler); + using (PdfDocument document = new PdfDocument(new PdfWriter(new MemoryStream()))) { + document.AddNewPage(); + } + // Events with specified PDF document are ignored. + NUnit.Framework.Assert.AreEqual(0, insertPageHandler.GetInsertedPagesCounter()); + EventManager.GetInstance().Unregister(insertPageHandler); + } + + [NUnit.Framework.Test] + public virtual void EventHandlerPerSeveralDocumentsTest() { + using (PdfDocument document1 = new PdfDocument(new PdfWriter(new MemoryStream()))) { + using (PdfDocument document2 = new PdfDocument(new PdfWriter(new MemoryStream()))) { + using (PdfDocument document3 = new PdfDocument(new PdfWriter(new MemoryStream()))) { + PdfDocumentEventHandlingTest.InsertPageHandler insertPageHandler = new PdfDocumentEventHandlingTest.InsertPageHandler + (); + document1.AddEventHandler(PdfDocumentEvent.INSERT_PAGE, insertPageHandler); + document2.AddEventHandler(PdfDocumentEvent.INSERT_PAGE, insertPageHandler); + document1.AddNewPage(); + document2.AddNewPage(); + document3.AddNewPage(); + NUnit.Framework.Assert.AreEqual(2, insertPageHandler.GetInsertedPagesCounter()); + document2.RemoveEventHandler(insertPageHandler); + document2.AddNewPage(); + NUnit.Framework.Assert.AreEqual(2, insertPageHandler.GetInsertedPagesCounter()); + } + } + } + } + + [NUnit.Framework.Test] + public virtual void NoDocumentSpecifiedForEventButHandlerIsGloballyRegisteredTest() { + PdfDocumentEventHandlingTest.InsertPageHandler insertPageHandler = new PdfDocumentEventHandlingTest.InsertPageHandler + (); + insertPageHandler.AddType(PdfDocumentEvent.INSERT_PAGE); + EventManager.GetInstance().Register(insertPageHandler); + EventManager.GetInstance().OnEvent(new PdfDocumentEvent(PdfDocumentEvent.INSERT_PAGE)); + EventManager.GetInstance().Unregister(insertPageHandler); + NUnit.Framework.Assert.AreEqual(1, insertPageHandler.GetInsertedPagesCounter()); + } + + private class InsertPageHandler : AbstractPdfDocumentEventHandler { + private int insertedPagesCounter = 0; + + public virtual int GetInsertedPagesCounter() { + return insertedPagesCounter; + } + + protected internal override void OnAcceptedEvent(AbstractPdfDocumentEvent @event) { + insertedPagesCounter++; + } + } + } +} diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/function/utils/SampleExtractorTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/function/utils/SampleExtractorTest.cs index 6cacc41814..f6d5019eb4 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/function/utils/SampleExtractorTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/function/utils/SampleExtractorTest.cs @@ -22,13 +22,11 @@ You should have received a copy of the GNU Affero General Public License */ using System; using System.Collections.Generic; -using System.Linq; using iText.Commons.Utils; using iText.Test; namespace iText.Kernel.Pdf.Function.Utils { [NUnit.Framework.Category("IntegrationTest")] - [NUnit.Framework.TestFixtureSource("SamplesInfoTestFixtureData")] public class SampleExtractorTest : ExtendedITextTest { private const String PARAMETERS_NAME_PATTERN = "{0}bitsPerSample"; @@ -51,25 +49,8 @@ public static ICollection SamplesInfo() { 9 << 24) | (10 << 20) | (11 << 16) | (12 << 12) | (13 << 8) | (14 << 4) | 15 } } }); } - public static ICollection SamplesInfoTestFixtureData() { - return SamplesInfo().Select(array => new NUnit.Framework.TestFixtureData(array)).ToList(); - } - - private readonly int bitsPerSample; - - private readonly long[] expected; - - public SampleExtractorTest(Object bitsPerSample, Object expected) { - this.bitsPerSample = (int)bitsPerSample; - this.expected = (long[])expected; - } - - public SampleExtractorTest(Object[] array) - : this(array[0], array[1]) { - } - - [NUnit.Framework.Test] - public virtual void TestSamplesExtraction() { + [NUnit.Framework.TestCaseSource("SamplesInfo")] + public virtual void TestSamplesExtraction(int bitsPerSample, long[] expected) { long[] actual = new long[(SAMPLES.Length << 3) / bitsPerSample]; NUnit.Framework.Assert.AreEqual(expected.Length, actual.Length); AbstractSampleExtractor extractor = AbstractSampleExtractor.CreateExtractor(bitsPerSample); diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/layer/PdfLayerTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/layer/PdfLayerTest.cs index b529d1b5dd..7f532ececb 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/layer/PdfLayerTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/layer/PdfLayerTest.cs @@ -24,9 +24,14 @@ You should have received a copy of the GNU Affero General Public License using System.Collections.Generic; using iText.Commons.Utils; using iText.IO.Font.Constants; +using iText.IO.Source; +using iText.Kernel.Exceptions; using iText.Kernel.Font; +using iText.Kernel.Geom; using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Annot; using iText.Kernel.Pdf.Canvas; +using iText.Kernel.Pdf.Xobject; using iText.Kernel.Utils; using iText.Test; @@ -354,5 +359,128 @@ public virtual void TestInStamperMode2() { NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + "output_layered.pdf", sourceFolder + "cmp_output_layered.pdf", destinationFolder, "diff")); } + + [NUnit.Framework.Test] + public virtual void TestReadAllLayersFromPage1() { + PdfDocument pdfDoc = new PdfDocument(new PdfReader(sourceFolder + "input_layered.pdf"), CompareTool.CreateTestPdfWriter + (destinationFolder + "output_layered_2.pdf")); + PdfCanvas canvas = new PdfCanvas(pdfDoc, 1); + //create layer on page + PdfLayer newLayer = new PdfLayer("appended", pdfDoc); + canvas.SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.HELVETICA), 18); + PdfLayerTestUtils.AddTextInsideLayer(newLayer, canvas, "APPENDED CONTENT", 200, 600); + IList layersFromCatalog = pdfDoc.GetCatalog().GetOCProperties(true).GetLayers(); + NUnit.Framework.Assert.AreEqual(13, layersFromCatalog.Count); + PdfPage page = pdfDoc.GetPage(1); + ICollection layersFromPage = page.GetPdfLayers(); + NUnit.Framework.Assert.AreEqual(11, layersFromPage.Count); + pdfDoc.Close(); + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + "output_layered_2.pdf" + , sourceFolder + "cmp_output_layered_2.pdf", destinationFolder, "diff")); + } + + [NUnit.Framework.Test] + public virtual void TestReadAllLayersFromDocumentWithComplexOCG() { + PdfDocument pdfDoc = new PdfDocument(new PdfReader(sourceFolder + "input_complex_layers.pdf"), CompareTool + .CreateTestPdfWriter(destinationFolder + "output_complex_layers.pdf")); + IList layersFromCatalog = pdfDoc.GetCatalog().GetOCProperties(true).GetLayers(); + NUnit.Framework.Assert.AreEqual(12, layersFromCatalog.Count); + PdfPage page = pdfDoc.GetPage(1); + ICollection layersFromPage = page.GetPdfLayers(); + NUnit.Framework.Assert.AreEqual(10, layersFromPage.Count); + pdfDoc.Close(); + } + + //Read OCGs from different locations (annotations, content streams, xObjects) test block + [NUnit.Framework.Test] + public virtual void TestReadOcgFromStreamProperties() { + using (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + using (PdfDocument document = new PdfDocument(new PdfWriter(outputStream))) { + PdfPage page = document.AddNewPage(); + PdfResources pdfResource = page.GetResources(); + pdfResource.AddProperties(new PdfLayer("name", document).GetPdfObject()); + pdfResource.MakeIndirect(document); + ICollection layersFromPage = page.GetPdfLayers(); + NUnit.Framework.Assert.AreEqual(1, layersFromPage.Count); + } + } + } + + [NUnit.Framework.Test] + public virtual void TestReadOcgFromAnnotation() { + using (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + using (PdfDocument fromDocument = new PdfDocument(new PdfWriter(outputStream))) { + PdfPage page = fromDocument.AddNewPage(); + PdfAnnotation annotation = new PdfTextAnnotation(new Rectangle(50, 10)); + annotation.SetLayer(new PdfLayer("name", fromDocument)); + page.AddAnnotation(annotation); + ICollection layersFromPage = page.GetPdfLayers(); + NUnit.Framework.Assert.AreEqual(1, layersFromPage.Count); + } + } + } + + [NUnit.Framework.Test] + public virtual void TestReadOcgFromFlushedAnnotation() { + using (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + using (PdfDocument fromDocument = new PdfDocument(new PdfWriter(outputStream))) { + PdfPage page = fromDocument.AddNewPage(); + PdfAnnotation annotation = new PdfTextAnnotation(new Rectangle(50, 10)); + annotation.SetLayer(new PdfLayer("name", fromDocument)); + page.AddAnnotation(annotation); + annotation.Flush(); + ICollection layersFromPage = page.GetPdfLayers(); + NUnit.Framework.Assert.AreEqual(1, layersFromPage.Count); + } + } + } + + [NUnit.Framework.Test] + public virtual void TestReadOcgFromApAnnotation() { + using (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + using (PdfDocument fromDocument = new PdfDocument(new PdfWriter(outputStream))) { + PdfPage page = fromDocument.AddNewPage(); + PdfAnnotation annotation = new PdfTextAnnotation(new Rectangle(50, 10)); + PdfFormXObject formXObject = new PdfFormXObject(new Rectangle(50, 10)); + formXObject.SetLayer(new PdfLayer("someName1", fromDocument)); + formXObject.MakeIndirect(fromDocument); + PdfDictionary nDict = new PdfDictionary(); + nDict.Put(PdfName.ON, formXObject.GetPdfObject()); + annotation.SetAppearance(PdfName.N, nDict); + formXObject = new PdfFormXObject(new Rectangle(50, 10)); + formXObject.SetLayer(new PdfLayer("someName2", fromDocument)); + PdfResources formResources = formXObject.GetResources(); + formResources.AddProperties(new PdfLayer("someName3", fromDocument).GetPdfObject()); + formXObject.MakeIndirect(fromDocument); + PdfDictionary rDict = new PdfDictionary(); + rDict.Put(PdfName.OFF, formXObject.GetPdfObject()); + annotation.SetAppearance(PdfName.R, rDict); + formXObject = new PdfFormXObject(new Rectangle(50, 10)); + formXObject.SetLayer(new PdfLayer("someName4", fromDocument)); + formXObject.MakeIndirect(fromDocument); + annotation.SetAppearance(PdfName.D, formXObject.GetPdfObject()); + page.AddAnnotation(annotation); + ICollection layersFromPage = page.GetPdfLayers(); + NUnit.Framework.Assert.AreEqual(4, layersFromPage.Count); + } + } + } + + //TODO DEVSIX-8490 remove this test when implemented + [NUnit.Framework.Test] + public virtual void AddSecondParentlayerTest() { + using (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + using (PdfDocument doc = new PdfDocument(new PdfWriter(outputStream))) { + PdfLayer childLayer = new PdfLayer("childLayer", doc); + PdfLayer parentLayer1 = new PdfLayer("firstParentLayer", doc); + PdfLayer parentLayer2 = new PdfLayer("secondParentLayer", doc); + parentLayer1.AddChild(childLayer); + PdfIndirectReference @ref = childLayer.GetIndirectReference(); + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => parentLayer2.AddChild(childLayer)); + NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(KernelExceptionMessageConstant.UNABLE_TO_ADD_SECOND_PARENT_LAYER + , @ref.ToString()), e.Message); + } + } + } } } diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/layer/PdfOCPropertiesUnitTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/layer/PdfOCPropertiesUnitTest.cs new file mode 100644 index 0000000000..f2a257799f --- /dev/null +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/layer/PdfOCPropertiesUnitTest.cs @@ -0,0 +1,110 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using System.IO; +using iText.Commons.Utils; +using iText.IO.Source; +using iText.Kernel.Exceptions; +using iText.Kernel.Pdf; + +namespace iText.Kernel.Pdf.Layer { + [NUnit.Framework.Category("UnitTest")] + public class PdfOCPropertiesUnitTest { + //TODO DEVSIX-8490 remove this test when implemented + [NUnit.Framework.Test] + public virtual void RemoveOrderDuplicatesTest() { + byte[] docBytes; + using (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + using (PdfDocument document = new PdfDocument(new PdfWriter(outputStream))) { + PdfDictionary ocgDic = new PdfDictionary(); + ocgDic.MakeIndirect(document); + PdfArray orderArray = new PdfArray(); + for (int i = 0; i < 3; i++) { + orderArray.Add(ocgDic); + } + PdfDictionary ocgDic2 = new PdfDictionary(); + ocgDic.MakeIndirect(document); + for (int i = 0; i < 3; i++) { + PdfArray layerArray = new PdfArray(); + layerArray.Add(new PdfString("layerName" + i)); + layerArray.Add(ocgDic2); + orderArray.Add(layerArray); + } + PdfDictionary DDictionary = new PdfDictionary(); + DDictionary.Put(PdfName.Order, orderArray); + PdfArray OCGsArray = new PdfArray(); + OCGsArray.Add(ocgDic); + OCGsArray.Add(ocgDic2); + PdfDictionary OCPropertiesDic = new PdfDictionary(); + OCPropertiesDic.Put(PdfName.D, DDictionary); + OCPropertiesDic.Put(PdfName.OCGs, OCGsArray); + document.GetCatalog().GetPdfObject().Put(PdfName.OCProperties, OCPropertiesDic); + document.GetCatalog().GetOCProperties(false); + } + docBytes = outputStream.ToArray(); + } + using (PdfDocument docReopen = new PdfDocument(new PdfReader(new MemoryStream(docBytes)))) { + PdfArray resultArray = docReopen.GetCatalog().GetPdfObject().GetAsDictionary(PdfName.OCProperties).GetAsDictionary + (PdfName.D).GetAsArray(PdfName.Order); + NUnit.Framework.Assert.AreEqual(2, resultArray.Size()); + } + } + + //TODO DEVSIX-8490 remove this test when implemented + [NUnit.Framework.Test] + public virtual void RemoveOrderDuplicateHasChildTest() { + using (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + using (PdfDocument document = new PdfDocument(new PdfWriter(outputStream))) { + PdfDictionary ocgDic = new PdfDictionary(); + PdfDictionary ocgDicChild1 = new PdfDictionary(); + PdfDictionary ocgDicChild2 = new PdfDictionary(); + ocgDic.MakeIndirect(document); + PdfArray orderArray = new PdfArray(); + PdfArray childArray1 = new PdfArray(); + childArray1.Add(ocgDicChild1); + PdfArray childArray2 = new PdfArray(); + childArray2.Add(ocgDicChild2); + orderArray.Add(ocgDic); + orderArray.Add(childArray1); + orderArray.Add(ocgDic); + orderArray.Add(childArray2); + PdfDictionary DDictionary = new PdfDictionary(); + DDictionary.Put(PdfName.Order, orderArray); + PdfArray OCGsArray = new PdfArray(); + OCGsArray.Add(ocgDic); + OCGsArray.Add(ocgDicChild1); + OCGsArray.Add(ocgDicChild2); + PdfDictionary OCPropertiesDic = new PdfDictionary(); + OCPropertiesDic.Put(PdfName.D, DDictionary); + OCPropertiesDic.Put(PdfName.OCGs, OCGsArray); + document.GetCatalog().GetPdfObject().Put(PdfName.OCProperties, OCPropertiesDic); + PdfIndirectReference @ref = ocgDic.GetIndirectReference(); + PdfCatalog catalog = document.GetCatalog(); + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => catalog.GetOCProperties(false)); + NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(KernelExceptionMessageConstant.UNABLE_TO_REMOVE_DUPLICATE_LAYER + , @ref.ToString()), e.Message); + } + } + } + } +} diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/tagutils/AccessibilityPropertiesTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/tagutils/AccessibilityPropertiesTest.cs index ba5eb86bc3..a9bb75806b 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/tagutils/AccessibilityPropertiesTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/tagutils/AccessibilityPropertiesTest.cs @@ -30,7 +30,7 @@ namespace iText.Kernel.Pdf.Tagutils { public class AccessibilityPropertiesTest : ExtendedITextTest { [NUnit.Framework.Test] public virtual void SetAccessibilityPropertiesTest() { - AccessibilityProperties properties = new _AccessibilityProperties_43(); + AccessibilityProperties properties = new _AccessibilityProperties_42(); NUnit.Framework.Assert.IsNotNull(properties.SetRole(StandardRoles.DIV)); NUnit.Framework.Assert.IsNotNull(properties.SetLanguage("EN-GB")); NUnit.Framework.Assert.IsNotNull(properties.SetActualText("actualText")); @@ -48,14 +48,14 @@ public virtual void SetAccessibilityPropertiesTest() { NUnit.Framework.Assert.IsNotNull(properties.AddRef(new TagTreePointer(CreateTestDocument()))); } - private sealed class _AccessibilityProperties_43 : AccessibilityProperties { - public _AccessibilityProperties_43() { + private sealed class _AccessibilityProperties_42 : AccessibilityProperties { + public _AccessibilityProperties_42() { } } [NUnit.Framework.Test] public virtual void GetAccessibilityPropertiesTest() { - AccessibilityProperties properties = new _AccessibilityProperties_64(); + AccessibilityProperties properties = new _AccessibilityProperties_63(); NUnit.Framework.Assert.IsNull(properties.GetRole()); NUnit.Framework.Assert.IsNull(properties.GetLanguage()); NUnit.Framework.Assert.IsNull(properties.GetActualText()); @@ -66,8 +66,8 @@ public virtual void GetAccessibilityPropertiesTest() { NUnit.Framework.Assert.IsNull(properties.GetNamespace()); } - private sealed class _AccessibilityProperties_64 : AccessibilityProperties { - public _AccessibilityProperties_64() { + private sealed class _AccessibilityProperties_63 : AccessibilityProperties { + public _AccessibilityProperties_63() { } } diff --git a/itext.tests/itext.kernel.tests/itext/kernel/pdf/tagutils/TagTreeIteratorTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/pdf/tagutils/TagTreeIteratorTest.cs index 92325f73d6..ff5daed1b9 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/pdf/tagutils/TagTreeIteratorTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/pdf/tagutils/TagTreeIteratorTest.cs @@ -40,17 +40,6 @@ public virtual void TagTreeIteratorTagPointerNull() { NUnit.Framework.Assert.AreEqual(e.Message, errorMessage); } - [NUnit.Framework.Test] - public virtual void TagTreeIteratorApproverNull() { - String errorMessage = MessageFormatUtil.Format(KernelExceptionMessageConstant.ARG_SHOULD_NOT_BE_NULL, "approver" - ); - PdfDocument doc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream(), new WriterProperties())); - doc.SetTagged(); - Exception e = NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => new TagTreeIterator(doc.GetStructTreeRoot - (), null, TagTreeIterator.TreeTraversalOrder.PRE_ORDER)); - NUnit.Framework.Assert.AreEqual(e.Message, errorMessage); - } - [NUnit.Framework.Test] public virtual void TagTreeIteratorHandlerNull() { String errorMessage = MessageFormatUtil.Format(KernelExceptionMessageConstant.ARG_SHOULD_NOT_BE_NULL, "handler" @@ -109,8 +98,8 @@ public virtual void PostOrderTraversal() { tp.MoveToParent(); tp.AddTag(StandardRoles.DIV); tp.AddTag(StandardRoles.CODE); - TagTreeIterator iterator = new TagTreeIterator(doc.GetStructTreeRoot(), new TagTreeIteratorElementApprover - (), TagTreeIterator.TreeTraversalOrder.POST_ORDER); + TagTreeIterator iterator = new TagTreeIterator(doc.GetStructTreeRoot(), TagTreeIterator.TreeTraversalOrder + .POST_ORDER); TagTreeIteratorTest.TestHandler handler = new TagTreeIteratorTest.TestHandler(); iterator.AddHandler(handler); iterator.Traverse(); @@ -134,9 +123,10 @@ public virtual void CyclicReferencesTraversal() { doc.GetStructTreeRoot().AddKid(kid2); kid1.AddKid(kid2); kid2.AddKid(kid1); - TagTreeIterator iterator = new TagTreeIterator(doc.GetStructTreeRoot(), new TagTreeIteratorAvoidDuplicatesApprover - (), TagTreeIterator.TreeTraversalOrder.POST_ORDER); - TagTreeIteratorTest.TestHandler handler = new TagTreeIteratorTest.TestHandler(); + TagTreeIterator iterator = new TagTreeIterator(doc.GetStructTreeRoot(), TagTreeIterator.TreeTraversalOrder + .POST_ORDER); + TagTreeIteratorTest.TestHandlerAvoidDuplicates handler = new TagTreeIteratorTest.TestHandlerAvoidDuplicates + (); iterator.AddHandler(handler); iterator.Traverse(); NUnit.Framework.Assert.AreEqual(3, handler.nodes.Count); @@ -151,7 +141,23 @@ internal class TestHandler : ITagTreeIteratorHandler { internal readonly IList nodes = new List(); //\endcond - public virtual void NextElement(IStructureNode elem) { + public virtual bool Accept(IStructureNode node) { + return node != null; + } + + public virtual void ProcessElement(IStructureNode elem) { + nodes.Add(elem); + } + } +//\endcond + +//\cond DO_NOT_DOCUMENT + internal class TestHandlerAvoidDuplicates : AbstractAvoidDuplicatesTagTreeIteratorHandler { +//\cond DO_NOT_DOCUMENT + internal readonly IList nodes = new List(); +//\endcond + + public override void ProcessElement(IStructureNode elem) { nodes.Add(elem); } } diff --git a/itext.tests/itext.kernel.tests/itext/kernel/utils/CompareToolTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/utils/CompareToolTest.cs index 43d2226b48..236244ab16 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/utils/CompareToolTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/utils/CompareToolTest.cs @@ -64,7 +64,7 @@ public virtual void CompareToolErrorReportTest01() { String cmpPdf = sourceFolder + "cmp_simple_pdf.pdf"; String result = compareTool.CompareByContent(outPdf, cmpPdf, destinationFolder); System.Console.Out.WriteLine("\nRESULT:\n" + result); - NUnit.Framework.Assert.IsNotNull(result, "CompareTool must return differences found between the files"); + NUnit.Framework.Assert.IsNotNull("CompareTool must return differences found between the files", result); NUnit.Framework.Assert.IsTrue(result.Contains("differs on page [1, 2].")); // Comparing the report to the reference one. NUnit.Framework.Assert.IsTrue(compareTool.CompareXmls(destinationFolder + "simple_pdf.report.xml", sourceFolder @@ -80,7 +80,7 @@ public virtual void CompareToolErrorReportTest02() { String cmpPdf = sourceFolder + "cmp_tagged_pdf.pdf"; String result = compareTool.CompareByContent(outPdf, cmpPdf, destinationFolder); System.Console.Out.WriteLine("\nRESULT:\n" + result); - NUnit.Framework.Assert.IsNotNull(result, "CompareTool must return differences found between the files"); + NUnit.Framework.Assert.IsNotNull("CompareTool must return differences found between the files", result); NUnit.Framework.Assert.IsTrue(result.Contains("Compare by content fails. No visual differences")); // Comparing the report to the reference one. NUnit.Framework.Assert.IsTrue(compareTool.CompareXmls(destinationFolder + "tagged_pdf.report.xml", sourceFolder @@ -96,7 +96,7 @@ public virtual void CompareToolErrorReportTest03() { String cmpPdf = sourceFolder + "cmp_screenAnnotation.pdf"; String result = compareTool.CompareByContent(outPdf, cmpPdf, destinationFolder); System.Console.Out.WriteLine("\nRESULT:\n" + result); - NUnit.Framework.Assert.IsNotNull(result, "CompareTool must return differences found between the files"); + NUnit.Framework.Assert.IsNotNull("CompareTool must return differences found between the files", result); NUnit.Framework.Assert.IsTrue(result.Contains("Compare by content fails. No visual differences")); // Comparing the report to the reference one. NUnit.Framework.Assert.IsTrue(compareTool.CompareXmls(destinationFolder + "screenAnnotation.report.xml", sourceFolder @@ -113,7 +113,7 @@ public virtual void CompareToolErrorReportTest04() { String cmpPdf = sourceFolder + "cmp_simple_pdf_with_space .pdf"; String result = compareTool.CompareByContent(outPdf, cmpPdf, destinationFolder); System.Console.Out.WriteLine("\nRESULT:\n" + result); - NUnit.Framework.Assert.IsNotNull(result, "CompareTool must return differences found between the files"); + NUnit.Framework.Assert.IsNotNull("CompareTool must return differences found between the files", result); NUnit.Framework.Assert.IsTrue(result.Contains("differs on page [1, 2].")); // Comparing the report to the reference one. NUnit.Framework.Assert.IsTrue(compareTool.CompareXmls(destinationFolder + "simple_pdf.report.xml", sourceFolder @@ -260,7 +260,7 @@ public virtual void CompareFilesWithDiffLinkAnnotationTest() { [NUnit.Framework.Test] public virtual void ConvertDocInfoToStringsTest() { String inPdf = sourceFolder + "test.pdf"; - CompareTool compareTool = new _T1689272844(this); + CompareTool compareTool = new _T798358249(this); using (PdfReader reader = new PdfReader(inPdf, compareTool.GetOutReaderProperties())) { using (PdfDocument doc = new PdfDocument(reader)) { String[] docInfo = compareTool.ConvertDocInfoToStrings(doc.GetDocumentInfo()); @@ -274,12 +274,12 @@ public virtual void ConvertDocInfoToStringsTest() { } //\cond DO_NOT_DOCUMENT - internal class _T1689272844 : CompareTool { + internal class _T798358249 : CompareTool { protected internal override String[] ConvertDocInfoToStrings(PdfDocumentInfo info) { return base.ConvertDocInfoToStrings(info); } - internal _T1689272844(CompareToolTest _enclosing) { + internal _T798358249(CompareToolTest _enclosing) { this._enclosing = _enclosing; } diff --git a/itext.tests/itext.kernel.tests/itext/kernel/utils/PdfAnnotationFlattenerTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/utils/PdfAnnotationFlattenerTest.cs index 8b19e51051..0fa48c4749 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/utils/PdfAnnotationFlattenerTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/utils/PdfAnnotationFlattenerTest.cs @@ -759,13 +759,13 @@ private PdfTextMarkupAnnotation CreateTextAnnotation(PdfCanvas canvas, float x, internal class CustomPdfAnnotationFlattenFactory : PdfAnnotationFlattenFactory { public override IAnnotationFlattener GetAnnotationFlattenWorker(PdfName name) { if (PdfName.Link.Equals(name)) { - return new _IAnnotationFlattener_872(); + return new _IAnnotationFlattener_871(); } return base.GetAnnotationFlattenWorker(name); } - private sealed class _IAnnotationFlattener_872 : IAnnotationFlattener { - public _IAnnotationFlattener_872() { + private sealed class _IAnnotationFlattener_871 : IAnnotationFlattener { + public _IAnnotationFlattener_871() { } public bool Flatten(PdfAnnotation annotation, PdfPage page) { diff --git a/itext.tests/itext.kernel.tests/itext/kernel/utils/PdfMergerTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/utils/PdfMergerTest.cs index 351b93865b..3e99ba14e0 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/utils/PdfMergerTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/utils/PdfMergerTest.cs @@ -134,6 +134,22 @@ public virtual void MergeDocumentTest02() { , destinationFolder, "diff_")); } + [NUnit.Framework.Test] + public virtual void MergeDocumentWithCycleTagReferenceTest() { + String filename1 = sourceFolder + "doc1.pdf"; + String filename2 = sourceFolder + "pdfWithCycleRefInParentTag.pdf"; + String resultFile = destinationFolder + "pdfWithCycleRefInParentTag.pdf"; + using (PdfDocument pdfDocument1 = new PdfDocument(new PdfReader(filename2))) { + using (PdfDocument pdfDocument2 = new PdfDocument(new PdfReader(filename1), CompareTool.CreateTestPdfWriter + (resultFile).SetSmartMode(true))) { + PdfMerger merger = new PdfMerger(pdfDocument2); + merger.Merge(pdfDocument1, 1, pdfDocument1.GetNumberOfPages()); + } + } + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(resultFile, sourceFolder + "cmp_pdfWithCycleRefInParentTag.pdf" + , destinationFolder, "diff_")); + } + [NUnit.Framework.Test] [LogMessage(iText.IO.Logs.IoLogMessageConstant.SOURCE_DOCUMENT_HAS_ACROFORM_DICTIONARY)] public virtual void MergeDocumentTest03() { @@ -428,7 +444,8 @@ public virtual void MergeOutlinesWithWrongStructureTest() { PdfDocument inputDoc = new PdfDocument(new PdfReader(sourceFolder + "infiniteLoopInOutlineStructure.pdf")); PdfDocument outputDoc = new PdfDocument(CompareTool.CreateTestPdfWriter(destinationFolder + "infiniteLoopInOutlineStructure.pdf" )); - PdfMerger merger = new PdfMerger(outputDoc, false, true); + PdfMerger merger = new PdfMerger(outputDoc, new PdfMergerProperties().SetMergeTags(false).SetMergeOutlines + (true)); System.Console.Out.WriteLine("Doing merge"); merger.Merge(inputDoc, 1, 2); merger.Close(); @@ -463,7 +480,8 @@ public virtual void MergeDocumentWithColorPropertyInOutlineTest() { using (PdfDocument merged = new PdfDocument(CompareTool.CreateTestPdfWriter(mergedPdf))) { using (PdfDocument fileA = new PdfDocument(new PdfReader(firstDocument))) { using (PdfDocument fileB = new PdfDocument(new PdfReader(secondDocument))) { - PdfMerger merger = new PdfMerger(merged, false, true); + PdfMerger merger = new PdfMerger(merged, new PdfMergerProperties().SetMergeTags(false).SetMergeOutlines(true + )); merger.Merge(fileA, 1, fileA.GetNumberOfPages()); merger.Merge(fileB, 1, fileB.GetNumberOfPages()); merger.Close(); @@ -483,7 +501,8 @@ public virtual void MergeDocumentWithStylePropertyInOutlineTest() { using (PdfDocument documentA = new PdfDocument(new PdfReader(firstDocument))) { using (PdfDocument documentB = new PdfDocument(new PdfReader(secondDocument))) { using (PdfDocument merged = new PdfDocument(CompareTool.CreateTestPdfWriter(mergedPdf))) { - PdfMerger merger = new PdfMerger(merged, false, true); + PdfMerger merger = new PdfMerger(merged, new PdfMergerProperties().SetMergeTags(false).SetMergeOutlines(true + )); merger.Merge(documentA, 1, documentA.GetNumberOfPages()); merger.Merge(documentB, 1, documentB.GetNumberOfPages()); merger.Close(); @@ -502,7 +521,8 @@ public virtual void MergePdfDocumentsWithCopingOutlinesTest() { using (PdfDocument documentA = new PdfDocument(new PdfReader(firstPdfDocument))) { using (PdfDocument documentB = new PdfDocument(new PdfReader(secondPdfDocument))) { using (PdfDocument mergedPdf = new PdfDocument(CompareTool.CreateTestPdfWriter(mergedDocument))) { - PdfMerger merger = new PdfMerger(mergedPdf, false, true); + PdfMerger merger = new PdfMerger(mergedPdf, new PdfMergerProperties().SetMergeTags(false).SetMergeOutlines + (true)); merger.Merge(documentA, 1, documentA.GetNumberOfPages()); merger.Merge(documentB, 1, documentB.GetNumberOfPages()); merger.Close(); @@ -779,6 +799,26 @@ public virtual void CopyOnlyEmptyOcPropertiesTest() { , destinationFolder, "diff_")); } + [LogMessage(iText.IO.Logs.IoLogMessageConstant.SOURCE_DOCUMENT_HAS_ACROFORM_DICTIONARY)] + [NUnit.Framework.Test] + public virtual void CombineTagRootKidsTest() { + String filename1 = sourceFolder + "tagRootKidsDoc1.pdf"; + String filename2 = sourceFolder + "tagRootKidsDoc2.pdf"; + String resultFile = destinationFolder + "mergedTags.pdf"; + PdfDocument result = new PdfDocument(CompareTool.CreateTestPdfWriter(resultFile)); + PdfMerger merger = new PdfMerger(result, new PdfMergerProperties().SetMergeTags(true).SetMergeOutlines(true + )).SetCloseSourceDocuments(true); + PdfDocument input1 = new PdfDocument(new PdfReader(filename1)); + merger.Merge(input1, 1, 1); + input1.Close(); + PdfDocument input2 = new PdfDocument(new PdfReader(filename2)); + merger.Merge(input2, 1, 1); + input2.Close(); + merger.Close(); + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(resultFile, sourceFolder + "cmp_mergedTags.pdf" + , destinationFolder, "diff_")); + } + private PdfDictionary MergeSinglePdfAndGetResultingStructTreeRoot(String pathToMerge) { IList sources = new List(); sources.Add(new FileInfo(sourceFolder + pathToMerge)); diff --git a/itext.tests/itext.kernel.tests/itext/kernel/utils/PdfSplitterTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/utils/PdfSplitterTest.cs index 7ff0d334a8..903fd8bd20 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/utils/PdfSplitterTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/utils/PdfSplitterTest.cs @@ -22,7 +22,6 @@ You should have received a copy of the GNU Affero General Public License */ using System; using System.Collections.Generic; -using System.IO; using iText.Commons.Utils; using iText.Kernel.Pdf; using iText.Test; @@ -53,7 +52,7 @@ public virtual void SplitDocumentTest01() { String inputFileName = sourceFolder + "iphone_user_guide.pdf"; PdfDocument inputPdfDoc = new PdfDocument(new PdfReader(inputFileName)); IList pageNumbers = JavaUtil.ArraysAsList(30, 100); - IList splitDocuments = new _PdfSplitter_72(inputPdfDoc).SplitByPageNumbers(pageNumbers); + IList splitDocuments = new _PdfSplitter_71(inputPdfDoc).SplitByPageNumbers(pageNumbers); foreach (PdfDocument doc in splitDocuments) { doc.Close(); } @@ -64,8 +63,8 @@ public virtual void SplitDocumentTest01() { } } - private sealed class _PdfSplitter_72 : PdfSplitter { - public _PdfSplitter_72(PdfDocument baseArg1) + private sealed class _PdfSplitter_71 : PdfSplitter { + public _PdfSplitter_71(PdfDocument baseArg1) : base(baseArg1) { this.partNumber = 1; } @@ -79,7 +78,7 @@ protected internal override PdfWriter GetNextPdfWriter(PageRange documentPageRan return CompareTool.CreateTestPdfWriter(PdfSplitterTest.destinationFolder + "splitDocument1_" + (this.partNumber ++).ToString() + ".pdf"); } - catch (FileNotFoundException) { + catch (System.IO.IOException) { throw new Exception(); } } @@ -90,8 +89,8 @@ protected internal override PdfWriter GetNextPdfWriter(PageRange documentPageRan public virtual void SplitDocumentTest02() { String inputFileName = sourceFolder + "iphone_user_guide.pdf"; PdfDocument inputPdfDoc = new PdfDocument(new PdfReader(inputFileName)); - PdfSplitter splitter = new _PdfSplitter_102(inputPdfDoc); - splitter.SplitByPageCount(60, new _IDocumentReadyListener_115()); + PdfSplitter splitter = new _PdfSplitter_101(inputPdfDoc); + splitter.SplitByPageCount(60, new _IDocumentReadyListener_114()); for (int i = 1; i <= 3; i++) { NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + "splitDocument2_" + i .ToString() + ".pdf", sourceFolder + "cmp/" + "cmp_splitDocument2_" + i.ToString() + ".pdf", destinationFolder @@ -99,8 +98,8 @@ public virtual void SplitDocumentTest02() { } } - private sealed class _PdfSplitter_102 : PdfSplitter { - public _PdfSplitter_102(PdfDocument baseArg1) + private sealed class _PdfSplitter_101 : PdfSplitter { + public _PdfSplitter_101(PdfDocument baseArg1) : base(baseArg1) { this.partNumber = 1; } @@ -115,14 +114,14 @@ protected internal override PdfWriter GetNextPdfWriter(PageRange documentPageRan (this.partNumber++).ToString() + ".pdf"); return writer; } - catch (FileNotFoundException) { + catch (System.IO.IOException) { throw new Exception(); } } } - private sealed class _IDocumentReadyListener_115 : PdfSplitter.IDocumentReadyListener { - public _IDocumentReadyListener_115() { + private sealed class _IDocumentReadyListener_114 : PdfSplitter.IDocumentReadyListener { + public _IDocumentReadyListener_114() { } public void DocumentReady(PdfDocument pdfDocument, PageRange pageRange) { @@ -140,7 +139,7 @@ public virtual void SplitDocumentTest03() { PdfDocument inputPdfDoc = new PdfDocument(new PdfReader(inputFileName)); PageRange pageRange1 = new PageRange().AddPageSequence(4, 15).AddSinglePage(18).AddPageSequence(1, 2); PageRange pageRange2 = new PageRange().AddSinglePage(99).AddSinglePage(98).AddPageSequence(70, 99); - IList splitDocuments = new _PdfSplitter_143(inputPdfDoc).ExtractPageRanges(JavaUtil.ArraysAsList + IList splitDocuments = new _PdfSplitter_142(inputPdfDoc).ExtractPageRanges(JavaUtil.ArraysAsList (pageRange1, pageRange2)); foreach (PdfDocument pdfDocument in splitDocuments) { pdfDocument.Close(); @@ -152,8 +151,8 @@ public virtual void SplitDocumentTest03() { } } - private sealed class _PdfSplitter_143 : PdfSplitter { - public _PdfSplitter_143(PdfDocument baseArg1) + private sealed class _PdfSplitter_142 : PdfSplitter { + public _PdfSplitter_142(PdfDocument baseArg1) : base(baseArg1) { this.partNumber = 1; } @@ -167,7 +166,7 @@ protected internal override PdfWriter GetNextPdfWriter(PageRange documentPageRan return CompareTool.CreateTestPdfWriter(PdfSplitterTest.destinationFolder + "splitDocument3_" + (this.partNumber ++).ToString() + ".pdf"); } - catch (FileNotFoundException) { + catch (System.IO.IOException) { throw new Exception(); } } @@ -181,7 +180,7 @@ public virtual void SplitDocumentTest04() { PageRange pageRange1 = new PageRange("even & 80-").AddPageSequence(4, 15).AddSinglePage(18).AddPageSequence (1, 2); PageRange pageRange2 = new PageRange("99,98").AddPageSequence(70, 99); - IList splitDocuments = new _PdfSplitter_177(inputPdfDoc).ExtractPageRanges(JavaUtil.ArraysAsList + IList splitDocuments = new _PdfSplitter_176(inputPdfDoc).ExtractPageRanges(JavaUtil.ArraysAsList (pageRange1, pageRange2)); foreach (PdfDocument pdfDocument in splitDocuments) { pdfDocument.Close(); @@ -193,8 +192,8 @@ public virtual void SplitDocumentTest04() { } } - private sealed class _PdfSplitter_177 : PdfSplitter { - public _PdfSplitter_177(PdfDocument baseArg1) + private sealed class _PdfSplitter_176 : PdfSplitter { + public _PdfSplitter_176(PdfDocument baseArg1) : base(baseArg1) { this.partNumber = 1; } @@ -208,7 +207,7 @@ protected internal override PdfWriter GetNextPdfWriter(PageRange documentPageRan return CompareTool.CreateTestPdfWriter(PdfSplitterTest.destinationFolder + "splitDocument4_" + (this.partNumber ++).ToString() + ".pdf"); } - catch (FileNotFoundException) { + catch (System.IO.IOException) { throw new Exception(); } } @@ -234,7 +233,7 @@ public virtual void SplitDocumentByOutlineTest() { public virtual void SplitDocumentBySize() { String inputFileName = sourceFolder + "splitBySize.pdf"; PdfDocument inputPdfDoc = new PdfDocument(new PdfReader(inputFileName)); - PdfSplitter splitter = new _PdfSplitter_223(inputPdfDoc); + PdfSplitter splitter = new _PdfSplitter_222(inputPdfDoc); IList documents = splitter.SplitBySize(100000); foreach (PdfDocument doc in documents) { doc.Close(); @@ -245,8 +244,8 @@ public virtual void SplitDocumentBySize() { } } - private sealed class _PdfSplitter_223 : PdfSplitter { - public _PdfSplitter_223(PdfDocument baseArg1) + private sealed class _PdfSplitter_222 : PdfSplitter { + public _PdfSplitter_222(PdfDocument baseArg1) : base(baseArg1) { this.partNumber = 1; } @@ -260,7 +259,7 @@ protected internal override PdfWriter GetNextPdfWriter(PageRange documentPageRan return CompareTool.CreateTestPdfWriter(PdfSplitterTest.destinationFolder + "splitBySize_part" + (this.partNumber ++).ToString() + ".pdf"); } - catch (FileNotFoundException) { + catch (System.IO.IOException) { throw new Exception(); } } diff --git a/itext.tests/itext.kernel.tests/itext/kernel/utils/RegisterDefaultDiContainerTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/utils/RegisterDefaultDiContainerTest.cs new file mode 100644 index 0000000000..73d303919d --- /dev/null +++ b/itext.tests/itext.kernel.tests/itext/kernel/utils/RegisterDefaultDiContainerTest.cs @@ -0,0 +1,90 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using iText.Commons.Datastructures; +using iText.IO.Source; +using iText.Kernel.DI.Pagetree; +using iText.Kernel.Pdf; +using iText.Test; + +namespace iText.Kernel.Utils { + [NUnit.Framework.Category("UnitTest")] + public class RegisterDefaultDiContainerTest : ExtendedITextTest { + [NUnit.Framework.Test] + public virtual void Test() { + RegisterDefaultDiContainer registerDefaultDiContainer = new RegisterDefaultDiContainer(); + NUnit.Framework.Assert.IsNotNull(registerDefaultDiContainer); + } + + [NUnit.Framework.Test] + public virtual void TestStaticBlock() { + PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new ByteArrayOutputStream())); + NUnit.Framework.Assert.IsTrue(pdfDocument.GetDiContainer().GetInstance() is IPageTreeListFactory + ); + } + + [NUnit.Framework.Test] + public virtual void TestWithOverWriting() { + PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new ByteArrayOutputStream())); + NUnit.Framework.Assert.IsTrue(pdfDocument.GetDiContainer().GetInstance() is IPageTreeListFactory + ); + } + + [NUnit.Framework.Test] + public virtual void TestWithSettingDocumentProps() { + DocumentProperties documentProperties = new DocumentProperties(); + documentProperties.RegisterDependency(typeof(IPageTreeListFactory), new RegisterDefaultDiContainerTest.IPageTreeTestImpl + ()); + PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()), documentProperties); + NUnit.Framework.Assert.IsTrue(pdfDocument.GetDiContainer().GetInstance() is RegisterDefaultDiContainerTest.IPageTreeTestImpl + ); + } + + [NUnit.Framework.Test] + public virtual void DocumentPropsSetWithNullInstance() { + DocumentProperties documentProperties = new DocumentProperties(); + NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => { + documentProperties.RegisterDependency(typeof(IPageTreeListFactory), null); + } + ); + } + + [NUnit.Framework.Test] + public virtual void DocumentPropsSetWithNullType() { + DocumentProperties documentProperties = new DocumentProperties(); + Object dummyObject = new Object(); + NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => { + documentProperties.RegisterDependency(null, dummyObject); + } + ); + } + +//\cond DO_NOT_DOCUMENT + internal sealed class IPageTreeTestImpl : IPageTreeListFactory { + public ISimpleList CreateList(PdfDictionary pagesDictionary) { + return null; + } + } +//\endcond + } +} diff --git a/itext.tests/itext.kernel.tests/itext/kernel/utils/ValidationContainerTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/utils/ValidationContainerTest.cs index 3d3767a03d..a37a69fb39 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/utils/ValidationContainerTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/utils/ValidationContainerTest.cs @@ -20,8 +20,9 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ -using System; using iText.Kernel.Pdf; +using iText.Kernel.Validation; +using iText.Kernel.Validation.Context; using iText.Test; namespace iText.Kernel.Utils { @@ -30,20 +31,20 @@ public class ValidationContainerTest : ExtendedITextTest { [NUnit.Framework.Test] public virtual void ValidateObjectTest() { ValidationContainer container = new ValidationContainer(); - container.Validate(null, IsoKey.FONT, null, null, null); + container.Validate(new FontValidationContext(null, null)); ValidationContainerTest.CustomValidationChecker checker = new ValidationContainerTest.CustomValidationChecker (); container.AddChecker(checker); NUnit.Framework.Assert.IsTrue(container.ContainsChecker(checker)); NUnit.Framework.Assert.IsFalse(checker.objectValidationPerformed); - container.Validate(null, IsoKey.FONT, null, null, null); + container.Validate(new FontValidationContext(null, null)); NUnit.Framework.Assert.IsTrue(checker.objectValidationPerformed); } [NUnit.Framework.Test] public virtual void ValidateDocumentTest() { ValidationContainer container = new ValidationContainer(); - ValidationContext context = new ValidationContext().WithPdfDocument(null); + PdfDocumentValidationContext context = new PdfDocumentValidationContext(null, null); container.Validate(context); ValidationContainerTest.CustomValidationChecker checker = new ValidationContainerTest.CustomValidationChecker (); @@ -58,13 +59,17 @@ private class CustomValidationChecker : IValidationChecker { public bool objectValidationPerformed = false; - public virtual void ValidateDocument(ValidationContext validationContext) { - documentValidationPerformed = true; + public virtual void Validate(IValidationContext validationContext) { + if (validationContext.GetType() == ValidationType.PDF_DOCUMENT) { + documentValidationPerformed = true; + } + else { + objectValidationPerformed = true; + } } - public virtual void ValidateObject(Object obj, IsoKey key, PdfResources resources, PdfStream contentStream - , Object extra) { - objectValidationPerformed = true; + public virtual bool IsPdfObjectReadyToFlush(PdfObject @object) { + return true; } } } diff --git a/itext.tests/itext.kernel.tests/itext/kernel/utils/checkers/FontCheckUtilTest.cs b/itext.tests/itext.kernel.tests/itext/kernel/utils/checkers/FontCheckUtilTest.cs index d32b148652..819155c3ed 100644 --- a/itext.tests/itext.kernel.tests/itext/kernel/utils/checkers/FontCheckUtilTest.cs +++ b/itext.tests/itext.kernel.tests/itext/kernel/utils/checkers/FontCheckUtilTest.cs @@ -35,12 +35,12 @@ public class FontCheckUtilTest : ExtendedITextTest { [NUnit.Framework.Test] public virtual void CheckFontAvailable() { PdfFont font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA); - NUnit.Framework.Assert.AreEqual(-1, FontCheckUtil.CheckGlyphsOfText("123", font, new _CharacterChecker_48( + NUnit.Framework.Assert.AreEqual(-1, FontCheckUtil.CheckGlyphsOfText("123", font, new _CharacterChecker_47( ))); } - private sealed class _CharacterChecker_48 : FontCheckUtil.CharacterChecker { - public _CharacterChecker_48() { + private sealed class _CharacterChecker_47 : FontCheckUtil.CharacterChecker { + public _CharacterChecker_47() { } public bool Check(int ch, PdfFont fontToCheck) { @@ -51,12 +51,12 @@ public bool Check(int ch, PdfFont fontToCheck) { [NUnit.Framework.Test] public virtual void CheckFontNotAvailable() { PdfFont font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA); - NUnit.Framework.Assert.AreEqual(2, FontCheckUtil.CheckGlyphsOfText("hi⫊", font, new _CharacterChecker_60() + NUnit.Framework.Assert.AreEqual(2, FontCheckUtil.CheckGlyphsOfText("hi⫊", font, new _CharacterChecker_59() )); } - private sealed class _CharacterChecker_60 : FontCheckUtil.CharacterChecker { - public _CharacterChecker_60() { + private sealed class _CharacterChecker_59 : FontCheckUtil.CharacterChecker { + public _CharacterChecker_59() { } public bool Check(int ch, PdfFont fontToCheck) { @@ -68,12 +68,12 @@ public bool Check(int ch, PdfFont fontToCheck) { public virtual void CheckUnicodeMappingNotAvailable() { PdfFont font = PdfFontFactory.CreateFont(FontProgramFactory.CreateType1Font(FONTS_FOLDER + "cmr10.afm", FONTS_FOLDER + "cmr10.pfb"), FontEncoding.FONT_SPECIFIC, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED); - int index = FontCheckUtil.CheckGlyphsOfText("h i", font, new _CharacterChecker_73()); + int index = FontCheckUtil.CheckGlyphsOfText("h i", font, new _CharacterChecker_72()); NUnit.Framework.Assert.AreEqual(1, index); } - private sealed class _CharacterChecker_73 : FontCheckUtil.CharacterChecker { - public _CharacterChecker_73() { + private sealed class _CharacterChecker_72 : FontCheckUtil.CharacterChecker { + public _CharacterChecker_72() { } public bool Check(int ch, PdfFont fontToCheck) { @@ -90,12 +90,12 @@ public bool Check(int ch, PdfFont fontToCheck) { public virtual void CheckUnicodeMappingAvailable() { PdfFont font = PdfFontFactory.CreateFont(FontProgramFactory.CreateType1Font(FONTS_FOLDER + "cmr10.afm", FONTS_FOLDER + "cmr10.pfb"), FontEncoding.FONT_SPECIFIC, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED); - int index = FontCheckUtil.CheckGlyphsOfText("hi", font, new _CharacterChecker_91()); + int index = FontCheckUtil.CheckGlyphsOfText("hi", font, new _CharacterChecker_90()); NUnit.Framework.Assert.AreEqual(-1, index); } - private sealed class _CharacterChecker_91 : FontCheckUtil.CharacterChecker { - public _CharacterChecker_91() { + private sealed class _CharacterChecker_90 : FontCheckUtil.CharacterChecker { + public _CharacterChecker_90() { } public bool Check(int ch, PdfFont fontToCheck) { diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptingTest/cmp_encryptWithPasswordAes256Pdf2.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptingTest/cmp_encryptWithPasswordAes256Pdf2.pdf index 092fe20533..8f724a26d6 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptingTest/cmp_encryptWithPasswordAes256Pdf2.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptingTest/cmp_encryptWithPasswordAes256Pdf2.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateAes128.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateAes128.pdf index e173bf5a6c..b13b030ef5 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateAes128.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateAes128.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateAes128NoCompression.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateAes128NoCompression.pdf index 5f692a7297..995e6259b6 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateAes128NoCompression.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateAes128NoCompression.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateAes256.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateAes256.pdf index d0c35c7959..138ba14ec9 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateAes256.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateAes256.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateAes256NoCompression.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateAes256NoCompression.pdf index 3beb48e7a5..8513c348de 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateAes256NoCompression.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateAes256NoCompression.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateStandard128.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateStandard128.pdf index 3292cd3cb2..d8467daf59 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateStandard128.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateStandard128.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateStandard128NoCompression.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateStandard128NoCompression.pdf index 8f00163772..09c0245272 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateStandard128NoCompression.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateStandard128NoCompression.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateStandard40.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateStandard40.pdf index 45d5c2a2d4..f48d6885ce 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateStandard40.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateStandard40.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateStandard40NoCompression.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateStandard40NoCompression.pdf index 0769bbd00c..782c17518a 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateStandard40NoCompression.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_appended_encryptWithCertificateStandard40NoCompression.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateAes128.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateAes128.pdf index 5fc210b229..7cd4e5a752 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateAes128.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateAes128.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateAes128NoCompression.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateAes128NoCompression.pdf index ddcbd32f63..1e00eb29c3 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateAes128NoCompression.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateAes128NoCompression.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateAes256.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateAes256.pdf index cd9f13666c..c2cdee2e07 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateAes256.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateAes256.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateAes256NoCompression.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateAes256NoCompression.pdf index 7acb873318..5f364a5d3a 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateAes256NoCompression.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateAes256NoCompression.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateStandard128.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateStandard128.pdf index c64bad3632..7df42b6d3a 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateStandard128.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateStandard128.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateStandard128NoCompression.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateStandard128NoCompression.pdf index 3088393a43..f695c44f81 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateStandard128NoCompression.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateStandard128NoCompression.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateStandard40.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateStandard40.pdf index ebfbe0697b..708d88a008 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateStandard40.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateStandard40.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateStandard40NoCompression.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateStandard40NoCompression.pdf index ea318f14df..07548fe6de 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateStandard40NoCompression.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/PdfEncryptionManuallyPortedTest/cmp_encryptWithCertificateStandard40NoCompression.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/PdfEncryptionTest/cmp_appended_encryptAes256FullCompression.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/PdfEncryptionTest/cmp_appended_encryptAes256FullCompression.pdf index 533b80e956..d1a6fe05dd 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/PdfEncryptionTest/cmp_appended_encryptAes256FullCompression.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/PdfEncryptionTest/cmp_appended_encryptAes256FullCompression.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/PdfEncryptionTest/cmp_appended_encryptWithPasswordAes256Pdf2.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/PdfEncryptionTest/cmp_appended_encryptWithPasswordAes256Pdf2.pdf index 5b492a02f4..103cab5001 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/PdfEncryptionTest/cmp_appended_encryptWithPasswordAes256Pdf2.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/PdfEncryptionTest/cmp_appended_encryptWithPasswordAes256Pdf2.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/PdfEncryptionTest/cmp_encryptAes256FullCompression.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/PdfEncryptionTest/cmp_encryptAes256FullCompression.pdf index 36f8d33df7..67169d5a14 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/PdfEncryptionTest/cmp_encryptAes256FullCompression.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/PdfEncryptionTest/cmp_encryptAes256FullCompression.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/PdfEncryptionTest/cmp_encryptAes256Pdf2Permissions.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/PdfEncryptionTest/cmp_encryptAes256Pdf2Permissions.pdf index fc84e5a3c6..24f164693c 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/PdfEncryptionTest/cmp_encryptAes256Pdf2Permissions.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/PdfEncryptionTest/cmp_encryptAes256Pdf2Permissions.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/PdfEncryptionTest/cmp_encryptWithPasswordAes256Pdf2.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/PdfEncryptionTest/cmp_encryptWithPasswordAes256Pdf2.pdf index ad124a4201..0342ff69f2 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/PdfEncryptionTest/cmp_encryptWithPasswordAes256Pdf2.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/PdfEncryptionTest/cmp_encryptWithPasswordAes256Pdf2.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/PdfEncryptionTest/cmp_stampAndUpdateVersionNewAes256.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/PdfEncryptionTest/cmp_stampAndUpdateVersionNewAes256.pdf index 4e4e2c245b..81221803b7 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/PdfEncryptionTest/cmp_stampAndUpdateVersionNewAes256.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/PdfEncryptionTest/cmp_stampAndUpdateVersionNewAes256.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_arabic01.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_arabic01.pdf index fdbf27e6ce..9bf3c10bef 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_arabic01.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_arabic01.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_arabic02.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_arabic02.pdf index 594d85820e..c5a942b289 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_arabic02.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_arabic02.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_arabic03.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_arabic03.pdf index 22a95ed46c..1fef9fd751 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_arabic03.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_arabic03.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_arabic04.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_arabic04.pdf index 84f2984d92..908976c468 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_arabic04.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_arabic04.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_arabic05.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_arabic05.pdf index 0072a341ea..9651572068 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_arabic05.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_arabic05.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_devanagari01.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_devanagari01.pdf index 309fdcf2ef..c41d3c8123 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_devanagari01.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_devanagari01.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_devanagari02.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_devanagari02.pdf index 6481b11782..f23b6fbaa5 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_devanagari02.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_devanagari02.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_emoji01.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_emoji01.pdf index 0c3803b0d1..bcb49fb02e 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_emoji01.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_emoji01.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_gurmukhi01.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_gurmukhi01.pdf index c090428637..e88847346f 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_gurmukhi01.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_gurmukhi01.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_khmer01.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_khmer01.pdf index 79672d615d..a4182c6804 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_khmer01.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_khmer01.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_nfkcNormalization01.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_nfkcNormalization01.pdf index 994a3cf184..700818f509 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_nfkcNormalization01.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_nfkcNormalization01.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_nfkcNormalization02.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_nfkcNormalization02.pdf index d12efd75e3..5e53b3b77c 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_nfkcNormalization02.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_nfkcNormalization02.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_nfkcNormalization03.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_nfkcNormalization03.pdf index ac6400b63d..74608901bd 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_nfkcNormalization03.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_nfkcNormalization03.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_nfkcNormalization04.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_nfkcNormalization04.pdf index b26f7154ad..b4f60b0dd5 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_nfkcNormalization04.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_nfkcNormalization04.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_nfkcNormalization05.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_nfkcNormalization05.pdf index 20ad57efbc..41b2f7c667 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_nfkcNormalization05.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_nfkcNormalization05.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_nonAsciiSpace01.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_nonAsciiSpace01.pdf index 25866b1594..b3b13fe202 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_nonAsciiSpace01.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_nonAsciiSpace01.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_rfc4013Example01.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_rfc4013Example01.pdf index 0f5dcc5def..1bb32c6a41 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_rfc4013Example01.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_rfc4013Example01.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_rfc4013Example02.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_rfc4013Example02.pdf index 68fbdbdc47..54866c9766 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_rfc4013Example02.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_rfc4013Example02.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_rfc4013Example03.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_rfc4013Example03.pdf index d7d11aac6d..2de9ec3f40 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_rfc4013Example03.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_rfc4013Example03.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_rfc4013Example04.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_rfc4013Example04.pdf index c7fbaa9399..bd72132b51 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_rfc4013Example04.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_rfc4013Example04.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_tamil01.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_tamil01.pdf index 23e1032373..8a0132e81b 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_tamil01.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_tamil01.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_thai01.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_thai01.pdf index ec9ba63c25..d9344d4983 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_thai01.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_thai01.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_unicodeBom01.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_unicodeBom01.pdf index a87947fbad..b13c9602c0 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_unicodeBom01.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/UnicodeBasedPasswordEncryptionTest/cmp_unicodePassword_unicodeBom01.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/cmp_externalFile.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/cmp_externalFile.pdf new file mode 100644 index 0000000000..cb26c71843 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/cmp_externalFile.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/cmp_simpleEncryptDecrypt.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/cmp_simpleEncryptDecrypt.pdf new file mode 100644 index 0000000000..04af4ab69a Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/cmp_simpleEncryptDecrypt.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/cmp_simpleEncryptDecrypt_1_7.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/cmp_simpleEncryptDecrypt_1_7.pdf new file mode 100644 index 0000000000..bfae56843b Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/cmp_simpleEncryptDecrypt_1_7.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/decrypter.cert.pem b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/decrypter.cert.pem new file mode 100644 index 0000000000..b389cc324c --- /dev/null +++ b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/decrypter.cert.pem @@ -0,0 +1,25 @@ +-----BEGIN CERTIFICATE----- +MIIEMDCCAxigAwIBAgICEAIwDQYJKoZIhvcNAQELBQAwWTELMAkGA1UEBhMCQkUx +FDASBgNVBAoMC0V4YW1wbGUgSW5jMRowGAYDVQQLDBFUZXN0aW5nIEF1dGhvcml0 +eTEYMBYGA1UEAwwPSW50ZXJtZWRpYXRlIENBMCIYDzIwMjAwMTAxMDAwMDAwWhgP +MjAyMjAxMDEwMDAwMDBaMHExCzAJBgNVBAYTAkJFMRQwEgYDVQQKDAtFeGFtcGxl +IEluYzEaMBgGA1UECwwRVGVzdGluZyBBdXRob3JpdHkxDjAMBgNVBAMMBUFsaWNl +MSAwHgYJKoZIhvcNAQkBFhFhbGljZUBleGFtcGxlLmNvbTCCASIwDQYJKoZIhvcN +AQEBBQADggEPADCCAQoCggEBAOFzgm4eL34uvUYrX4akyEBi+sn0gCYo8UOthApf +luxF4ccaGhCHdjZa1PwRpV3bDGFQpUbhNu0juCBkYbRGxasQOn1CUDF7DCCjztNE +d779WwRlA5dnqWMFU5IjtoavSYl+CA1Ase2edxq7UjEZr4kIm7ADlUVpdKxLItJF +EP4QOjqv5sENuiGCKpMqb/JGmvnLxRevxDZQ8hIDV2s07krCog8hRChie39mDNmZ +/RH/JbgME6mGY99bDAnhu8xH41iBo8GemEmmFesx8YPrMivcXHk3QNt2LsKCAGZl +G51fsrtiC31732W0+dc09PoITS0NMvP8/38dQmod3ktJBusCAwEAAaOB5TCB4jAd +BgNVHQ4EFgQUXsenutQKZ62drno9rRRqOLVzCrgwHwYDVR0jBBgwFoAU7796UYsu +pC5KXdLO52F4zmo2SU8wDgYDVR0PAQH/BAQDAgUgMEcGA1UdHwRAMD4wPKA6oDiG +Nmh0dHA6Ly9weWhhbmtvLnRlc3RzL3Rlc3RpbmctY2EvY3Jscy9pbnRlcm0vbGF0 +ZXN0LmNybDBHBggrBgEFBQcBAQQ7MDkwNwYIKwYBBQUHMAGGK2h0dHA6Ly9weWhh +bmtvLnRlc3RzL3Rlc3RpbmctY2Evb2NzcC9pbnRlcm0wDQYJKoZIhvcNAQELBQAD +ggEBAJemwKDaHB+cRZHHGZbQ26E+xR1XgBw/IPqEanGfm37ANyJk1BCBXFUJBNLF +3b9pdvRnu+wuF0h9rGBkIAKNuuzyJIJhAj5FgRVTLRTIDxYZMPgBuxdrKx3rocYm +CVCu/OmlK6k8kHQubMCuQgVucd2emqg2tG1QOjt+yHXLLpPoOnYjKZlixzA0mW75 +DHj2hPFnan8fZ18orLGuWKRjMIatEdQYNIcPkmDEbQT9mh2v+ucXChg01TdvVzbc +fz43Jgu8Idv4PUiwbr4x8qCOahH1eUHQ1PCsCuF6RH5vjqAS8urthuR56BJOw7TX +Yl0L7vBpz0oA4j+uP6n1a8Uu43k= +-----END CERTIFICATE----- diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/externalFile.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/externalFile.pdf new file mode 100644 index 0000000000..e2253473ab Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/externalFile.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/invalidCryptFilter.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/invalidCryptFilter.pdf new file mode 100644 index 0000000000..086d385149 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/invalidCryptFilter.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/signerkey.pem b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/signerkey.pem new file mode 100644 index 0000000000..cc30330c20 --- /dev/null +++ b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/signerkey.pem @@ -0,0 +1,30 @@ +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQxtGpvXqM8ggXE+LE +qX9lZwICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEKK3IjaIwyNfaYFC +I8eHbZgEggTQS/qyyqLzljwQRKFPb6la2EAF1SKsWwP5hsrZ6TaGC4Rwdgm2wpH/ +HYp7DcdigKoYFCb4avatNRNdjY9YDEObrULn3YKemQNxcDRnceDppNWfN7eR0Ug4 +Y6OHPQfWzBsxWTyxrPJsa7v+rEczqLcIR77HNIGvH9oFYE58hTHLiEiFe5GM1lY3 +n+D7xyFrDT1IhO0BqVsIQUNXYonF5sThbUur2/g6YVpjHASnkILxZNoKEm0akfLV +99ACy6ABe9NwR0pHeCkOqkhVRT68/iktriK2Cpsp5xc8Hs6PT7jKMtF803k35vH7 +joMFYKzrqpNkv6goJ1MK0twpsvBVQD6zoK8dIXfuduTSNfhYobZ8ACjppLSZ0zTo +oXWBQPaOPADpH+/sC/MpZGH1DvUwV9XPsOQWcpmbrzb9rp83/KyBZ/sPSY3j9XqY +2WKT2nfi0DUPepolhBFG3Z/rBQZsK4IxCmMA2Dy8yJwct7Dk2CH/dRy0XDi0hV/3 +sSug2XjnTg4z+fBEEd/S55+DJNUbModH9Z5bfcDSKoXWwa7tmF+EYiAVjgRDPJIK +2eDJ6Esaw2HPKhe5sI/NJ2kxzmd0k8/ITH428kQS8VrC6k/MTtIxDjOx+0xbwvgI +Vuh+oDGjpNb7UVYLZt8ckdGhzWSOeZahHpygA9aG2zwhu0uL2Mu6uUqZH3WHv3Nl +UnrLanQ9EiLREiKaNBuLRWCX0/RI1UgAiKVI+bsyNYVGb1EKCX5f7WAJUX0C2Qzv +AWDohtBbDcpSFKgbwZy0JvR899i01xkJwWy8wwNwrcZ4XVfU7H34TcF/qklt90HU +epSKShHbTAejgZURCAK3OQaLaxEDMMAXNxoMk2LYq/8syB7dt73iU4b4iJJospiv +aSI9CTvMj7EQ4iE3m0LSxFWF4cXgMqXe6X51VSvf68oq2Ge9yZr29UW2sdrNfdJC +oV76SoRdcTiYd1BLbOKiUbpDmP2bzX9eCCdJkBfpAePVzf6LCajBJnr7A1FHpja6 +TbC1vWyPvqLKI+B4sVFJwoGXW/a91Iuqxtqo5fsT0FTyy4z8gMXyi/XWIPq93KWx +ZHDSNUDNc38Jb00nR/spap8btt9MNf5SFgwCGt0+RQxxp0FVKvSYtTa6Gu1/0Odc +bYbjAZRuJz6TxningKMFoNHAUo+/0SGV/S7ebjF618nPhAnmTXSlHzJ3OA3jmASl +eIpwyFpBCq8h0icyGNMJU8j5YMsXgWVlw2s0YGwpNwDVMsaFgLzByMStONdhRM6l +EOCmgAS8H+TgRuTIvqNppYs/1Q/SfOt6Gw/0qv0HBQtDuwbuQzbIt/YuAyUjXTni +CSvz5/3GCtGuCG4wQLw+ZRYadfLSwNv/c6yX8fdkOxpxdWrl/ixnZVy8+9b3q0Zx +J645eDywxWEtFGFBwNxsOkJVKXFuvG6S2MQhG22jH6tPFsGl4n7bgNEJmFch8EyX +bbkacEqJmpF1TW3F7d4lhg54fC6ex8mPtMYCtCAbTdmVBwv6Q1AmR2SpuWwwLlFv +sTe1ogJAvtvWkiHbG0tfVgNi3R3I6JfyAagwzJQcz3qsVKgfB5KHZCJqrDDDb1b6 +QA93ii2B/a+xQUDE/31NlraIuPKbQa8BWMoUxf/5JTuCSvM3jSPVh4Q= +-----END ENCRYPTED PRIVATE KEY----- diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/simpleEncryptDecrypt.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/simpleEncryptDecrypt.pdf new file mode 100644 index 0000000000..7f24d3a4fc Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/simpleEncryptDecrypt.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/simpleEncryptDecrypt_1_7.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/simpleEncryptDecrypt_1_7.pdf new file mode 100644 index 0000000000..7f24d3a4fc Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/simpleEncryptDecrypt_1_7.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/test.cer b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/test.cer similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/test.cer rename to itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/test.cer diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/test.pem b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/test.pem new file mode 100644 index 0000000000..9a9aba7c6a --- /dev/null +++ b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcmTest/test.pem @@ -0,0 +1,51 @@ +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQdOaEUfD0sZWtUR11 +xwgn0gICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEBaNXSfwUjF5SS7n +ce1JFoUEggTQ6eV+IsckiVP7I9VTldLkpP5OKB8brmw5t20fO11HyCnqkkhooR2b +t2fBj4fWv0IRUe266L+fVs7AOngjkWfezEvGR6nte4pNXEFrOwt/U8A6IYZXBdA5 +dvqs6VMPHbjQ8CufVLGvksuYFQVRcGy0rk1DH2Of44GU4X0GtROlFFJnkmfZhVPS +Hx2MXXGQ02Ko1i1eKoEGgvmSAsDcPijiX96DKlQZJ4YMtI/8rRsdvNJsJ2beyZDa +T3aJMmSSBF92mS2dtS21DwjzEu8utquguYA0KYzjZM9onOuBEEUifam8Fjnvlui6 +beQJya4zldoA6QZPSd2PUAP6l1U/d8UXqcisjzArDZDmRu58dPxn4rs0NgTOIO8h +fEUIvfS+wuknff1b/wdGnwXkXoeSrrjS9dhP9KVU1SJ/FWKc6BY+P+JmE5vLjAtn +AmbyZhXY0jX7ZHFh0z0y1y1fTIXL1aj4iB+cUwhJ1ZdlGkT5HdG4ts/oTGCnpB6O +F1GvGyhprmtjp/dspLH5ha0I+4aTn46yFpnBNyg8w9c2+xj8Jiqy9J/ppVtPdhxt +wrE1/ThUGIWUTsbGbLW87WIrZq6IlSGtztbxAMYxXoe4solYueE3pI3eYFzgnBcq +T6Byktr71gt9AGD/N/p+Kk5RM4JT8XpQjLjz9TlmsGpJzUoBGeG6KFLsqqLLSD+0 +c5lAGWsFhec3uCu4fCyBqxpQc0y5j2bgUiTRGYn1NOdyZg+ERO/aWGfkDOAtlL1i +B79NGIBxIXgt508g83UeaQC6KjuG/8hPY6UHmU5mlgRT9H5jvkSX3mEtl1Gdk2y0 +M5pZTTrhbG4p66GhBi8vM5tQfiBoLUKEM/kgiGXPC6Kob42nb3ufP0rmnKklcDGC ++898hW5ge+VNmOkHpVuV5ZD9aWUSVEU4+8QNZj8pcyL0GXFyEL/HxNxUESdz3k0S +bInuxO49mgGPjBqtx5ZvaxyWFnzOp6rmHZUHymejxxdnlnTnSnXKkJFjcm7n0sKO +575ofHtk0OdqIK6YiPgfeF6nZkIg3C0PbReZ05kTplrW182ZWuQQyJgv+RPzF4+9 +5rCe67nJhJrt7hXFRsUScHXNj+HF9Av8WR2RnHTRbpQBJszijM+Xgl+VeYcY5ckB +fk+AfcR9r0Jud4O9795OOWVxWqGVu/b1RGonfjMkGW+JdnZL0vkOYYcHt4iMZmzW +M0ZowZPGO5dFBV7/ZkVzb0fexw+f+E0lUBEK1cx0gxnzjmcGJO+C9if1uIEfwpon +3wBOTDsU7XKDx9v6ibcDMOXrZa+rcJWxgNkXt5nRpozZkddYctBkehGu+snV2g4n +SdOwr0eIVv/L+v4IywZmeWWEVnbSAvB0p7nB89bgLMr9tV0ly7MWxPH+gPnNJ1gE +7Mp3AgN5BxEmLfW3+ou3QLoqnOS2MCw/xcgLP0nJACSPI7/nWy95iKXKgkCkAgF9 +4Ztk7uBG4tiK14KcKq8ToCW2YNliT3g0CWjBLtVPUS6qboudMiuedxTxE8WEirpT +A77nfDNg4MVjl4kP9jhV0Phpn9rDMJ2jw0BqFc1Vou4aNDXYandAFJea44Wce9H+ +qAowcrfsWehD01HBQ2KwWVg3sLnwwBHw0nvbATS41hdxsP2OmCnxWkc= +-----END ENCRYPTED PRIVATE KEY----- +-----BEGIN CERTIFICATE----- +MIIDfzCCAmegAwIBAgIEUFic9zANBgkqhkiG9w0BAQsFADBvMQswCQYDVQQGEwJU +UzETMBEGA1UECBMKVGVzdCBTdGF0ZTESMBAGA1UEBxMJVGVzdCBUb3duMREwDwYD +VQQKEwhUZXN0IG9yZzEQMA4GA1UECxMHVGVzdCBPVTESMBAGA1UEAxMJVGVzdCBV +c2VyMCAXDTE0MDkyMjA5MTExMVoYDzIxMTQwODI5MDkxMTExWjBvMQswCQYDVQQG +EwJUUzETMBEGA1UECBMKVGVzdCBTdGF0ZTESMBAGA1UEBxMJVGVzdCBUb3duMREw +DwYDVQQKEwhUZXN0IG9yZzEQMA4GA1UECxMHVGVzdCBPVTESMBAGA1UEAxMJVGVz +dCBVc2VyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA+6g5sYzXiNOA +hR7C8wc8buxU/JgcbdHpHIR44iuXjpepBYAE7hRsWM7H4cuXrKiRxS9UMOadqkGF +Qqb5sG6lo2UUhcj4qlN6hKDc/+AMZMIW1mvQldiygCAkqgM8iso+kw56dpVuerG/ +k1nd8f+X9rjXN6/DIMznZcMy2d9ByIFuixFKElPvOWx9q9N4aiueOd5FM5eHxp+3 +F4uCTrpM5zkS7Rmf5GVtCofc8KgaTLLp4D0Ge5VUJm7yW8fuU3eIpin4ivjk+Gye +Q3t0BsrmNyQy3CmKGOBP/vX0+wEMvGN2xqNgAFP9dxA+AbJMiAfsmoWvxXaPktqC +DOspTCFqbwIDAQABoyEwHzAdBgNVHQ4EFgQUILviRCmSrhuLDmF0nus4pv2uu7gw +DQYJKoZIhvcNAQELBQADggEBAGnfGYL7nDm5taDPRxuGGMqUPwRnH2bXwef6S2Xb +/nIEFtNheVFQFtKNn5Ikq68DTFMP06yXLnI7F40+ZiQezRBB1EPPmDL2fYKc9fL1 +SHntu6HLgP/Y5nnCVegtL8l9745gQZnnXlMtkTs2HFwffznIHW/3STO0Bcj0+KMa +p8vebMjmvV7bZEGvrcrVXL55QPZXJwRuQMXJB3f5XhAEH1VqAhTW6DrvBUnuESwo +9fxxA5gmblt80SQYdKr2I08OTk0qmyF8zNuffTOiSS8/V6Cf7CntuPWjSuVf1EVP +MH6KkSjceLZ99Y7bvl7KKvQ4Kj5Bp27PwlRvtYbfCUmQEG8= +-----END CERTIFICATE----- diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/StandardHandlerUsingAesGcmTest/cmp_encryptedSimpleDocument.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/StandardHandlerUsingAesGcmTest/cmp_encryptedSimpleDocument.pdf new file mode 100644 index 0000000000..51981cdead Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/StandardHandlerUsingAesGcmTest/cmp_encryptedSimpleDocument.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/StandardHandlerUsingAesGcmTest/encryptedDocument.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/StandardHandlerUsingAesGcmTest/encryptedDocument.pdf new file mode 100644 index 0000000000..07df73faa8 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/StandardHandlerUsingAesGcmTest/encryptedDocument.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/StandardHandlerUsingAesGcmTest/encryptedDocumentTamperedCiphertext.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/StandardHandlerUsingAesGcmTest/encryptedDocumentTamperedCiphertext.pdf new file mode 100644 index 0000000000..9bd2097f6d Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/StandardHandlerUsingAesGcmTest/encryptedDocumentTamperedCiphertext.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/StandardHandlerUsingAesGcmTest/encryptedDocumentTamperedIv.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/StandardHandlerUsingAesGcmTest/encryptedDocumentTamperedIv.pdf new file mode 100644 index 0000000000..fc50c51615 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/StandardHandlerUsingAesGcmTest/encryptedDocumentTamperedIv.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/StandardHandlerUsingAesGcmTest/encryptedDocumentTamperedMac.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/StandardHandlerUsingAesGcmTest/encryptedDocumentTamperedMac.pdf new file mode 100644 index 0000000000..93d25ec16d Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/StandardHandlerUsingAesGcmTest/encryptedDocumentTamperedMac.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/StandardHandlerUsingAesGcmTest/simpleDocument.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/StandardHandlerUsingAesGcmTest/simpleDocument.pdf new file mode 100644 index 0000000000..7f24d3a4fc Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/securityhandler/StandardHandlerUsingAesGcmTest/simpleDocument.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/font/PdfType3FontTest/type3FontMultipleCodesToOneGlyph.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/font/PdfType3FontTest/type3FontMultipleCodesToOneGlyph.pdf deleted file mode 100644 index 80b78eebcd..0000000000 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/font/PdfType3FontTest/type3FontMultipleCodesToOneGlyph.pdf and /dev/null differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/font/PdfType3FontTest/type3FontWithCustomNames.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/font/PdfType3FontTest/type3FontWithCustomNames.pdf deleted file mode 100644 index 9c85f4294b..0000000000 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/font/PdfType3FontTest/type3FontWithCustomNames.pdf and /dev/null differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/certs/SHA256withRSA.cer b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/certs/SHA256withRSA.cer new file mode 100644 index 0000000000..fbaad2b382 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/certs/SHA256withRSA.cer differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/certs/SHA256withRSA.key b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/certs/SHA256withRSA.key new file mode 100644 index 0000000000..d7e9b5e825 --- /dev/null +++ b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/certs/SHA256withRSA.key @@ -0,0 +1,51 @@ +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQdOaEUfD0sZWtUR11 +xwgn0gICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEBaNXSfwUjF5SS7n +ce1JFoUEggTQ6eV+IsckiVP7I9VTldLkpP5OKB8brmw5t20fO11HyCnqkkhooR2b +t2fBj4fWv0IRUe266L+fVs7AOngjkWfezEvGR6nte4pNXEFrOwt/U8A6IYZXBdA5 +dvqs6VMPHbjQ8CufVLGvksuYFQVRcGy0rk1DH2Of44GU4X0GtROlFFJnkmfZhVPS +Hx2MXXGQ02Ko1i1eKoEGgvmSAsDcPijiX96DKlQZJ4YMtI/8rRsdvNJsJ2beyZDa +T3aJMmSSBF92mS2dtS21DwjzEu8utquguYA0KYzjZM9onOuBEEUifam8Fjnvlui6 +beQJya4zldoA6QZPSd2PUAP6l1U/d8UXqcisjzArDZDmRu58dPxn4rs0NgTOIO8h +fEUIvfS+wuknff1b/wdGnwXkXoeSrrjS9dhP9KVU1SJ/FWKc6BY+P+JmE5vLjAtn +AmbyZhXY0jX7ZHFh0z0y1y1fTIXL1aj4iB+cUwhJ1ZdlGkT5HdG4ts/oTGCnpB6O +F1GvGyhprmtjp/dspLH5ha0I+4aTn46yFpnBNyg8w9c2+xj8Jiqy9J/ppVtPdhxt +wrE1/ThUGIWUTsbGbLW87WIrZq6IlSGtztbxAMYxXoe4solYueE3pI3eYFzgnBcq +T6Byktr71gt9AGD/N/p+Kk5RM4JT8XpQjLjz9TlmsGpJzUoBGeG6KFLsqqLLSD+0 +c5lAGWsFhec3uCu4fCyBqxpQc0y5j2bgUiTRGYn1NOdyZg+ERO/aWGfkDOAtlL1i +B79NGIBxIXgt508g83UeaQC6KjuG/8hPY6UHmU5mlgRT9H5jvkSX3mEtl1Gdk2y0 +M5pZTTrhbG4p66GhBi8vM5tQfiBoLUKEM/kgiGXPC6Kob42nb3ufP0rmnKklcDGC ++898hW5ge+VNmOkHpVuV5ZD9aWUSVEU4+8QNZj8pcyL0GXFyEL/HxNxUESdz3k0S +bInuxO49mgGPjBqtx5ZvaxyWFnzOp6rmHZUHymejxxdnlnTnSnXKkJFjcm7n0sKO +575ofHtk0OdqIK6YiPgfeF6nZkIg3C0PbReZ05kTplrW182ZWuQQyJgv+RPzF4+9 +5rCe67nJhJrt7hXFRsUScHXNj+HF9Av8WR2RnHTRbpQBJszijM+Xgl+VeYcY5ckB +fk+AfcR9r0Jud4O9795OOWVxWqGVu/b1RGonfjMkGW+JdnZL0vkOYYcHt4iMZmzW +M0ZowZPGO5dFBV7/ZkVzb0fexw+f+E0lUBEK1cx0gxnzjmcGJO+C9if1uIEfwpon +3wBOTDsU7XKDx9v6ibcDMOXrZa+rcJWxgNkXt5nRpozZkddYctBkehGu+snV2g4n +SdOwr0eIVv/L+v4IywZmeWWEVnbSAvB0p7nB89bgLMr9tV0ly7MWxPH+gPnNJ1gE +7Mp3AgN5BxEmLfW3+ou3QLoqnOS2MCw/xcgLP0nJACSPI7/nWy95iKXKgkCkAgF9 +4Ztk7uBG4tiK14KcKq8ToCW2YNliT3g0CWjBLtVPUS6qboudMiuedxTxE8WEirpT +A77nfDNg4MVjl4kP9jhV0Phpn9rDMJ2jw0BqFc1Vou4aNDXYandAFJea44Wce9H+ +qAowcrfsWehD01HBQ2KwWVg3sLnwwBHw0nvbATS41hdxsP2OmCnxWkc= +-----END ENCRYPTED PRIVATE KEY----- +-----BEGIN CERTIFICATE----- +MIIDfzCCAmegAwIBAgIEUFic9zANBgkqhkiG9w0BAQsFADBvMQswCQYDVQQGEwJU +UzETMBEGA1UECBMKVGVzdCBTdGF0ZTESMBAGA1UEBxMJVGVzdCBUb3duMREwDwYD +VQQKEwhUZXN0IG9yZzEQMA4GA1UECxMHVGVzdCBPVTESMBAGA1UEAxMJVGVzdCBV +c2VyMCAXDTE0MDkyMjA5MTExMVoYDzIxMTQwODI5MDkxMTExWjBvMQswCQYDVQQG +EwJUUzETMBEGA1UECBMKVGVzdCBTdGF0ZTESMBAGA1UEBxMJVGVzdCBUb3duMREw +DwYDVQQKEwhUZXN0IG9yZzEQMA4GA1UECxMHVGVzdCBPVTESMBAGA1UEAxMJVGVz +dCBVc2VyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA+6g5sYzXiNOA +hR7C8wc8buxU/JgcbdHpHIR44iuXjpepBYAE7hRsWM7H4cuXrKiRxS9UMOadqkGF +Qqb5sG6lo2UUhcj4qlN6hKDc/+AMZMIW1mvQldiygCAkqgM8iso+kw56dpVuerG/ +k1nd8f+X9rjXN6/DIMznZcMy2d9ByIFuixFKElPvOWx9q9N4aiueOd5FM5eHxp+3 +F4uCTrpM5zkS7Rmf5GVtCofc8KgaTLLp4D0Ge5VUJm7yW8fuU3eIpin4ivjk+Gye +Q3t0BsrmNyQy3CmKGOBP/vX0+wEMvGN2xqNgAFP9dxA+AbJMiAfsmoWvxXaPktqC +DOspTCFqbwIDAQABoyEwHzAdBgNVHQ4EFgQUILviRCmSrhuLDmF0nus4pv2uu7gw +DQYJKoZIhvcNAQELBQADggEBAGnfGYL7nDm5taDPRxuGGMqUPwRnH2bXwef6S2Xb +/nIEFtNheVFQFtKNn5Ikq68DTFMP06yXLnI7F40+ZiQezRBB1EPPmDL2fYKc9fL1 +SHntu6HLgP/Y5nnCVegtL8l9745gQZnnXlMtkTs2HFwffznIHW/3STO0Bcj0+KMa +p8vebMjmvV7bZEGvrcrVXL55QPZXJwRuQMXJB3f5XhAEH1VqAhTW6DrvBUnuESwo +9fxxA5gmblt80SQYdKr2I08OTk0qmyF8zNuffTOiSS8/V6Cf7CntuPWjSuVf1EVP +MH6KkSjceLZ99Y7bvl7KKvQ4Kj5Bp27PwlRvtYbfCUmQEG8= +-----END CERTIFICATE----- diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_addMacOnAppendModeTest.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_addMacOnAppendModeTest.pdf new file mode 100644 index 0000000000..792884c274 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_addMacOnAppendModeTest.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_addMacOnPreserveEncryptionFor17DocTest.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_addMacOnPreserveEncryptionFor17DocTest.pdf new file mode 100644 index 0000000000..2a95592bc0 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_addMacOnPreserveEncryptionFor17DocTest.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_addMacOnPreserveEncryptionTest.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_addMacOnPreserveEncryptionTest.pdf new file mode 100644 index 0000000000..86eb20d0c6 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_addMacOnPreserveEncryptionTest.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_addMacOnPreserveEncryptionWhileDowngradingTest.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_addMacOnPreserveEncryptionWhileDowngradingTest.pdf new file mode 100644 index 0000000000..31820a46c0 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_addMacOnPreserveEncryptionWhileDowngradingTest.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_addMacOnPreservePublicKeyEncryptionTest.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_addMacOnPreservePublicKeyEncryptionTest.pdf new file mode 100644 index 0000000000..ea6b7c705d Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_addMacOnPreservePublicKeyEncryptionTest.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_addMacWithDisableMacPropertyTest.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_addMacWithDisableMacPropertyTest.pdf new file mode 100644 index 0000000000..0bca6b434c Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_addMacWithDisableMacPropertyTest.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_macEncryptionWithAesGsmTest.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_macEncryptionWithAesGsmTest.pdf new file mode 100644 index 0000000000..995f5df2fb Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_macEncryptionWithAesGsmTest.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_noMacProtectionTest.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_noMacProtectionTest.pdf new file mode 100644 index 0000000000..963d5074ab Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_noMacProtectionTest.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_standaloneMacPublicKeyEncryptionTest.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_standaloneMacPublicKeyEncryptionTest.pdf new file mode 100644 index 0000000000..3eb997bda3 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_standaloneMacPublicKeyEncryptionTest.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_standaloneMacStandardEncryptionTest.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_standaloneMacStandardEncryptionTest.pdf new file mode 100644 index 0000000000..f8bffedbdc Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_standaloneMacStandardEncryptionTest.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_standaloneMacWithAllHashAlgorithmsTest1.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_standaloneMacWithAllHashAlgorithmsTest1.pdf new file mode 100644 index 0000000000..0c296530e4 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_standaloneMacWithAllHashAlgorithmsTest1.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_standaloneMacWithAllHashAlgorithmsTest2.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_standaloneMacWithAllHashAlgorithmsTest2.pdf new file mode 100644 index 0000000000..396ef5bb01 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_standaloneMacWithAllHashAlgorithmsTest2.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_standaloneMacWithAllHashAlgorithmsTest3.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_standaloneMacWithAllHashAlgorithmsTest3.pdf new file mode 100644 index 0000000000..b2b994a544 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_standaloneMacWithAllHashAlgorithmsTest3.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_standaloneMacWithAllHashAlgorithmsTest4.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_standaloneMacWithAllHashAlgorithmsTest4.pdf new file mode 100644 index 0000000000..54aac71803 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_standaloneMacWithAllHashAlgorithmsTest4.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_standaloneMacWithAllHashAlgorithmsTest5.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_standaloneMacWithAllHashAlgorithmsTest5.pdf new file mode 100644 index 0000000000..e4dfce5bbe Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_standaloneMacWithAllHashAlgorithmsTest5.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_standaloneMacWithAllHashAlgorithmsTest6.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_standaloneMacWithAllHashAlgorithmsTest6.pdf new file mode 100644 index 0000000000..9b6fe69a20 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/cmp_standaloneMacWithAllHashAlgorithmsTest6.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/noMacProtectionDocument.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/noMacProtectionDocument.pdf new file mode 100644 index 0000000000..318f529543 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/noMacProtectionDocument.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/noMacProtectionDocument_1_7.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/noMacProtectionDocument_1_7.pdf new file mode 100644 index 0000000000..db862c7069 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/noMacProtectionDocument_1_7.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/noMacProtectionPublicKeyEncryptionDocument.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/noMacProtectionPublicKeyEncryptionDocument.pdf new file mode 100644 index 0000000000..4b5a106e64 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorCreationTest/noMacProtectionPublicKeyEncryptionDocument.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/certs/SHA256withRSA.cer b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/certs/SHA256withRSA.cer new file mode 100644 index 0000000000..fbaad2b382 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/certs/SHA256withRSA.cer differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/certs/SHA256withRSA.key b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/certs/SHA256withRSA.key new file mode 100644 index 0000000000..d7e9b5e825 --- /dev/null +++ b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/certs/SHA256withRSA.key @@ -0,0 +1,51 @@ +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQdOaEUfD0sZWtUR11 +xwgn0gICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEBaNXSfwUjF5SS7n +ce1JFoUEggTQ6eV+IsckiVP7I9VTldLkpP5OKB8brmw5t20fO11HyCnqkkhooR2b +t2fBj4fWv0IRUe266L+fVs7AOngjkWfezEvGR6nte4pNXEFrOwt/U8A6IYZXBdA5 +dvqs6VMPHbjQ8CufVLGvksuYFQVRcGy0rk1DH2Of44GU4X0GtROlFFJnkmfZhVPS +Hx2MXXGQ02Ko1i1eKoEGgvmSAsDcPijiX96DKlQZJ4YMtI/8rRsdvNJsJ2beyZDa +T3aJMmSSBF92mS2dtS21DwjzEu8utquguYA0KYzjZM9onOuBEEUifam8Fjnvlui6 +beQJya4zldoA6QZPSd2PUAP6l1U/d8UXqcisjzArDZDmRu58dPxn4rs0NgTOIO8h +fEUIvfS+wuknff1b/wdGnwXkXoeSrrjS9dhP9KVU1SJ/FWKc6BY+P+JmE5vLjAtn +AmbyZhXY0jX7ZHFh0z0y1y1fTIXL1aj4iB+cUwhJ1ZdlGkT5HdG4ts/oTGCnpB6O +F1GvGyhprmtjp/dspLH5ha0I+4aTn46yFpnBNyg8w9c2+xj8Jiqy9J/ppVtPdhxt +wrE1/ThUGIWUTsbGbLW87WIrZq6IlSGtztbxAMYxXoe4solYueE3pI3eYFzgnBcq +T6Byktr71gt9AGD/N/p+Kk5RM4JT8XpQjLjz9TlmsGpJzUoBGeG6KFLsqqLLSD+0 +c5lAGWsFhec3uCu4fCyBqxpQc0y5j2bgUiTRGYn1NOdyZg+ERO/aWGfkDOAtlL1i +B79NGIBxIXgt508g83UeaQC6KjuG/8hPY6UHmU5mlgRT9H5jvkSX3mEtl1Gdk2y0 +M5pZTTrhbG4p66GhBi8vM5tQfiBoLUKEM/kgiGXPC6Kob42nb3ufP0rmnKklcDGC ++898hW5ge+VNmOkHpVuV5ZD9aWUSVEU4+8QNZj8pcyL0GXFyEL/HxNxUESdz3k0S +bInuxO49mgGPjBqtx5ZvaxyWFnzOp6rmHZUHymejxxdnlnTnSnXKkJFjcm7n0sKO +575ofHtk0OdqIK6YiPgfeF6nZkIg3C0PbReZ05kTplrW182ZWuQQyJgv+RPzF4+9 +5rCe67nJhJrt7hXFRsUScHXNj+HF9Av8WR2RnHTRbpQBJszijM+Xgl+VeYcY5ckB +fk+AfcR9r0Jud4O9795OOWVxWqGVu/b1RGonfjMkGW+JdnZL0vkOYYcHt4iMZmzW +M0ZowZPGO5dFBV7/ZkVzb0fexw+f+E0lUBEK1cx0gxnzjmcGJO+C9if1uIEfwpon +3wBOTDsU7XKDx9v6ibcDMOXrZa+rcJWxgNkXt5nRpozZkddYctBkehGu+snV2g4n +SdOwr0eIVv/L+v4IywZmeWWEVnbSAvB0p7nB89bgLMr9tV0ly7MWxPH+gPnNJ1gE +7Mp3AgN5BxEmLfW3+ou3QLoqnOS2MCw/xcgLP0nJACSPI7/nWy95iKXKgkCkAgF9 +4Ztk7uBG4tiK14KcKq8ToCW2YNliT3g0CWjBLtVPUS6qboudMiuedxTxE8WEirpT +A77nfDNg4MVjl4kP9jhV0Phpn9rDMJ2jw0BqFc1Vou4aNDXYandAFJea44Wce9H+ +qAowcrfsWehD01HBQ2KwWVg3sLnwwBHw0nvbATS41hdxsP2OmCnxWkc= +-----END ENCRYPTED PRIVATE KEY----- +-----BEGIN CERTIFICATE----- +MIIDfzCCAmegAwIBAgIEUFic9zANBgkqhkiG9w0BAQsFADBvMQswCQYDVQQGEwJU +UzETMBEGA1UECBMKVGVzdCBTdGF0ZTESMBAGA1UEBxMJVGVzdCBUb3duMREwDwYD +VQQKEwhUZXN0IG9yZzEQMA4GA1UECxMHVGVzdCBPVTESMBAGA1UEAxMJVGVzdCBV +c2VyMCAXDTE0MDkyMjA5MTExMVoYDzIxMTQwODI5MDkxMTExWjBvMQswCQYDVQQG +EwJUUzETMBEGA1UECBMKVGVzdCBTdGF0ZTESMBAGA1UEBxMJVGVzdCBUb3duMREw +DwYDVQQKEwhUZXN0IG9yZzEQMA4GA1UECxMHVGVzdCBPVTESMBAGA1UEAxMJVGVz +dCBVc2VyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA+6g5sYzXiNOA +hR7C8wc8buxU/JgcbdHpHIR44iuXjpepBYAE7hRsWM7H4cuXrKiRxS9UMOadqkGF +Qqb5sG6lo2UUhcj4qlN6hKDc/+AMZMIW1mvQldiygCAkqgM8iso+kw56dpVuerG/ +k1nd8f+X9rjXN6/DIMznZcMy2d9ByIFuixFKElPvOWx9q9N4aiueOd5FM5eHxp+3 +F4uCTrpM5zkS7Rmf5GVtCofc8KgaTLLp4D0Ge5VUJm7yW8fuU3eIpin4ivjk+Gye +Q3t0BsrmNyQy3CmKGOBP/vX0+wEMvGN2xqNgAFP9dxA+AbJMiAfsmoWvxXaPktqC +DOspTCFqbwIDAQABoyEwHzAdBgNVHQ4EFgQUILviRCmSrhuLDmF0nus4pv2uu7gw +DQYJKoZIhvcNAQELBQADggEBAGnfGYL7nDm5taDPRxuGGMqUPwRnH2bXwef6S2Xb +/nIEFtNheVFQFtKNn5Ikq68DTFMP06yXLnI7F40+ZiQezRBB1EPPmDL2fYKc9fL1 +SHntu6HLgP/Y5nnCVegtL8l9745gQZnnXlMtkTs2HFwffznIHW/3STO0Bcj0+KMa +p8vebMjmvV7bZEGvrcrVXL55QPZXJwRuQMXJB3f5XhAEH1VqAhTW6DrvBUnuESwo +9fxxA5gmblt80SQYdKr2I08OTk0qmyF8zNuffTOiSS8/V6Cf7CntuPWjSuVf1EVP +MH6KkSjceLZ99Y7bvl7KKvQ4Kj5Bp27PwlRvtYbfCUmQEG8= +-----END CERTIFICATE----- diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/certs/certForEncryption.crt b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/certs/certForEncryption.crt new file mode 100644 index 0000000000..9b472214d4 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/certs/certForEncryption.crt differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/certs/keyForEncryption.pem b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/certs/keyForEncryption.pem new file mode 100644 index 0000000000..068689ceaa --- /dev/null +++ b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/certs/keyForEncryption.pem @@ -0,0 +1,30 @@ +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQw74LmQhymYGN8QhZ +NXA6/QICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEAQIEEAw8/Oa2xvlCpECW +RKztuKUEggTQiWBW4ih3uPsyF3rmJbCU+ipcKTe6NcDEIowHxY1BH0MjvlO7KBaB +Qxg+9mz9yf05lz9CkrPvd8HCjpLa0+v4tzsBq55me6flqYTq8udtVkzCSigPkWkb +35QjCG1FHNUN4Fxc+YlZfbMvCCW2e7uGvANXtAeUNq8oo7bGOJUizdcs8V8CJ0t2 +UtXIYWV72WHznn4qZNcQBtAwFtL8tO/mpan+J0TLbydWu+oK8aDvTwkVs4DQPBp/ +ztEBMPuyJXSoChxzh4IpWlKBJoWkTXZpBZds9zjQ21JV3QeCxqBvAqlY0YBChOMh +HSxGhIuCQlj+44BjFUVYfGYTCulW/qLd+fS/fZGe7PKEoXxA71+uC47oCQMQKZda +XBOqYEGhoXg3XRidPK0yGSkRsSpyhVGgffy5c+ckDW2b9CO3IRAFIqI06QgW9tBt +Wfk30KfhbRADQ08p9zEaEchKUyEZLcAp0b+UHl0ocL1Up/tfygv5atqwvoR/aL3p +lX4yAfDPDIXSY7wF13WPwx8FbebPSd3T2OZQB9q07gjLgkczbRSvq+7muFCFCNPH +mBtyZl8WQqE85yz/jrvkSQG+6TCLgXEJvNxOvw4tmDDvWxW2bKKnij3fUDKHlop5 +6ypojj8jcfFJVUVGbxEdD19mTvnBTSY1Kv1h6D2CEBLzMuYyZaomwWfUD0oGIdfA +ImuI+WhFXcY5GIo0yWPbu1L0HWH9xJObEM9MhNdLm1LIY3rQ0OoNipDAFrLv9jfc +W9Ef9VPklv5lO6HhfAhEQgRvdP9NAY8U66287lioRUuTU9O1MULZETg7Or08JIMP +qIeKYWxrmXEuaS0S6i1Q65WF9ayP5mEragIBiEQpTm5C6BVk3cxv2GVN84HyEdRQ +ekAQyRbZQitzkRGv8Nf30GXlhEz1vgiG2tylfvLmAhL5y4BE51YrrBtoljeLTm59 +2kGSXYUqN5bTlvjk/v/kflRpMNCPzJAMP59dkY0ithoiQJn3VHbRiqB0NwxuRtpM +EpYTkBiItKhlpVA48pX/kfNbk8t7cp5Xo/FFo5gupygYZOJI1LnEQyoGoqR8n8wO +XzyAqzQFyhtAyOkTQMn10x6s2g3mjnYnfify/9oJQstX4Q2UNChwLresxpv/fcDF +rJjG5Qq5kvbZjGsdYcT6O89DGWWTHVPZdKe9MApaw1hb/q8OhueCrVgudZES/A9t +jx0F7TSoEPcm5yTAWCZfdsukI4Vtfj0x653uhFlu4DpRIxw06yLjH+6Sb6abvDoS +LpDs1l/doQI6CJOcPw0uESEAXkj7tWmyCSXxFnG0hor7w5Oaz82hpQcc/mZ09p4O +PqP0QBU/dUzHgSQdhZHDBXY5NT6laEQMMzdnyYdFanxdoinWMY4RvgmjwRFU9rQg +N72sYdZZ8GD0mG3k8ZhSt3rs4+sraDo38BqOFtNGBGE9LMyP8AqQtfbABPl8VAb6 +MrI4tVuUpo/vD68tFfDk2flH36jvmZoAUUgGINn1GFgTJXXC+embg6lHAu3GgeQC +9TOrtNzKjIj7jX3sECgmPEBS+9HymrGhSue9klq0/iptRLIrXWuuB5TtBD5PGG15 +Afn2MfHM5IR8Bls+5khYRtoM5M+TdfkAjvsFUpD1YXehn/aTO2BzquE= +-----END ENCRYPTED PRIVATE KEY----- diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/cmp_appendModeTest.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/cmp_appendModeTest.pdf new file mode 100644 index 0000000000..31dafb6472 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/cmp_appendModeTest.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/cmp_disableMacInAppendModeTest.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/cmp_disableMacInAppendModeTest.pdf new file mode 100644 index 0000000000..acd6ea98f1 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/cmp_disableMacInAppendModeTest.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/cmp_disableMacTest.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/cmp_disableMacTest.pdf new file mode 100644 index 0000000000..833985f2e5 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/cmp_disableMacTest.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/cmp_doNotThrowOnValidationTest1.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/cmp_doNotThrowOnValidationTest1.pdf new file mode 100644 index 0000000000..b1117bb947 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/cmp_doNotThrowOnValidationTest1.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/cmp_doNotThrowOnValidationTest2.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/cmp_doNotThrowOnValidationTest2.pdf new file mode 100644 index 0000000000..593d11e8fd Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/cmp_doNotThrowOnValidationTest2.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/cmp_macShouldNotBePreservedTest.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/cmp_macShouldNotBePreservedTest.pdf new file mode 100644 index 0000000000..079ab91ce5 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/cmp_macShouldNotBePreservedTest.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/cmp_macShouldNotBePreservedWithEncryptionTest.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/cmp_macShouldNotBePreservedWithEncryptionTest.pdf new file mode 100644 index 0000000000..c74d7239e3 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/cmp_macShouldNotBePreservedWithEncryptionTest.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/cmp_preserveEncryptionTest.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/cmp_preserveEncryptionTest.pdf new file mode 100644 index 0000000000..abefee33ed Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/cmp_preserveEncryptionTest.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/cmp_writerPropertiesTest.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/cmp_writerPropertiesTest.pdf new file mode 100644 index 0000000000..00f32869cb Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/cmp_writerPropertiesTest.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/invalidMacProtectedDocument.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/invalidMacProtectedDocument.pdf new file mode 100644 index 0000000000..e88e53f82d Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/invalidMacProtectedDocument.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/invalidPublicKeyMacProtectedDocument.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/invalidPublicKeyMacProtectedDocument.pdf new file mode 100644 index 0000000000..728bd49ad9 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/invalidPublicKeyMacProtectedDocument.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/macProtectedDocument.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/macProtectedDocument.pdf new file mode 100644 index 0000000000..7e180dbf47 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/macProtectedDocument.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/macProtectedDocumentPdf1_7.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/macProtectedDocumentPdf1_7.pdf new file mode 100644 index 0000000000..e3410f2fc7 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/macProtectedDocumentPdf1_7.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/macProtectionStrippedTest.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/macProtectionStrippedTest.pdf new file mode 100644 index 0000000000..f772dea961 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/macProtectionStrippedTest.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/noSaltTest.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/noSaltTest.pdf new file mode 100644 index 0000000000..dcf9bc7117 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/noSaltTest.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/signedMacProtectedDocWithoutAttribute.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/signedMacProtectedDocWithoutAttribute.pdf new file mode 100644 index 0000000000..27038d63b0 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/signedMacProtectedDocWithoutAttribute.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/signedMacProtectedDocument.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/signedMacProtectedDocument.pdf new file mode 100644 index 0000000000..0f8a456338 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/signedMacProtectedDocument.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/thirdPartyMacProtectedDocument.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/thirdPartyMacProtectedDocument.pdf new file mode 100644 index 0000000000..1850292a1a Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/thirdPartyMacProtectedDocument.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/thirdPartyMacProtectedDocumentTampered.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/thirdPartyMacProtectedDocumentTampered.pdf new file mode 100644 index 0000000000..026b98534e Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/thirdPartyMacProtectedDocumentTampered.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/thirdPartyPublicKeyMacProtectedDocument.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/thirdPartyPublicKeyMacProtectedDocument.pdf new file mode 100644 index 0000000000..766820a649 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/mac/MacIntegrityProtectorReadingAndRewritingTest/thirdPartyPublicKeyMacProtectedDocument.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/parser/GlyphTextEventListenerTest/test_dec.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/parser/GlyphTextEventListenerTest/test_dec.pdf deleted file mode 100644 index 0778c3ccd8..0000000000 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/parser/GlyphTextEventListenerTest/test_dec.pdf and /dev/null differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/parser/LocationExtractionTest/AliceInWonderlandMarked.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/parser/LocationExtractionTest/AliceInWonderlandMarked.pdf deleted file mode 100644 index d9d1b7faf2..0000000000 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/parser/LocationExtractionTest/AliceInWonderlandMarked.pdf and /dev/null differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/parser/RegexBasedLocationExtractionStrategyTest/in00.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/parser/RegexBasedLocationExtractionStrategyTest/in00.pdf new file mode 100644 index 0000000000..1526edb58c Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/parser/RegexBasedLocationExtractionStrategyTest/in00.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfActionTest/placeholderTest05.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfActionTest/placeholderTest05.pdf deleted file mode 100644 index da43b2a6d5..0000000000 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfActionTest/placeholderTest05.pdf and /dev/null differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfDocumentTest/20000PagesDocument.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfDocumentTest/20000PagesDocument.pdf deleted file mode 100644 index 60261cc670..0000000000 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfDocumentTest/20000PagesDocument.pdf and /dev/null differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfDocumentTest/cmp_pdfDocWithAAndUaMetadata.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfDocumentTest/cmp_pdfDocWithAAndUaMetadata.pdf new file mode 100644 index 0000000000..0a3149d4f2 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfDocumentTest/cmp_pdfDocWithAAndUaMetadata.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfDocumentTest/cmp_removedDuplicateInOrderArray.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfDocumentTest/cmp_removedDuplicateInOrderArray.pdf new file mode 100644 index 0000000000..602e3a4c81 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfDocumentTest/cmp_removedDuplicateInOrderArray.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfDocumentTest/cmp_removedNestedDuplicatesInOrderArray.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfDocumentTest/cmp_removedNestedDuplicatesInOrderArray.pdf new file mode 100644 index 0000000000..9da2248dfa Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfDocumentTest/cmp_removedNestedDuplicatesInOrderArray.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfDocumentTest/encryptWithPassword.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfDocumentTest/encryptWithPassword.pdf deleted file mode 100644 index bf26b2e4b3..0000000000 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfDocumentTest/encryptWithPassword.pdf and /dev/null differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfDocumentTest/removeDuplicatesHasChildInOrderArray.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfDocumentTest/removeDuplicatesHasChildInOrderArray.pdf new file mode 100644 index 0000000000..2fa10d0386 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfDocumentTest/removeDuplicatesHasChildInOrderArray.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfDocumentTest/removeDuplicatesInOrderArray.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfDocumentTest/removeDuplicatesInOrderArray.pdf new file mode 100644 index 0000000000..5afded545d Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfDocumentTest/removeDuplicatesInOrderArray.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfDocumentTest/removeNestedDuplicatesHasChildInOrderArray.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfDocumentTest/removeNestedDuplicatesHasChildInOrderArray.pdf new file mode 100644 index 0000000000..754950dda9 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfDocumentTest/removeNestedDuplicatesHasChildInOrderArray.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfDocumentTest/removeNestedDuplicatesInOrderArray.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfDocumentTest/removeNestedDuplicatesInOrderArray.pdf new file mode 100644 index 0000000000..1f43c432c2 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfDocumentTest/removeNestedDuplicatesInOrderArray.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfOutlineTest/pdf_open_parameters.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfOutlineTest/pdf_open_parameters.pdf deleted file mode 100644 index 4a547d99e8..0000000000 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfOutlineTest/pdf_open_parameters.pdf and /dev/null differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfPagesTest/veraPDF-A003-a-pass.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfPagesTest/veraPDF-A003-a-pass.pdf deleted file mode 100644 index dd81bde4b6..0000000000 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfPagesTest/veraPDF-A003-a-pass.pdf and /dev/null differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfReaderTest/StreamLengthCorrection1.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfReaderTest/StreamLengthCorrection1.pdf deleted file mode 100644 index 8eec21c1fd..0000000000 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfReaderTest/StreamLengthCorrection1.pdf and /dev/null differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfReaderTest/StreamLengthCorrection2.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfReaderTest/StreamLengthCorrection2.pdf deleted file mode 100644 index 57a4388c24..0000000000 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfReaderTest/StreamLengthCorrection2.pdf and /dev/null differ diff --git a/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUATest/cmp_pdfuaOCGPropertiesCheck.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfReaderTest/bothAandUa.pdf similarity index 67% rename from itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUATest/cmp_pdfuaOCGPropertiesCheck.pdf rename to itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfReaderTest/bothAandUa.pdf index e90526e6fd..a5703e8d40 100644 Binary files a/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUATest/cmp_pdfuaOCGPropertiesCheck.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfReaderTest/bothAandUa.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfReaderTest/incorrectFilePositionInSubsection.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfReaderTest/incorrectFilePositionInSubsection.pdf new file mode 100644 index 0000000000..3e9731b7bb Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfReaderTest/incorrectFilePositionInSubsection.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfReaderTest/invalidRefCauseXrefRebuild.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfReaderTest/invalidRefCauseXrefRebuild.pdf new file mode 100644 index 0000000000..c4fed73c02 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfReaderTest/invalidRefCauseXrefRebuild.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfReaderTest/noSubsection.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfReaderTest/noSubsection.pdf new file mode 100644 index 0000000000..c146b9abe2 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfReaderTest/noSubsection.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfType0FontIntegrationTest/cmp_cmapPlatform0PlatEnc3Format4FontTest.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfType0FontIntegrationTest/cmp_cmapPlatform0PlatEnc3Format4FontTest.pdf new file mode 100644 index 0000000000..d6b47d7f6a Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfType0FontIntegrationTest/cmp_cmapPlatform0PlatEnc3Format4FontTest.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfType0FontIntegrationTest/cmp_cmapPlatform0PlatEnc3Format6FontTest.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfType0FontIntegrationTest/cmp_cmapPlatform0PlatEnc3Format6FontTest.pdf new file mode 100644 index 0000000000..25f9ffb1a4 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/PdfType0FontIntegrationTest/cmp_cmapPlatform0PlatEnc3Format6FontTest.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/ImageMasksTest/Mask.jpg b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/ImageMasksTest/Mask.jpg deleted file mode 100644 index 2db7edb5f6..0000000000 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/ImageMasksTest/Mask.jpg and /dev/null differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/ImageMasksTest/MatteImage50Percent.jpg b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/ImageMasksTest/MatteImage50Percent.jpg deleted file mode 100644 index eea6e285a4..0000000000 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/ImageMasksTest/MatteImage50Percent.jpg and /dev/null differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasInlineImagesTest/cmp_inlineImagePng.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasInlineImagesTest/cmp_inlineImagePng.pdf index 402b81c912..650e266b1b 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasInlineImagesTest/cmp_inlineImagePng.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasInlineImagesTest/cmp_inlineImagePng.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasInlineImagesTest/cmp_inlineImagePngErrorWhileOpen.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasInlineImagesTest/cmp_inlineImagePngErrorWhileOpen.pdf index 42e92c46ad..e61658af19 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasInlineImagesTest/cmp_inlineImagePngErrorWhileOpen.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasInlineImagesTest/cmp_inlineImagePngErrorWhileOpen.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasInlineImagesTest/cmp_inlineImages01.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasInlineImagesTest/cmp_inlineImages01.pdf index 81f42a9149..f7c5bf4899 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasInlineImagesTest/cmp_inlineImages01.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasInlineImagesTest/cmp_inlineImages01.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasInlineImagesTest/cmp_inlineImages02.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasInlineImagesTest/cmp_inlineImages02.pdf index 896fe09ec6..ef51a01173 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasInlineImagesTest/cmp_inlineImages02.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasInlineImagesTest/cmp_inlineImages02.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasInlineImagesTest/cmp_inlineImages03.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasInlineImagesTest/cmp_inlineImages03.pdf index 5d88b57d0d..b00d239486 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasInlineImagesTest/cmp_inlineImages03.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasInlineImagesTest/cmp_inlineImages03.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasTest/cmp_ccittImage01.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasTest/cmp_ccittImage01.pdf deleted file mode 100644 index fb0e1aae56..0000000000 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasTest/cmp_ccittImage01.pdf and /dev/null differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasTest/cmp_colorTest03.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasTest/cmp_colorTest03.pdf deleted file mode 100644 index dd276830d9..0000000000 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasTest/cmp_colorTest03.pdf and /dev/null differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasTest/cmp_colorTest07.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasTest/cmp_colorTest07.pdf deleted file mode 100644 index f3e15694b2..0000000000 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasTest/cmp_colorTest07.pdf and /dev/null differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasTest/cmp_colorTest08.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasTest/cmp_colorTest08.pdf deleted file mode 100644 index 244cde8c04..0000000000 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasTest/cmp_colorTest08.pdf and /dev/null differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasTest/cmp_ignorePageRotationForContent.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasTest/cmp_ignorePageRotationForContent.pdf new file mode 100644 index 0000000000..dbad67e477 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasTest/cmp_ignorePageRotationForContent.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasXObjectTest/cmp_addXObjectWithXAndYCoordinateWithMatrixTest.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasXObjectTest/cmp_addXObjectWithXAndYCoordinateWithMatrixTest.pdf deleted file mode 100644 index df1cf5a831..0000000000 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/PdfCanvasXObjectTest/cmp_addXObjectWithXAndYCoordinateWithMatrixTest.pdf and /dev/null differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageCalGrayColorSpace.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageCalGrayColorSpace.pdf new file mode 100644 index 0000000000..9d39eb6b65 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageCalGrayColorSpace.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageCalRGBColorSpace.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageCalRGBColorSpace.pdf new file mode 100644 index 0000000000..053e1b16b8 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageCalRGBColorSpace.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageDeviceCMYKColorSpace.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageDeviceCMYKColorSpace.pdf new file mode 100644 index 0000000000..044dd4ef7e Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageDeviceCMYKColorSpace.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageDeviceGrayColorSpace.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageDeviceGrayColorSpace.pdf new file mode 100644 index 0000000000..2e72ec99cf Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageDeviceGrayColorSpace.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageDeviceNColorSpace.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageDeviceNColorSpace.pdf new file mode 100644 index 0000000000..a959089193 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageDeviceNColorSpace.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageDeviceRGBColorSpace.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageDeviceRGBColorSpace.pdf new file mode 100644 index 0000000000..a82ab683d9 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageDeviceRGBColorSpace.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageICCBasedColorSpace.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageICCBasedColorSpace.pdf new file mode 100644 index 0000000000..cc8527d711 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageICCBasedColorSpace.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageIndexedColorSpace.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageIndexedColorSpace.pdf new file mode 100644 index 0000000000..308b89da0e Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageIndexedColorSpace.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageLabColorSpace.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageLabColorSpace.pdf new file mode 100644 index 0000000000..9f0f4dfb9f Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageLabColorSpace.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageSeparationColorSpace.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageSeparationColorSpace.pdf new file mode 100644 index 0000000000..954af2fefe Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageExtractionTest/inlineImageSeparationColorSpace.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageParsingUtilsTest/cmp_img.dat b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageParsingUtilsTest/cmp_img.dat new file mode 100644 index 0000000000..eed4ff54a0 --- /dev/null +++ b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageParsingUtilsTest/cmp_img.dat @@ -0,0 +1,234 @@ +J3Vsg3$]7K#D>EP:q1$o$N>iL@So+\<\5,G^LL-NjE<[*IE5[a2RJa3-XFkqZF,@n9eVk^VFc'/enm@9:1mM9jS"!dTMEqb2!l#N8#0#toX2(aMbe':>ZE_:<^TriioWjnAY&^gM+`4=1jRLW!YA=M/6)*KS9P +E`kN%="Tc_Aoh+fk'&t\ctIN)4XQLiVpoI(>.nOW?*DmIDOWebB%lA%.Q9k7iBquDi!)/,DC66[a5h8d>eXi0S^6MAH1IXb_>kP+oS^^pnX!PjdJ%0OEX9GI`IODGoc^+5,t$):"t/5eh:9Jl%POR,+@ +`"_L`O_e;>`Y"/@)9.H\bcnd!<%/i[Y`*t?_=A"g+ioftN?cOX9U-pGP&-[:aqBZ0.E[gS=!,Tp[!7W\AU%]<`,c@+1!Gh4biOO78m5==1Mkl+c4c.P3R3haDQ_#7bdP"(1[=9V:_X?B6-tiJ%7AMW9bg+EP\hF2dM.T+5>m:/p3KX>AMl9mPjLV0e.-I+ +;9h$MiB#L(9O0`\PKVQ@^%AEW8QM+YD-PU,c#m=DQ0j!,fG4pM7TNISG>'';n=`\3Q>N1*`,=fY;cL/)X]3i.h-D%%#lTZR=Eb4nESQm4c#_\W:"=CBQYkO)>Oo\eZ9)OOTmPZ5c1L%JpZ[0Wg66Z_J^/G][;ET8mCdbf2gud&iY[\%M;jo*/W8X+c8<7DOn7@"A/F)kOlVc9 +^)3Ge9rW_UOd6EWi=ABl\7;fC2k/tJc?5]@RI5KqkSaqa_.Km.go6f/p6Cg*RVnZ.P.HZTQKjTM?E@`h?=o5]Z1`sVll-GRZ0[r4c*QdV94+j1X)Q\"l2-M&\[hfjm0auaQE.^=g:P\4]pdY6[Q[ns%E%]U:DLk=S8TFgf6efTNuX[jXpsfhcS`t!`K*0qDjmR%^[MUq"i9b( +V]jU`SSqfcp)T3*g%L@P;VEAG)%4`6SaN"$GR)9CiV7X.NR2c*^IGJMX!^]GG3b3)l2%!TXm>j*caE/eQ7nhYXH?a[(jFjjc$Y/Y8_n5u[J@\l>l1/30nrI5r@g2*s$u,,K$Xi86eHe2?pm50OD'3`.#ehkC?13`/g`hCM%ekW9o;e+&1]-B=Tc<>Kb82T.F?BWiFFU#:Vn!h=76T);l"]Cl3bGMV]4Wc;2u&?-q?8a'&]:(O&>p4,e6EJR58t$Dg@nPFUfd3[gC4%QZZ/2mn@M!L*=8E0+>M6rbo!?HAt;Pg@F!Pa +-RLtXUI7F[c\\2^kS0tk'TOHc$;Af\,k7Oc)6K0C92"JS0qh);(/Xd56t7e^::+$::?`!QBh]Y?P\Q9/)Su+\9M.S#P# +nRLp>Og7M]Y.o;!=6gReVmKd&=3Ea3%.0[o;)lnU4&&mbql$mqY#O,<2/=>rCUOq_f/:0QCQ?/sV)R3o#s(Uj'5Tc(JAFje.r],,@">?eX^ia(ER&/Nr*1?WLZ($;Xljp4-Ea)CF"M$FjBia5n'ENVb+Z54tdgrGCqTu8t&24!oC +=[-S=2@6ut-O*(f`Ii,_"i9t'=KXb77P@3=_Xrl^5kbE009.3Od0I7JqCsq1.B/E@1&?)ob]u"CjNsK(690K%Nj>A(t^VEV!M/Gj>dE4G.cM?+OWWZR0-4SJMq,-+L6F'P1NKnSr$8`RdHY.;PcBo)o'5\VAMlN6.LBAj"/D/Tlkb6Z^DVeBoV-+dgP_ql;U +AT'[K]l_iL_OEPKmqCmkTJHok>RtZl+`kKdD[GB'2\Lgn*PkLE.2R>^9PuH&A+qV<:&/[9A__jO[%?aI'5Ml64WhBu2;mR7>CBp#pm1_L<3O\Q&Lu`Cc1lk:*.7*uF5D>kq>g'L>n?E_q`k?MT3H-u=LlgqdL>P-fKl=eM=hHOpGmU'>hIGX4KoQL?5 +hb386?d,SK[tO]DTCr25h>>AKSc&35pO5=7-b1dIrnfs9qEN4'O5U'lb4Q6VOKV\J.iJMO'_`i8$]lA%E$4>iI-=2.)\!ooLW&CCP5,6P*'"Rt4U_jDn3M[b]#"7SY\0M)d/9X:m!f+:nhcs5uN!t)n*$aC-Kd0Mn=[dqf^&MY:50>Q2!9bHC>&Fh==:n#Rh>5aL('(J*k&N]rq-PTE+__@rDaZU?=d0gOV$5$JUnR,AD^<&!@FQ@HT&TJ9_O;:]=%8\2X +J`?E3UDH:^A-!tn&FBtrLCZ(1%r/]eXjI[@ZOh#t)Nb[K0sFG.<+_)=&WguOEPVJ!,2J2@*$R6Z1!oI<6O;&%`UV\'1#R0$hZe&.qN9"N.0TZ!h]D<)'T`h3dH_i.i>,o<$no[b5dMUgLcE5_+gHFgOQ[4<,p?c[T]!F"%XT'imhq3W)9Qq;#h'\\=W5T',`o,N;GdU[mh)`8 +-'A!Lmctj/2&rmG,r0;P;:cKo2]\'&-LqB_E/>\mK-h4Co.a)5Eemr)=HLp9.?])u1'fTi$ta"t7;?-3Z5*VL[3>%k%YJj<&h#a()?j"m*`=j+&ifZl4JFSrP7g;0E`DO+9aWYJ*AR@9cNPs7P:pdD-;\t7Oi&fVitF%,-ZX=uZNV`IHQLUgoWn8;On/p9q(^s>.<5ABO^Bgt +4XqZg.V9AX.]=8K_?.NX1pXY.nE:ch;.D6K^DkS416[\3d!HC"V]PG\.M@9RkjT7$^3P(o0"NicmYSL1iA@2nf\HoWZD./5-n?NMZOR@@3[R=petkl'%WTdg6bf\7e;#Q +F:SU4b7aE#33laJF2($raN7C/&oqbRF#Q/)F[JpW3]&PtEsX78SKJUm&Q9o&n>es^.j*6Z4#BGpn:s-d%51X0/7QE(JB]o]],2$G"*Ar]oRTNjSOdhi!l38UoRf[jk=:U\if$RRN\7UBhW%?i2`(k(Ec"G@[7bVP9<-#[dg[T[]hE@67?]qVdU)n%a\?m19si_NkF53d+gY'&k>HFO;R>OX2).V=GRi5\#1Yk81kSA\I6Y(:8ee"Y/SM]Ek>,sC>BLQnl?-,Toi:SA,m$"u2/-,K[jKU2qUA]('m)RgAQX)27Z^VMl4*O^?'p+KVX@:KnS>F$44p5`HZ;/%lE>jo!r +U::q=V)2SXC:3):odO6iJf2#-?K6iq5uV-5qY%>rlEs>ciU(#f,@tuJ4Yu6SU.--rG>]Tj28Q")p@&oBol"8YDkUl`iFd*g"_p>&.5qYa!C:]LHkA:T%2U%)i;msX+*)QB&L)X0TgNen%efW#F125/iGsU&K5Yr'FJ5=6+h/KC40W)Utj\5Fa&%T +GIN!EQ@4!:Km7fuGdiZWpQ9\InTKt]@PrWr!o,>ZE#c+DDrG@V!c)h^,S,k6Hag\8i:[Zt`)BaY%=l3@ngk-7e-Ym&IC+_8^k$qnjaMF;#<1uR=7Lc!om[UW"IK(:p\rn/PQTP=J@40Cp^r'-jp)^eJ[abJQm$megM3CZ!Pl5i`nuCkf6fjQ%p1uIpd'Ql]5h%Tn.!b7/PZ_h`>#Bc(/afKVp9*Hn^ko'*+-ahN]mV2BMsMR]dGpp#`#0ISokMkYWB#.&!n_0,k4GUFs\Q?FOIX;Vr.)0jtZ=%.Ge4`d;mNjglb_)[Q#LQ?]TC*>*\Qq.b`"cs;B&Xa%T)#,Lp%?BG29=X/(:'MM971NBlNIddG +\M85lef5OKN/JUA2!8SnE:m\O%XCc*@/Z?KZ'AbVCK,k03!W!^2f)O7l'BLNG0a.]e=@B-q1ROhTrKFW;@gRbR%TM-o!ARn6^`10F#X)G@$-m#_jYg6'D\^I3O)*(nTgC(3k'!2D7t89Fdc^T#arm?g!Q*:6?;j="P=N=[#PSME"WsQ5'aZ9P3kAc>^bRfT=O-4i4]H-"FVCS +RAn/U@"Y.41QPt4TsP#!es2'N]7r?UU816]H81#&#GY^]USqj@g*<(uZ\^L,M.U100-6RG<#S\*HJ$,G`i*#Wg_k1c%m"PO^k\g5dKM<["8XQ_UP&^crW\gJJcM/H\ri(>r[AXVPP-#%cjHdU81U,3#I?p\Thgr>Z'Eh&R,F#r\oJ(%BpPoYQL:SW/S18_J!Zu!)g^9d\1+>e +I_ID;TceuT@=buFJ#Ls=)#K;'[+U[6-`UX\N/b"t@\Oce[;,QK82tu,[X))\J#&e6JOe\H'`J,AgSL?o*=p?0A([8E]n@ZS>&,X`sE[5M$t_onj>=es'BV%au>)egia>\5t67:FT^pe2;CCW1ZJk;VrCr*a1/]t$Jo>p?Qir,FQ6YI]!\]!R$L+ZY9DRMOYi]?Z2E%\^!6$+u,D +_ZI41);^r5b-net])/\['J/3ibFh/Er2)M&06!2?^_3RsGCo&V^'#Fn55CC]S)oI\5V%1Mc+NC'qgRbp)FjSU/0$N(Ho[f2d>?Uj21.j$ge"@Dou,h:VSMbCr9k'K[="N#;>$UL=DK]SmmoOSG<`ir#1<>b!&u$(V'%dQ*bSi6Tf: +8%sSqFLs-U_k!_b"]mh1@6n,MqKLR1$spHi_:X[Q4@g+KMB^hC,*@*c?>r@-;8%EkL0CSqrh+#>jX,of7;egI'#H(ot&+rrYPCbnsPssqDoHmWTnPcJ[!U48CRahnZpftT^u).Pr3,V)[\n5gBb``7hnQDp!H_[(b+4K4WV>bS7rP%8ps#E:C4nD`f:9tEQ&(hR+ +#mGrI+4-BS/f>+Q_;Z%DPX2&Z$Us(fR+-"6*KN_O&fDCD8K1f(hbokAY$!?C9BHkbbg'o[Rk3_'\^Zpj4eGO6'H.\rM++1:kX"K4(7@(Y;s'/;Ptn;VLK3XTRakjOr3'2g()n!G<0":_/JagTA3k'Vg[5jsQ-SW4G?sYRS(6rrRD2qp(`Pe#$$a&?nJ;Fj0,]biA+B"MPLCtG +b@U8_=0?E-S^1s@)BAA+8Pml7gH(HdY6D&[C\A\fQH1eg?>]>`*S0\)^#*c'*$*a3M6l5^q%H"XS'I)[A[uHH-=YCAK:c+R7`;KYm6>3f9@[/4,:@ +jcgPF3Q:>_SHEjG>8K`s\4[\s-Hl=7Wj0D?%7bEt\:Hu0!m$Ua&gUl_M,HXu,r%/aikA"TJV,CBd:g!>0[adC\$?Y-]#HKqRklcmCt\+$9_1VBHcF1$eMd^HKW-t,F/*(6KZ>A/pdETlq`d,-[0&J:D3-VB*4/,dRnrZdUBj`dH;u-s'I>8&;X*D%9es(U3deDTO\&5GFX9YO +"I2C1F]6G9!ehR(;9RoBNV4el^Z63XDb4jhEQ@,#\d]3`Q-V4VJ0_l_*.*YQtj-s^W9d'9acc>faKfk-qTDR=7KUq2<9V5P??tb,WB$)Mfd9>E&U?i' +)cR?>9p]GZ2.r1ODOk.%./B-4NjkD\HO*jH%>bHsLj"KI+EfY\TijD0>,O-_d#"T6HD4!$]sc(_U2+Mo]q@]<:9's$4!i4"Ynq$#]SG6R`1e-=LG:(2?e`E]J7)UD#lbW%#2R+7BeiGPBtQqKQB"(?$!;sFL,Hq[RIqV=o'0%7a)cR)13)p]S(j6.>j"c#7R8N_d+-Jb +9T\Q7G:*T8]qoqV_Kn6fXs&5=NNi*2/5+YFeXqEQ@98+qkA)Q>GNU-bT]pSEEBDi0*XFn5\#F='Ga^K/A+6;?K5ZUkG<((jYV1@QX>$di=c4 +7Yn2R_Y"*O@?\l[M!=*?GG>F9q9'2N.2A2)[.t>Uh/+]N84*A.)5:(s0!C[k5)7RRT3LYUn$qNdaKZ@%dXr;IFq2L`qCH+j>=JY91I*q8T:l#5HNPlU7eDXs`r'n/m-'h:(uZN7P7.h\>j4%X,mMJmBoR'M*>U%s6".]g6c<.-_P\)B,#Dm4;H3OEGqcQo\Yb+cg)H+;)'R/m +eckW1"U$8N\`+#k*Tc4&b5#HsAX'Ne!p3]TJ7gK9[&f,-jsWY4`t]\+pm@6\@NFF[s.m$F5(QaI7ohO"SkYY#fBYG>Vl8._K\7Nl8,&+Ug+!+'tKF(?Ak +eErI*/e_'E]c>&i'+Ip*\\ptd/La[MQ32`*7RUr@$\YOWPh)=&601jUeN9[np7A,ab>;pg6`=UWF](F]PP=QP<[)m9?QFQs3SeVc[^LA#bULM(.FpWsM[L*0@b7f(/kL/!6*at;,5Sd*fi5Z*)4UJ)CDNl"p4A=NY!JnGWe;L20Nl".2eF!)?)G`X@keM8`KhVVQ6I;j'=3iEc+j'6>Y=Cj`aZo9h9M*%DClBR@?QW;".]:>!W.ns\'+\+%nS?PJ9-2'+MiG!M31WB/;eQTDk#X_Tc2+kl1tCAB(P\k?G->tm>.pZr;8(\UmB_72Qa5qK)J^N1S1M%$Xtd;l>G4NNRBscJ.N9O)CXBo'eRIgqAQ1d=SN(H,.a!eRjun]]p(P`Q(o/@=,%n4mAbd[4I^J=0G(]8\b$)0&TjTJoFnM_9B)/"8sSA +2F0^Jq7`tF]*KbWieiW65C;P#MiMf/6qUS3Y4!1Foo6+O@!P]b5C%n%GlJqS4,9$jSla)n:F#"Lf:/rs((!T0?d(EP14adB^@Q4ec;']fkJ"B%SQd\Th[`)c=0o(>?OM6#JBU_n4l,cJF)#QLLM],eWP\AtrLN,N"b<]V.*k4E#PjkTDO*2HfR +mh@r7l0=mjn-:n5VSLm_Im)K%hC!s*I),sYO%&paO8BA"h4U5CJK)ui]4\f-RQWa%]hq9F1Y4m:YIXG5\d?tOUVn=dJ#oe)]>5A9dUGoK&"-:0K7"U$;> +pj4Z8Q(V@[XR$o]X=F_g!2,Iu^af%C3X%Z',f!QNV[;(mKJu/XYs>#35dJA4@Z:K^.4aI9#J8k3j5:jO1:?r^#2DO/4;3Kl'WG%HLLP_*R]V,(FMs(L.@_9T]Gdpe)oCg`W]3>`lo_?$,=MtuZ[3i^'#qe-R?jco7/3CSEQbd@R^T4\(t&,0>ZNA&:4t)G_YDHlapCDg_8Od_ +3C;c$C*Z7-]#-9&_qZMm]NIU)5.tD:`f]LQJ?ZqRd_hfu046EPls$LR3(F8#2cTa@[JP:5"A438i7E:@48!nG>X10As?Ur;@[*^0Gkf>4$?l/C-K62\fQo2rE431*L86gm?CkkQ/Le*%X8=YQ.XG]W^N(D-m!qHYKCl_*nIuN0E%)cGT]EKWb&#"gWg5Xi`IhA8;(%"*Rt\BClh.SRtkOeeD/ +/B\\@ZV:^NL"t*A'*uancV48"[UcKe1Z8HNS-fC!8bC?N%*kjmR]L1B:#+C$A:ao*d7t!%8dqDX7,^a!T2$*!9O+Jj<9F[SWM#KUaaDg$`2pD;Xig;'$#Hh='XC1BiC0aM5TJiNWA%*tSkaW2"Hj)'[(M^KElU!J#N8r&RL+W-r(J*I-%s1^m!-`I=IdMZ'V*5nPfZUd`ltOL +WZ5#4f[S0UHHrJ4c?uG4+C1^0e4CA)6-E_/WAQ!C)9qB_[f*)Xs$;;E9jm2i(M(K(SH[j;AS1u]XBU.u-h.GZ2ir8o/V-I*=hTNpa'FU8J`la=ClcJ:)XeJ97&Z%[S2c3s4cV".Df:X;0\#F+m=3XJ5SpQ<\pbMbsJ;IptK +h$#A.:Y9j:ofjck`6:fOU-Ul;KLsCHIaC@":fQ/K)"7RV#6rEY;RjltN1SD'k*$4(btQ;T>0b6hM2!l"$67[F2$MAoTZtW[eI!QUZD#^[92M@R!JO]"RhSk]Us_:-dS/%e>rG^$QVr,Gec_r"RKZTh?dP&h`>_ku4YG%90;"dhdi>`t8dD2%'*V&QJ9+gTOAtbj<,GSJ/QF:)?s(ZSO\Jp(Q%@@]SCO8Lf@fJoQqK;>eZ&pU]u82:PYsp0=TpWbCo5X7a3!_:+.\j"eOiuV+PG#1-l&:"ue/-4KncJ)?_>A=K!ICRX`IGFu`\sQ`,d%__#^KtbV>RGo7*Q$Sog>'oMgg-&tD3EdV>p*-R9atuBrKeXloh"8iT+0*#"fSo*6.R7KIB$-*<2?1m+(mGQ2WGH55&,"8>766TZ87:'MlWZC8q +Pg3K-JDQgEfJS=]h76Wns0<#Q?LX]#3HNW^MV,5drh*A#`s(h,!\k4mLEP%&)d\nLKV\!atb6j,"LR9>8;Obc6+SP(8+tMhMrH-Af9?H)Q![l +@9j?ul\u:(HN=m'$928O/k=n1ngE!4Tme5d%OC&XT&4+B!oC\OW8iS@@_)_SJM:Qdj5TIPfPKna%PcleYb1nN_8\=Z[KY].-=Crf@"p]"ONL@U+!E@0;/fJY7D8sI5L\a[i:o$>.P`B-;7)N&7&3GA4u`tj8>&s%c@+:)@=8=1Hm1pIk(RYMN@T]`J7TS)"%IlA?7O6K +RgeYOYd,Ne^g/Q>Bhp@.$sn+ZrK/4lMuqQEBULK+rf81ic\ER!koQ!RQt,AA,\X?@/G]Z0XNF]e-Kn18`ca&QAt'9LB5,Kl2oo%`iI(p=TN8Z@k?als/0^aPOUPi<$G&\@K+=QDV1?`kk7)TI*NRD)118[UC+bZ_2"KDpGb=t\c?3K.p51<5LM,"&6*@D!I3R+O'PJ&RAI2@L +jJ1I1Koo,bkJEd*0R2h7^a[!UTU(Q'$<7nnNs,HD*<*ilDT?HNA"]5)kq5G>@Kl"8a(t(IBS?e)5#5c@S/#Q-Bt7"'aCcVo56YZ>/c4;R^7oIh`+h#c+J,Bf?DX)?7$N3BmFhlR80/^6%cI&];tujdRPFp3jD*Oom%puLSXPM7Yb.etc;q7:1>ck>(h_UglYbm%m*FF66#2RW +/RH%W^:ZoNL*;;,Ct>4q?GgRt"mdk^CdsJYQB:QYr+N7SC)3u,(<[h$bYUp%jCZ\N72+bL:[J1BD'%+=B%(Ta5B"]5m;=ecNnA<\\a>P)l:"lk?S1Q.&4;DSCMdcF*)sk1td\9X:IIl1qfH'QQbq:_COK7e4Bu +o>K5PTml\(*p[d2Omdl*DjJE3VT!J^`cB*S0n0(oP`Gi`(t;UdTDnoVpB!2V\*uPl9kBh]=\j!L#*8K`TDm@3)'s6r"i)2gF;j$#-DR5?g4t_"nHNhAEj(2&,Y;V^A-WfP]c_lH1+^`flK45sj@ee@#p>QS>brb:hR%:f([fbXo^q3YN6d**=P!AOE3]37n<3CEHJ=+K"$1R,l@c-:$u?enX!;HV]-]g;:Y%kp'R8Va&MU/f +2>On7H-,ROhY(AR3.&pj0R'40?_[BU4aKV=qH#EG63$QnVsT7_qOae^O*Qc4b3oZ5FLgs[&$XO\*X+;S44CmB?Pn#0MH"em<7q]$;om:o]?\c[sa8145bqI,,p&"83^!5cu!5EIkmRY.>r"0(@ca4Po_8iW##f9E.-sjd;,V\gSY1(,q_opMM&B%EaSq4d6 +4'jL-;'\R@Sg=5B'Lkci`u;pZ]Q"pn`]SMaa31_T+NI*%>o+!V4F\Wu;I#U2+i@QXLX"R/h'9_+p;d@u188F&*1X8S_o"D8K]^W`ZPMGstcdVgk`h-3N#Y*1iSIhBRe61TsdFO9U/"/0e.;rDHtcCCulS*EReK(f?[rQq*"p-M-NR/m?!SR;&N;Ef[&3,BZB`C>m3;CS/lF;NKJL!bKoQdWn*LTfb7T<<)bGSP@6Orh""=[GhmS7kd),8^#(*'GMVR_8E6iDJDaNJGRWNIp(1Ng8%'7]iRiT&LuMO..>QlL^+kP6R,/,X9GK-(OO=ZUV2iL^:.:E/=^<+q +AXQsKR,lW:#,fd-^2ZDN=krg=:m;g#T]U5[9;:PD'e,s,FN0`GZslLuTuLQEWDVQ^,u88;XpnO55BA-fVeZ)I`EO->oIt9%<@qdaD9hWf\Esc.V7Op>FOp/RIrJUXR5?()D9+b\>p!5#]ResJ +=S>kB0oG\WO(mD.R+[nZ178#3cI'0MI+Ghh;`WfI5#7H>Gnd,b8,00c#-m>4]^MG=DOpFJj+l=W[K/&?9c\'M.5p[#*k8G&ba-)Lri=GQ5I2clLD+Jt:(=\#!Jpf7S'b3/)@/UFLp7(-J8caM"=sT7iK&nQJjn@32CJM1b?L'\j`/DZ6H%uZ3F3Vc +]t?]LAIQT^229K7*(-*9%:PbiLX=HiT@d=JQp=t_ME01t\;(^U4&cQ^H71LlD\U7(\p#dt-5;esRpK%3M^9h4]_BLBhIL,TO.=Q[(qrn>WFC2d]YH\?jIY&oqAKt&23jh!*mG[7N=R3*8/"`FA0cFQB^fNH85s2.]5N0H.ROn_qRC'>["'o"Ud.HZOPn;c%aof"'HrYgeL;aT +0ru>:Qn70+l+C+PE9b:(6;_.sn<1*4YsN/::Z4tsKp(k352f3ii]F)DDQ#Ti)3iA&J0f$Z;;9'&Bbi%#>B=]i02/Zs(g]UBI&:e"7X4oF@oV/0OgK>Q$.N<,S8sXcQq^=bIfog0iLFa35u3\68d5^p."YKM8?$Q3,\q:[oD2%Z.L)@f]`%u\Bi6kB>,hrI/>CSr("&;f_M-d- +JOQjPPj)B1AV&9q;u0\E\JHlq<5!sJreFDf"pufPkbcfDcV/SK9W@$.Da7_RMA`)*k*$[OP:C>p\@R-%Ph]tOg2Ke)^HKfrjdaeoFj?u?p>`)^X453LrVJ9PB(PJFlP[Mi.`sK/J?fL5eq0(tK_oAK[d*N`XY49Pg\n +.BbE(Q:r3&#jI%ZZc[Y`g),p]m2E@"(4Oa\0h6!D)]#BRBoYncR-EDmfpbu%Ut.T'<9g;\RoNq!`qm.;USofTeAt9fR`AP>ok(bMlKD9c#@&gnF'=j[F'!I=A^&C.T@NTm;(DX%aUi3V6AkCg5dPds>o5(6Hm?YgbMZ5&\QcG$!SD%t9SBQDqYa;XLdG!!(.orNbkHs2EE +)mna8b9m&S9rUgV3%"mfg`M2gSe]-;B+6IT,+32&/#nX%7@QU/N)P>P6_da/j4)_'5?tMKU(oD!c8U%>PoHqR%I4BaWKt(ph6_I$P?fibQu`\nc$A:/QsuHjF<6*g=4k]c6E?nPkg>-^:`S`:4/d9CV:6QISB;>.>9S'//[WH'talr[IW^m_smeqXK2?(QaVk2*$bV*U)lRK=KJ!Jd$n'-.9\*-l;+9h:9p$V4#meHLp\iOR^dA.Tq/6R-jlf8GUT#b'a8[qi=4K5mmZ[7XWN]dZ7K?DuTi)[#fhop1&pPYAP(NEd^`,)DDs0!kA"+h"X[$m&u@D_/0\qSi=0iq3+E1BrGeqo:bq!haG(UmjWC#K"LYlr9nHf'nB8;D00i#6sa5r;L0HriVLBcg[%Bo^f9]oIt%4 +TQ:K,I1),bXNsr?Yd"U'H;:0nbA\YnDNP!7me9M&$uk&Nn2CHR4P_\V:S@e"$J69dpB9ta&&UF=Yl_<5pCNEm?Edl[0P:k,Ym0AO#;5*DBpS$57$`6#qmS'0.=&#/ICU)o-+=0d&?@DXT-Z`ZbU,f$31^7W#[ET!6ejP&R>fRCDW)XP].oV`gm1YFUeuD +:CuaVOR,bnP8T6g"OWhSN<^!aVDE/=Zf$l`&If$M_YY_R(m)cMVN1s*,ohd>)%k150VDu"ruHq@#B;e1E=c4@QC^pB*AL0-O\Q)m;S@">'p64u9]cL/$4P9L(<>M(&T5N!F!)#L$kaWucYX+EE=J![%FQ1"Oc3'*OUeT\67a/[C1IYA7iq-d)NasL90X[&bpA<6qXM)a0teeC +1E7`K#:\l+5ZK1/8KC8h*f.,(6+87:QD-)trW.,<;=#i2nJ'=<'a`t::>[/aAq?#?SrJgEEj?P1[SmeO\^8.n18t625qJ(-Q4VE2:t6C0Ri$1b!HL"NE]Dkdm"%d]Z%29gYb1"(;oO$$;PBeRRQ*.]CaMZ"k65q*?+'Q<4b +LH?STp^8hSA5E(VkY;9P_9fqP:FDQnm29Vpd6(FSF5AgsY7<;!_#p)Qf,\0/Fh+EN'lWNjTC^&G$&:o*H!b%60DS0d]rQ_$rLur"Kgf1'a:(7RCc2Y*(6u1Fp@);d5j"ZiX7pq!3&$l[c3Da6S<(7k#BsJECPf`-pb=)nsXh<%$kia#:+48l*Ui#@77#c$:saqN@ZnbdS\Ij7I"=e[%fNJF>Ph>!0_C21nO/DUJ$O13jX4$'7bJpof.'#kEIkY'KRsY*DMdQ9o$JFM9R:LPsf_:8?bqlX&(f3 +&>&LMQNF!PeBH2]^JKacjorhJ.JsF9(/djTC!EfBciao^k.?UI84s(`1p&:Q/P,*Vjj^AG_)G=n"K/85"UgJ+d:du/=&kMii!3W=_c!N/'L?_GD(T+qSR:TK +?oA-cp'G@]f_PSOF>b:Bp)e)c?Xd'EfV_)Gd^N]e:Lf^FD:UjdbQhZ'$"RNRACaC.^rid8*AeA)A[D4Re`aCT$"f0c]9UE`XQQMReQF'ULG'f@o!Q"m7aCA+kh2RRNsGpbjW!nPD#_aS_aaPHSkbj\dNf$d^BQWP$VD:a8>p>L2< +4`4a)DRSqMoq?%+fdT5E&%;Kf72kg!;/6jlB!XZqIq,WpX;]r`H.p&1Y4lhpI*lfX`ULsFSATgpJlPi@l:]%Cj*d@F]WCgp9c@.G?3=?(_^$S=b)ip+@R:\G"6g7fYpK[L=TF$f:_!>*7Fp(^i1lt'!E!6MJe=&gpa.`IHEEO^"le!Vpb^EQ*8^d/^i;;d/N\W0&t;\n +r:i(2=[SEM;1#'U'tI):`8b?^F9?1\HW@f8@%9<-YXE1'DM2)h8d:*I,;dAM]_*@oO:lI]/VG=eh"6Q$9b,Rb72!Fg`,aBq(O&Ram=aF^(@.M4?KAQa"5fB?>`_SWQ8X%QWCJPLks+5EpHA*R<`]@,%;V1;A%;Sln2hU"\9^l_'[SE4C3PoE_)> +9mpmCLku6MqBD5FScmGSn+gUEpmir2EF7@oRolY[iRs+QQH=YGOEs^!$PK=7Z4_G>Mj_JN$'go]_eU-\UWMR.H?5NhK:9?kGT!`R=gaa1L)i='=BWgIHAl!1O]AtZT2"U0H.Pbng+eW;Xc_6Hq<)\M%8WfCU;0m=&@;[&q/H-fT@s;kg'=[If<'[>PbQa2(egRE]F9NtI#7G@ +J]s0_5*g.[(&BPd2^"JFop41*UR%mVl'8%^c_P9>)nR2B2R06JB3K%ZSsin)RZXHrK;Np\VQ4kkH(Kk=EY*P?Ql:=N<]R)bK;_t1S"!:r>:(A;@CB=,WQ3Ph):^_*q\_rgH_u;&"U>g$;0T9:Xf9>>Zr4\WjP0@UCmK%(&,V4rDmoPD]%WdLR6G.RJu2bJH2Fa$oK\W`_n;6% +S1L\;=s=aSY'h8*])+mJmTm9/@AWX$AI7Gc=;APsB=0YM@ChH5GNHOE=qFpWAX*phThi)O-_$,^_V?f^"Lb13>Jcml_qL$W*(..rpTf/$;Yh;CP2c8KHB,Uh:m#uhTn;d9WPWQi6TIDIp]*PB%;r#-,O*a]m3_u!`W*.Qn-Mt +>csRNdE>]QC2)6"X;8T?;,>pZtRq8L#uC&j?tM$3-H"fU%h1UaCLnWV5id#n(-f*I&A_En; +g$+jIf7D0cqoq\$VkB=<*OF$+Cn=qGS,L/=r_e8Pb%5rDR[&H\&S^'LfI)(T>CMe$*TbS;l(#I6dKW_/>ppeC/0@6-,RW2W*XCVZ`:EKr/;m@N$IGdLS8 +TWO..k?<;gM.c#)XlpZ^gf\`khM>`LNMiA1l5l;=?.tq,hs)3]l3U52ktE,OrOL[i;[Ak!Bu9[\dBZ4WgPn55ot9J=&'&nK!D.5"kFUp=R37i.@!NeP/hCO@53_bk*&rThJRq94/\:qo^Ri*S5AF6=u8B<8T`DFPhL7Cd8?lBlBN]=?B86kjofg3#Yume[>;`"u-FI%EQIt!$iGlD5mP=NQrpb9*^TX!Ylh:DW_-lc">W*JoM1&k'R)ET#\WP!Ei[bME^G2/#cYhFk +p4#B%d:i0@>lEtcWRMnFR8%k>,_aocF^&(qCN6o@DY#&8p;;HtMPiG&D'dYn.(aMFSDJHSU!`(D\t*-(gJ`:F,!2;IpO4/YnTD1O.84g--uJgtrndsp\4QLA5*GobV/c>+IeX;#o@!\)/p^tD5EIZF/AWiY(3R:S.5_Arn<1(p6EY/4OWK[/6ceoY/*_X?=NY0Pj>S`m#^7f-X4jQn^Q?Z]fXZ5-qWalV"S4H;)YkFT./T<"lGu[4UJN6oV7H!@BdZjR@?9Bmd<\;REd*85h)L$D5M"aELHXPPGki:='*j!=0E?71$Z# +\YiP.9cZ3c5:+9O2S[5E04$mu[;d0P,0[:!6-1Ap9ir"G.W.kE,#'Q,$ZnmM:^-Nq&u5/X#8GmsA6j&FscO'f;O"F*nSVdD0[X;)>=cN)CCcmU5(bPhH]0-lYU7Y>e7lh;T:L%nBM6/d7VS +1p/WnA>aQ4Ss^JI#.&.&$)B9)XU7-9Im93Z)V4a!0-/k+*a48'EiO''LEOfH+gAY#njfBpOk_tr^H=7%off7)Jd42#T<3t?rE7]D^1n6JafHb;6QIIsCCE]ra&]@Y((`#Uo](4kn$G,43^'@aqBEk#1'_+cIpT?_DZi4mW&qH$/WB$I="e4p"a4Th("EpJ=!fs>sh +FcCB"gh"hJl,\(^nlFkf=f5fCk_%c/huqn7;Y!;*j31^'5!lUtqRn1<4',aX?`82Jp8RG[>/)&cCS(sEYJpMh)6ka*iLf_O1)Cd[D;U5WqL9q'/+A#Q3.ZS`d@Uh;r)#m>#B3Kd"VkLO!D:f](b<_HY7dT/Qg<^K/Bpm>7k4gC':<3'BZ<5L*+X^b-Zi-j'cKSuD*cB!KVlCQ +6T8CYiG0BUMCoa0LN"TsF'*e:"lHs,!t*j6SL+g&*L&h,'3YGcj+@K'&k6=cqGB??EGr4G^A->X`?]YZ`#sb(;DOI]bArCAU,'d+.f]\\!b]pmMSO4+!p"CnE0;W.5mSb>b&L=?lY\P`#W/Ddj;r?'Je5dBoGJr3Os^=J +EcV6i+G$ITp!)/)Fslp$\r$=Pe/LtuW^`\.DaAP:H-%q9j_/ahtbKfQ+g#[i%L&T"%%PPm@pUg[0+NZcD'XVrJ>>=(,jLW8C6*#fl<,SAII&Ts3XhmDtuEV`A*B`^@D,jLK>+p(Ps)'e?"A'C7b"uu%'"Bm@khrg7I#Rd'Vs`8nLB5fC*lFq>kjkG??\\X[/6B\66[)o4O8L\)ATTP)g4DSIog.e9/$Hom^c35UG4+IG6T,rHfU=O)'-ir:=&=X)qtXf?Cb)k<)&D.')a$M/FP+ebqs=o8r&'Jh1n<%A1pClM[+cDXH0:-bShuqhgFQikhik=!cn?eDXJAhdT]sVQ]kM&B)17XUoTU5D_mug]%^U\Xg)6eSif*4=2R[QJN)1JV9^HV8ApSY>20%gXaM@;@7G;?s.=qHNA3f#?:.(@:kK8pBaP``K'I[)P[:N\F^jP:_1i7=s&^PO/\otSBE8hnY\U&8>[:`.'QY>e90@3GZ$Hj6-_:R&Rd]T-,Qa(VV.i322u^b[ACfc+ORahD?R_To.QjI!pb"AX96S<=WmRVf^GpF"pRh(!LXAG.%N>:)5nC]+*I>J&NheV;p)_9-HTu63ICH]ZT"!O&^No9>crg&`"GV(Bb9=Rna7Xp$h2S%oTaSXbq@q96"cmZr6jM?@+(sth^UNlbpYYljL[fgXamKk6FU59ft!Mgp9KP7e7E+,fYniU@aL:e/#Mphc15J^;6_.4=tF;McH'u&`H_5&!cZl?j"*5U,D^FUG>aIP$,4h_UR_BIYGlfSTP%72TlT+M3aMglp2NJ@'S[s/@cd3h/Bq2%@" +6K3\&/2+cjqNeWu/;u1`dN6:o1rE9M_dR(CF>q*j308eO6_lc:l/_q$R=f$5^c7Q';KSl@"uV$fQf/FD1K;/YlbKNJ5e6P-F_CO<*t^=5=Q>NLL`W88sR=, +[D6i'Mei[;5YX53'e*:A7\je=Ztm\"CrXtA`oM$W_ltXV:Ic*k5m$Sp]M'-/E^s):7prGeoMA%oGfPp7`@4rJcm2-"H,n9j`F-2BJNT>K---_t*<7a\Ub)mGG_#.7Vc5._Qu>$J4@XF@aIo;]P`*O,@k!pY\Qc\cA-bRar=j?eaK1P^dgX8B91M;P^Vl=-E/)DY4\:$hae4O3 +WKIY;>6=GcaY\I'Ck%JE=t1Y17fpsO7"`QGPlco@W)QlP`/'Vhjp'&$8t_#pA?3en#K-[t8E7k6o2K5npdEPH4h%e&DO%&%pRiZrG5icj`65c/dWu9Y^s>_'VHC5H#[-dMIJVdS*c-L,A%k;--@,kEV:m:%X<0W2WJ5F@JAXbj*&7>d-p13"3$!9f2.W0Gi&$"i1&$9lYH2I.trD:sG[":Q5.]%,@:R]UE[66KbhNNq2Md%;<""i_a4aXEDdLFdH^[+n?EOXK>j%UhDV+!X<1B<&uI'\@V">+-76_/eiJ>cGW!NQ1JW$']dHic0ZVA3iJ9/mUK9\.=7+f4C(I0l#BpKn!2$C!t'b4F)sdl(hI&>$-c=S].8'LhbX4M3e[/g+kuhi(M_DOBC4Z=RD.W)k:)H +*SD`B>0X44rKN>iQJJEBq?I#^`3:8\eNg<<:o.@#I#j@7gc=cUfp#aDb`@1V%PVI!p!"MbZV/`6"$P)=KUiQ@\$h_Sgdho'<Yg>TIZS2;KF5TEuWXgi[Vl +KufF@WnmcjgprX*?0@+,c46rc!sRm,FjX.A>_bK0JJIUZJRi%\eMg#I?QtoW^fi2R`!3'N?EpNJ`70P?gfc<'Te%\)p"n>tD;V&<-6in&h2TFrL!QGPYMBiE1,REl4nh`h/3I`XmAj+=>.je?WHUQ'1'iWQ%MOk?suH4*[?JQ#`c7;@R37e`?6JO'JkAY%B^5MSE>P]R@&]qLH;#^%POdM(?0$mYM^e?=l/+T0q,51;-L55OVcuR2&'I#;@mhVaL#=nCLAb:$A6EW>$5?t-=SDkj:2l5;!Nl!1?9l'id+[sONcaep+S!OW?l(924Q+/'e,MLAE*W\Lg&4R +7?B29jX'q]P<\)&;&?Rb.$`\$;.UJ`I>*L]M`s8#Aj,26^uOp+aEj`bQ<01Q6&k#7?`!!%Uo@i6@LqF+2YD525#e`8dU^'^k&tM%XkBZR0':U_N@fTk;"-fRo=es);-!h=.NY6m[q`d;@6Nf,ksl/kQOJB6pYB5.=ekTSD8`35/@^`U[#l%P6o@2.kOe/cD37oK7RFKs%l*e4bk.L$,OOatMcTi<6Ga[n%Y&4-$Ca'gUQ(@2piJe,B+b5DID5aCl,JN;?82+DOK2GY0,`2aFoT`mb5Scii`oJhWHUp!uDTOn@3Yphsnrn%QDPcJ.a&`_@QoE[M%[($BSEDK%Bn0[B+g0&c;5]P=UjKHm/Y +pBp8b$gOlID$#f>G7MT=onR4[>('4W;2?\&,h/+LD)W_sR9)p1[16geO&$\cE/*QjO(lYK[a/8h@;Cp!70K#j&li]g9)&aD`&:?:480Yf;f5LX[l.(o"57>QKr,W?BsLH5r)4)n\*!SO8LOQU]V>49=H +Dq:GWLoCPZAA;e.l1UbA:*XnH>BFcjioXB22[%?rF*+(IBWK(XL/W3G$ZtONKO8c$NIH!d%s&Rm*+C_;I;&1KagcN[86)jDHHOW6gsc3q&h;82j=&-PkeCGq.H#hD%q8N +R/*):q59\W\!Vd!SGCd-q<+@FpRh9eTGA?;qBr$62l$4>V#"/hqIc]%GGk:mW;;j[qPU@i\#]AGX*YT=joKhR\%DOX]_gC@;ur?,*>^eg84@#f?B5j?$^_;rU91Rp[A+enG>l<>pqMH1r@!e;076]=qA:GEkqg[H%\(uP3r;YC+H-??+5_'oK8N7p.%*O;biD/$92B<G%6DV:Of*]O#MX]B/SSJ&#H2=?IP[%/.VKEEKkc-0pV!44!9rHKUF]uIj[p?2iCj'#GVUaM3ghq=?^#o';^Yj'THWP[VM9"[kpfn7=0:gGI`M2/uVcSl"lum_]]oIBsamXJ%?9]cd\``U2F?X&E\)$NDB0KZeVpjW!omVBrD>u!Ys1f0Rpu]@g/.D]Pcm/bm6',n'#IZOS@&S,LF7kq;b*lns$-OE*Me%GO`CUB=T0=#Da]WdQXUqe\)],N9D%!h-]99STpH-$St]ct[a/BoupYuK6330(Yuo>!%Zf'#NNS#\Ko'?aB1\IZ=24\uXDrB\ekAA^d^%.+DmcnoQq$;T*0.lgL,X9R$:e87';bk-7C92\W?>^"#J'hqWW'hbH$-"D/"(M;fM(*pi>odGSl='aiL\'K6EP36jC@iqT*.MU]/sF'ZhS&_g[Rd>gbfAMp!-QK2/.++.2A +eWXQIRE>,7kDT;6C$6>7YG']0lJHl!H;9_]A'dZd$0c\f!D6cZAj**Y%5s=%?hai39l%?KbG/m4f#7%Cm`oBbl+!=a[agjoXgIM\#1j.K(pmXIj>htn^ZsRugQ5nb"A>$3R5Rp[6sN4uO`C;1A%U^J5&Hdlq:1n)kF)=#BkUZjXeP0nhWrY`%;uDl@TP2Henr&0("DM31M*od +PCCj6k.<9oGkW6%B?E+1?44;gf,bOTG[>17i\fRe?+nf$D[X[6*m,Yj>[/NRm6j'[=iFtP"?l8qS+e0!83Varb?4\_1X/Mhje'k?o"RQ>9:[ENm@JD#Fmj;72"p5$)JcWe0F(l&SJu(TW/+8^3ZIj+F]du\L_:/Ua4/]_cD6+;E8D\A\9/qQlS+Il.1sV.bn1XX7Yq^(,paCr'22A$M?Zg)0A+;dAO:X'`qh8F +Qk7-JFab*fdtCLBP^PFd^CTE*8r_nQ"X>_9K5Hp*b<$FZR-.?:hMt2P/dbR8lV$gtcqMJ-R/OemB)5C/KN`"L0)Q8?54gZ,j +7;+$\jk4LH8eC[!qFaK>`6"kjbk+O$h$If%;bour8Od]-;G*1!VD=fYP5bGG'K=6g#u9GE)Delp=$lU>MM7tP(qWmm^-@euq'Kt>k3b5^;b&mr$^IMV5E53qlkYI3Z4=B"BjVr_Bm<\DBogDsejKorZA3lG,.%&,8Wm]J-b +]">o^Aks^oZkK0g=.:jWkuFUFerJp5s2u9HAc7orto) +^@`7\AK/#GMC3hIda,M\@@Qq>^MTRY%B,nf0^;k"!`81*#6=-cPg:e!5<:K%`\.GRTE/dNDs2._)Np^fSeKk1-P!FR4c21/7Fb5L/G\Zmj9r.rh!tABu"q:!or$>JhjHS_2BBXAm?L4YiQ#)WLF:XPi7A'G&`h0;\.sTVhhT),fJ5#'OmPuMXbQ1\l[bRk%tR$lW-)E +GinR1Xpaj:R3ookLFj!]X>b6" +ep',nn6/2^2ACDfBp2lmQqP?,LCDh'f&'pQjg&sQbEKOsB2;Gkfdch\]0V7R_V/'LLfbZ0=/E2e(TaF+76O%\)0s@kC*Vjm^mt6jaLFX3IZn,rV#i%*c$qO'u'1LS(MthXl;Gi9W\MPB)U+MpVai*&g*2*IUC@qs$u>P?a'0PhoI+Y +J=Z[+X835hloDi$&o8oQUCn0A5M-j/ri!miY(+ADrGNru'V"6$'Z/B%-538A"1):21o0N8T[=:B.R#r#`l0Ot>`BEW9j"0cbI0QdV>Glo0V#OlO4?s#iO5>+Vb<%kS6Ck$18;\",I`^W"'B?#S=3C&@Dan1CKjc +$fJQ(+[lfKCo-*q%,hF#+H[+P2?_BO"*!3)?s3nVkRk&d$/r6WO%;,0&/enB&+E[45f""Ned2mu#9ZqW0S9T13sW#2#Co5U0S0JU-jT8o#iM?bEAS8i3=2qZ[_ci!O[L!?8/2_2!$[X?O3S@-=TK+?!9&DC,?,D_Bbg/T(@cA\0m*KU0H)0>)3KIdDo`nqLdCAi5!d"&+UoTW#CoAa0KKL0Q4UmC)X96?a"[4(Pau:[W_pSP0uY,Hi:eZcM9K4rjLDs=o_NR`*V&(=/'=R1h",==*lSX,m[deUi_]#8*KgFG.fR1\"X()[+R1Mln^Se')'Q:++n=(%&cV8HaW7,61a+.i0]`o;3?tgm,P",G1.;9F0dNEI,iKOc+i>U93;(6%rrL=SP%>*.7jbNY-Lu.( ++d"-gM'33')=i:`P(b8;G71'"-:%>_146:r.\A6L*-.](@5ofg:F`Z,.e9hH0YR`8U^XJr*E']qAb;\X#T3-W$NP`.0Q[M^fbP`[?S]^1bRckRE=ah^"*2pEnrYI(e:&$8Y`Y(g!AuQ?aX32$0_0#aEtf&s(_r5T09:]K!Rif5O;25p%WY;MEpk^r3@?N/&7\ZjP<1UB8Mmac +0u6sf_*'Ys3#^7O+/7bhTf4lKZih#F&V2Gk.iTY*q_tj02o=euMhrCiqCiN'3:i7+$0^c;G4!^#g26('F/:#jY,kR"3qKU<1(>F+[6!^,40uaH1TJqTIlqJ\3V/o`'@AsW8AmM9nm4>.Q6nc18i]0_%=8E(R21Us&rq^]!37MMO$E7uF"oG_nR?]lt^Z`Y+/\HTdh5np(f0JF'&a?Ggn9N9D61-ZP*=u2$3'D16>JZhgi^sjM(:@nf(2"WQ0p.J>6:\02u +:D5R[*SPgriUYU#qW*Gs`0!o4%\P?4$/-PS6P2*emN.ONLj#8CJW25O@(Q6'o%-"4[t+OgJc\QJNK0(eQBZM:]2ZS-i;>kDA@d*?$kT?+&EiG%#!+BX5$'B!Rh'[W,'MWkT9;7+PVbokRFtDcJVQ]s*2R@4A01.XDZ=>?qp=2bl&HP22+h#\2FF4j3;/Wha=S*jCdWQK9'g"3P'@bA9pB>2E.:)4!'LA]1PbT,Eq"h$8+MhD=f'c[JGB0s=)3$d.asS;F-645bF8%%O((Xgr[<+?%.lJBqp*!0e&Pcc(QiD)UES3dH]fOd=2en*aaCO\Ha4`?lgPQHflZs_,9\@KeZ>M;]m\J:=Z=O_Ep_.A14_)idWJb=15@=L=Vt6#hR$*l"%"\'nS#f.%#M5=1]+5'5,)\7H9H;DV;0 +Fd!>Yf3l=XSH>%NG(;Ci(klJoFs".]GKYtj!qBgqKfM)K*7rMMPGnU24eBXLi#pVgiJbDiruME&j(GLXA%08=WX)B_U$!QQ=+^7rDEO8/*EfC=e-*\pSp&bU?6&n)tD#@8!&O>X^(pdQ&7.lpTb=*JNiGU[rrM[pYU=*>g@C;^[o +8WjgL&XXk&2`46#rriFo#(T^d,L3RL!8bZ[P-[#0L^7bFl20XZrFblB.M"m*h=I-KWRo&mPMADnC=-JQj$].37h2Uh4:nDNZ$'*H-j9uNLm\!@'udC3;J#;r@aT-9j%^k$Q(t@?_FffOSKbtW]^[!s'+.GLJtG` +TRBma\,u?TH!%YP_#pHTO.SF#X2.B'3ZD2pl3.m')f+%S\N:,f-jAd+Y+)^6"2WI9n?$H2Br2ZiXX^K%Y1IC'[R/UBqm1/U/d71qD"1k2DdI!UU?qnpCVs5UF=br/%\(G!A.bB9ejIi\bf8=gIVB#;A!=$]&9?q0bOXHdC'rlK^(HS&qgOVaf_*N]_g$-UZk03 +ah8YL^%_I[)[jA!l+Gt`^A(-56g0V>ruZ9#_rr$=NFh6PbXN4+kN'cX9&=EF>n`2?,DlgJ*:@5EH&`qMP63;]=`)DjAb\Pb@CH7L[!4d)f=FjioTd!L2]jdOs\W]b^\*IlZ3cc-mC +PYou^>0g6?NH[:G4a^Jf,dF>*5MASZ`Dc$SVME0SeYJtRTej`M;(MtD8/An_au.d,S?^!iQc*eUfa7,!;Ur"FHeu7R$o6?h4gg_N`Ckc-6@a4:3Ji[sEMttZ1pYaUgqdbgNJt(:1LR]NRnFK4+`0Q7-/P>BMumi24#]"Q!XDZ1Fk7?bddOTZll$pNc^FTugl6Ij +3RIaBW4ll=Zl?c$%paFq*57!"]hQN?QTk2&eL6FA4]dJ"Q.=\t*5/?*]rWs%Z0K'*lMe'S5.0^$f>83_NOG$O5.L!o^$C-Fm/GBrg`A0kf6j0bmJ<7mhV7H>UVX\3mf)_r?C\#ZoC'5\m[i065,CI6[k1R>$/X*p2.m%8V3CK^r1:W+HNu8+&b%t^RUMgj8QKlJ-;qA*fkN:P4hlY+:kCb%LE;k6(]iu<%]$tL;"iBGa(rP +'oPN?:MA6q3?=/Nj:W='':IA<:E,lgA5jEdnqBE&dH$MV7,EhrVc2jq)O4'O(op*cFaDP4W?JCqlkUMaL,!2D=mZ`EKs'*G[p/8:)jS_5DhhWe&?Dr$q0]R,lrD^"Es3L"iPO6;<\G>M`g604>V.TO>K:=H(t5p2BgQZLo/[l.:J"3D +A@3>H<-J?VC?rb6*>Zs6dG%*K)kEkP.tOk^1/bR$%sQ"4)0lj#?S7r2k70NmDCJM`3h[)]*A#&T\Jm9tqcJs;O.>9lFgVm)GH\oB?2N]rJcE1uUe/nmbqI\tBP[VhO981P]d\NO!sW^3prnZ#A-A)9n:S^i_+_Y4$QW'^*=YATj-7A*YbN%%`,(m!&#A:q;\63H6s?KQ$>GD9 +2B]XH_hKKpEYc]8=RdIWC[0W&aDrPa+eOocP9ie@A=.eenq4\LUJA`@o\g]1trokjdTZ\(4jYC.>eMp'u%cEA7EACNOn_Z/P9^W*eD#Ip=Or]:aY"A]1We^KGENU0gZoGG[C&B#alQ3j<\5$7pZ9&;l%t+`.jXI+EPhQAfDAS[M21tiU91P'Lc"a>'*4-H9uo;iXSb*f,B-qbGp +&OsrZ>pPB^1u91FBR2"`UF*=5.raOKSrWoDg)bgEC2.k`67ilEIB+Srg$Pn;QUY8*8DZ"_aS./'!6spA6(_\p"KXVilO`Xb@&,mEas&GAgPY9I0HR3>1!e`Nea/mg)Td/qJi@/7L*E,&tPlLG'(36G)lp" +jb4Tj^')L.VM"&ibSEB1*$ffW_0b?ZhLmbAi\;a-V.mHM6XaJ,kB*A[hZR![%;>>`P`HF\':28CQeNm"hh7hrrb*(j/T!>230*i"kPP9Dns7^*!NSr@@ACU`i;TBJ;JWCW[Pjrdf+R[VJd$_46$CQPMp*#Sn5]g_-RMh4H5(6KaJFj::p>nZH6b*4;n(qd!o]9C0C&WRK4o3q +9%]noLo_-)p(UMlj)&7YOarJ"r2IR*9870?,D$c*Y_.=%F@:i2+[poOKTo\,6OGJ3Lfj>,J7sms[0[mP:rks1m69jLBb"*UY`:t[9[=-8\3\@M_"to(@G%E]V4\#9;36;@('1s9W5R^0Y*!Com4ji1;d_$o*"l:#!Yc=TUss=1VEsgfPn**4[Cq?A,a\nMX`%=;qCf>TPIN:pNc/LfL,/b>D0A]?J:41.s_?2)(!n6<:$_`cTss@;[c]pfs`UJe".:bd7lucjH[K.h]1qYg.gZ$>5MP&TcMH3@K_.`Ou(h%$4gk<:1`>'#InHhC=ZoY(E%'*f]\8m63OT9Ok=Y*Agd6!TVlMkg:oS-h;8uEFDCC^r)t1eU8*M +fh,9WngS%jQT9l70VtU%-*L$Ad('rYb)n*7cYc:<=`Qua,st+1MPCe#b_T-fk[e\4;'^EZqkZ]YPt^=Q&F!Gm+e:HjQ$0>X8g6sj_b?tF3j@0B!ErqOCP#QjeP.KR>>sp0Xp&QR=*"+:dcG^N("BH^6W#_%jOe3Y/T!$]\RK1H*h4siI+G1s=t/_["BJPJQA7SY6"QOW"Br4\ +27b&6'^>ipNlW3^r9oW$m'W-1NmZ>?:'ge:$g4r]7!Gfq$$-586JC'b*4OsVBobB-<,R\+qi9!Si*d#,\_lVb?<>,l^@W\mDJ^C%!d/("d+.K6I*X9!ij'bYD.''7;_EmUjK_R0(pVp$(8"7,JYR2,_4 +@59KC0[XmTA1nCjHn\U&")]h&^rX"eQ7d/T_@>/+f+H1FE3+KuJXBPd3e2I4_nJ2d#T.PXj:j$u'qV$(mZWf!eWNrK8I\eKjj+5cY_GVG`T1ph*nt3qXmibb6?b(eS%),CW'`_@^G@V7kAUs'10s'j0rui-*,\eI-DS17/C6A\L44IsiEnf#.[P\NjYg'5AclWHThcNEjJVAK +MQC7D5u:Gl5=7u8<0Sh0jT:4:og8M])t/5/b#cKWkq9`=@A(#/X2%ggQrZ5\!m<^UmrkfouPt,XZ,Ht)D+J0s'_&l;Ue;@P*=B?>,j\dsp:o,6jg>/D;)pg4&\Zn,(@6FgCd#-/8^+,5"=V"T"&f),`gW$@>N^8()]a`p'$Q;f%Jfe9[H[;>i6YFR;\(nF'PqI<2JkY-6IS(Lufs@BoN4dFq,h=kMOYJp!+0gj>B/m[_tAGCJl54-s(1 +7u"s9cILiCc[T%`j26"j\`-X(m1Qhe_0GtOr6Cs77==/J1SOE=`a>3;6N>AUDU8g*'#J"./'*$Z)BSiT_ED?gSX7VO&.r7"94ARh+JGLsC;4*LHPF*4e.el[hm&`9\#`@J;R!O3W;2//=,/FFnXm9sbmn.P[UJ^WrV+S'Ie2t=XfHHTn(H@?A;'EJKSB_5OArdL"Tr,j4;lu@ +$-921s*j.X5M&:&M%cVk"/D9Z]K!l#"._u'f[#_bK2-'6$c!j"m(=C+CQ%6pWb5Jt#re"AqkrkJ8r5R[ZZ4/Kju0#1Fa74_@aA-P<+$q(dk6Ln/GA*uDe;+6mB5h&t$A.LB\'fol%7I4AMr*ViYVT%;"6"&qCFBaQ?DoPm"`bAj$ +GWEAT`.m=9]P>'u9BMYc(5$TAZ,1cGZ(8$upu8'r.4u`1[aW\3.OM9KD`> +5NGQPCek\>@&6hc8$l4;4JYSA]Y?!%`E\TjS>Vi-=?^P(8h=Ml[&Z8V>d)q)7F\$Rr3/g&Ttq.6_-7P6Uj`AkD9H1m95M(1I(2h.\P%i0L-Sa3]I8E2&51\b,eG-fPT,kb7foVV9J"(T4N'oe`CsKO9PhaCI)o!?a\85Gb?OFu\qZ7`'nl5)2'`[C:lVt%(D0k2b3NOB*7P`8 +kQ/W']#2dI=^_B%fh*s/8&5*od4L&/h%3PtKiF($(l#pN-kBu(:+GIqgss+e9"JDIc=p],?m/6[V^si,`^Hdifu/T53=\H>:'Bf3g^V@nK#f1@4$8f4+^mJAFU)V$JS>9XC,a87ou*r%`4VXroU`W6T:^M(P)QXY`:'O=V,/06:b8Qd*3;CVWQsl$cQho$XT64T"ON*9T<#E4 +g_A*5%8bjj:rNdRMnVhEbY]An()2Ha6tt%#'iA)t2q6$6ZeGU+(!$17bk'&jO@R^?'nGZm(fRn**9N"/@0/S9:nnNJ8Q3_;7_OJ0OJLYEdmsK[.1^)?d]D?QBSAdoj$%bu7PNjnHW&$i@8a$PdPCcUV)/r%[*lH`dqV&Th$-GF!74s":D?mW4K'257*0.A]EgZ!q%^4):9a)S +&>Ygfe=Fq/Thj>fcft7%laP>!VpI:n<3-8GA5tn.3_:n.;p5]tKh57no2Q3*:p^b[ohs:nue!C52_&@J.pK?'nca".^[O6M2bBj%Zsj^B"]RV]<)#e7V+)>n7iB!@'`ohe]5H,+Qc=]tVog:^3N@S-;7di^Pl0iM +E@nN$G?2V=f$Lp-i:b:0%0fP8-rCT./N\a'NQ@L\Jb?W)]ibg#G;%Y%L&k]b28EDs7b5+Kf$/c$bJm#R\5L!I=rY:['^O99\C`BcO^#)HSK\+q"T[)u4ih:tAVgrZME?docc(g='o^eqNJH=jf_(?^IFq$&JlNct>]g'PQ,VE.Q!>!b=`*".h3]\*R9gVt?7k2+m@7A9=P%,Z +hIt`D]/\LM;VMblDccq#qi?93]Bt%rK"\e\8=n,i`R'[BdCXPLh*'7n8:FiJ<7pS9?&fk4^#)c6 +*5+NE]/AAA?'@C):gdeKiSGaaA`0G.iSmktibg,*`T45ISR0Sk%GZH^+ALk<,N7pgg+Fl7pu:/be-I!FQ4[t@*ND3.i=T477h)H/`NG>/YMqNrhhW-,R($G$m9dG**M?"VlJGt9#.u)JOHG6)-(W,#$F&q$Prg=&TSDBE(#XcM@$sg7i(mbC9hMiH4"_!%"s;W[b#@DT3cTjD +q&9`))S1'ZEI +"QkI&]2?KnG@$D?5T5l>@25]m>JVY3N])49h9tO_Q">\Q)1Gb'IMh3_UZf^dBs(oIjUUCY]4o0nl.&==k*o!ZT0'c\l0]Dp*gnLJ!U<Xs30=W'C84W2dd*$#_J%Y+iP-@0B'JCC[!'*f^ss]2#%,ClB%naPH)D7ql;`D6B23p8H+4cQA1hmI&k7[\-IJd(>=rm(Ls"g^?faWlL*G'C::sg(%9e7mboX/R8_R"C2N+sjh:7#4Q10T.p&ji\?jC,juQQp +[3%!kf"ppi'Cu._=PfV:J:2I1%!i"4.@=)q%]2#3YI'915QR:QoFL^2!-o3LAI0qa"[i3>a>s0!bVb$^Bfgk$&CXALf6)1GkTBh%(gPIgMfLMl2"Q_&Su6ok?1aRDcDM> +i!+$U8*8hTi),dT)"F4Yo4Kj@`uKb%qp=JqD+P'[$b<^>&;8)E7JBoD(F;Za-MLb=Edp'PY<$i&H$>kBn`LkcY8_Z!SF[8;DPo=7[7>HErp!!&l=bnl/XN:6`Qst@(IO_?Q"$m(pn"b+-q=YC3nJf'fd/"bb*;3-LCPOMTH-c^t@6T0UF)QVQhU*'%dWX4_m6;&'nHE(m[p"YP&5XSJGd[9),S0'[`:nG%]UiuTKm6r^GON:nq4.:\@.PT?r"8dQ,bb,p^a3(#Eqb'qQD+3EIrfPAr3+:h-\gte(9C;fp^=[DTi9C$&Vupg +Gf^;;hO=6*UpPoS&>AXl_'p*M2@u\%H!^X7Z#Q(TBF*KGaAe,-8"5nYcbV?S\iO[W1CHgW6'cc0BJdpgTm'o^S.+eFHAki:rB3miTkB;KZ8pL:EDQ\W%_+8L6PCu'85?C:NSg13WfcOQZuIbsB,,Y8VQIt%I)A3E+i,?u?Un-ZaV5u:f(#/SZ6+U+LBS1+f^d(D!46VuL$oW+&n5nLt3*(^d;8gI*T/WX,eogLJ&pD:hC'*t,I +B[gf46cp*[*N7?GJKW$3*/LK4dQEVS/-1\.[#9iIDNB_hS,T\,`@CGlb+Q'>91EbC2MiLh(hGJ;iagF^_o:]i/V:qMi8_jdXQ_YZ1VCI7$o?\o8PdT?(BVA3>mT.4jZO1FPI+S&M$S3MQMiT%RuWB@:]$TJKll,*>uT4r6HG'@EALM)ki'uic-=Tu0qT!se=adbqHZ$D&!U]& +^@/u3LRpC$ar*#[2CdcdE!K +`Yn4^kFeYb`c1ZN.<(cPc,r4drD@geel8(La^Sc[p,g%rH(rPp$*ObODk'b=N%]OnH:A.L?Z;'S%eF*me>T6%I9M`!Pn20*Fil(S2s4OnHe:e`USO_MoN0D%hS8kW +@!q`Th=OKfdrBHiUcc9l2ePH$VqeM7eepCt7aJ>ejpuFam\Oq@l0u>tO3-L`UVG1GY3'PEU:bA[L6<#GSDBut^63[`Rc!#(Z$)mi_EVSd-QjXf?OfZe'd>u6KM2hG#&SaaG0Y,"\CZ>JD@@R?[g(cB*-B6Z4i.nfh-hQTKZH=&_O+=1TM-qkd(U>a(hF,uZIO\fiYt7-XU\dh +4bqCe+>#R#;IU%sL2dtS7$s5Piabc?d68s;[IFLJF/TJNZ6>o-E>I#F+V/?ks1<=_&DY3$6N\Mh-K-0fb%t[2`EAZf?qc'eP]_iE2<,#(g]c`rjH%]NbFI);#:(P2+#)6Y";qo'hWScoK/uOE0_$FJ0hrdq?2#7fI4!+,6'EZfpb.1I.+<,PPf'M#8-^9RKS"(tTRl\[8'i:* +Eh\br:/rPVP7LKc%"ZdB-5hikVE9_UB)#=a\Hr[hYXU5=096>fG>`O^e`&PV]9]:F,WN:\q.5PWh"OH*gSi"VjbL:5hjZQo/R;r;t1g7F6^>pV5P5FV_qF[(VNa?7e\8O:.O>b.]lgL.hRlj>qd*_Xg7A#DTjlt-Z4CYJS'fh@ri4p:s"0.qZWdMNO(aHW6\_muk[;H=TSek@P<\Kr7*rrliU7q_<=;g!*jm$'$[<>qG\V.-O'ZDMR[es>p<-Z_;5EOEqa.DSN$L<]UR^Ouh?-F%8n72j0'I*k.XP@Y\X^d^.pGD!UJtP$mU#QPa?:7`H2c&&\)[gb6OBoh1%s'$0^FVKif9^6.Js]edHb8m7\t6&!euaO4C0(B9u*TL$YVPRfImaSYpirlUmsAp]8E[Uk0)oA?!p/mJS/iBK5S9!YrgH.($BVt_n9bDqj@KPWT/&H +Hs[K_=#]O4cR7_9"SFY[cQA'(K=Y4N,`[FK;(c9-:[b`WcmEqt5+UB=5RLa0n_^Lg*mfW*4Ud/3b?]s/D= +hJdEujr]&c;1Iaqr@b>@7(QCC-G_*D]rh"RaB[%!kka>*Fhq7NWBS\4.':fK!t+,^Y-a;kK"PfV[$)EmtBI0;TU-d]EZ!47egR,>iFO0pK&(r]+@%KgY25X#Jr6[$6P4'"B;m(!kfQUDb=&A?WNm/B9-Pn-nKb[`103iEi2cA&)lfD<11p&s,#s33-P7IN&!nIh??`'( +Ak(:7@4<)"M^ZNI+#2-rTt(Af_c#AE;WfZqlRlrh0%0>E;YMi-q^umK.['rg6HT]-$K861s+*.Sk@9"lc/fphD\?a7"EX2tm1'5PY1QssY'8JB:N28q/1t*^1ZK;S%RlAff0i7g#aHC7LR4l[`\H,bj_&YV$Y!Nc,2$gjt1;c5!8/!1WBam5S^bbT#XqT&O;p.\\Rn;,%8ee$Re)O&"X%Lgh54l$O<4>MZ%-hqQ9E6Y'P[s@W-VQ>t8#.4]oZp6q'1**8-5%CpZ_9@a>:jnt6^(di`MVR5&KjiH/TaZZF)rp(//mha +:33#O;f+1)@`[(5+B3D6P]f[+dm%kl*&Af^iJg$CN&#L:Xn7rZ;SPl492sG;<>9jRPuC\J>!^ZEcnl=O^(Z'&=lH!Ei;'bLIIlcA=or^43O:/TiI+omo>jCFXkr?5)j-_\H,W +X]0H3/6-=i$%&X5((:7@]iR-2/CoMJ#a%0S)bK#7F:QgsmDoB*mMIbSFG'U.$)qZ>nSB"KFr+XAG-c?nCL&G*G1UeZ6nT$U:!9!)e=*]7a*"d[G?>N0=;J]]Bn;Wmd5JUg(ai\0VZrjB%4*&$?pfR4JQF)g#+.ak96q00_AZ>M]@S/1=BBTGRP)(96$Q[K(S<93#.qn)bu`RaLu_N, +=]9K44dWN6(V'&!4OtY$M$')sJ4!t&04hPt:j-81KdNH'dKqn:LK"bl/A-sN,8#Nm8uP^te:8@/)iVdJ2iih#kiI,TDgsOgIq-N9e=(%&XpH>=]U+9Yorgs^$V<;g<*1T2=U0MF*KZ[!DO;`4)&H8_'p4n+433VIA13MTaL=HiXKkG2YBl,J]d@.H%Cnij=\"^:'9f@]U^.5> +O^u">*l4WS"@3N005Z'\tM_7V5,$/?eVW_>.:1DYq;ETT,PDE1]mFgRrl=/\9c8]&Bb0je:Dm<]]WO>5'QdnLV9IXP3WW<2Hf; +qlk.rYe(RR>8OQ58[.d3Z+;ftoA?i7A$U5OZF_omgFi'o2*@?gZkM]14$u*a4g`s>[2W$q4%TN9@4rI9t,JM]+W`*)mcUBVn:]u]GducLekZEhn49q]XrI%oBX(OgRanc=o5D: +)s6-A\%\$I^"`.n>PF3umV\NiYWMe7gY9MJ&\o@sO?URCY/&L'p_]1JM>W9Qj42]i<`#M._>Xu`&9>oU]`>hgq>Z\n7>K,B)`Z/L.>\D'HCW>.J`uK0@>^+5YHcOoka;fiR>_gCjMoa\7aW-Md>aNR&S&sHXarI2!>c5`7X305$b8dk3>dqnH]?B!E +bT+OE>fY'YbKSbfboG3W>h@5jgWeO2c5bli>j'D&ld";ScQ)Q&>kcR7qp4'tclE58>mJ`I$dd]?d2`nJ>o1nZ)q!I`dN'R\>pn'k/(36,diC6n>rU6'44E"Me/^p+>tLhP:efA8O?"_`ZCY%<[f,\qa?$FnkHe7)'fH#Us?&.('MqHjHfc?:0?'j68 +S(ZVig)ZsB?)QDIX4lC5gE!WT?+8RZ]A)/Vg`=;f?,t`kbM:q"h&Xu#?.[o'gYL]ChAtY5?0C(8le^Idh];=G?2*6Iqqp60i#W!Y?3fD[$fKkPi>rZk?5MRl)r]WqiZ9?(?74a(/)oD=iuU#:?8po946,0^j;p\L?:X(J9B=r*jW7@^?NO^KjrS$p?>&DlCZaJlk8n^- +??bS(Hfs78kT5B??AIa9Ms0#YkoQ&Q?C0oJS*Ae%l5l_c?Dm([X6SQFlQ3Cu?FT6l]Be=gllO(2?H;E(bO"*3m2jaD?J"S9g[3kTmN1EV?K^aJlgEWumiM)h?MEo[qsWDAn/hc%?O-(m$h3$anK/G7?Pi7))tDf-nfK+I?RPE:/+VRNo,fd[?T7SK47h>ooH-Hm?Usa\9D%+; +ocI-*?WZom>P6l\p)df7Kg\p$erZC2"?g%E\li,f1ru^k4?haSmqu=M5s+*GnOB==\&IF.XiK2]64s:Mp7,j>2ZsGI)NCMrj +f^sVY+d#=VP$'W5;(7c&jc\;=^0raa9]hOA[,,d_SPJ@3g%>8p6(q-=PZfpcO\)BIl'0nE5+tiQ<9f`P[9g+@X]FbQg@]p2@Bir$QX(B>jdq_[GLG!]jC/og\(RIJ\ba`Qs;Nk&W+J9nX/*T59Z02AFc-n[U1bWc"?R8h"H4`U![QGRU%hD;5r)\opX][ +^L=D#D"a?([bl)8h/;tVh=gl"_;TA.S6e,rOic^*q4-;c5G?KhFS_P7[pQDnm<8AthY2N9iUM0jSmOFKdHU=MrLVnj^Z"_YI/]aF\)6`OrI4d=ht-jJ5VNlW!^NtH%g50P<#5a)Y]Lrm684WO$::u(0+:3%e2Ik)Yk1-k6noBG&k&u]:D?5P<*'i(Z#j=i7PU-?)Fh!=D]D8% +e9;s(Z1NMg82:m7,"T!rO!I:P<0nq'Z?2]e8huX/.S@"PL4Fd~> diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageParsingUtilsTest/img.dat b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageParsingUtilsTest/img.dat new file mode 100644 index 0000000000..93875155ad --- /dev/null +++ b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/canvas/parser/InlineImageParsingUtilsTest/img.dat @@ -0,0 +1,243 @@ +BI +/Width 1030 +/Height 325 +/BitsPerComponent 8 +/ColorSpace /DeviceRGB +/Filter [/ASCII85Decode /LZWDecode] +ID +J3Vsg3$]7K#D>EP:q1$o$N>iL@So+\<\5,G^LL-NjE<[*IE5[a2RJa3-XFkqZF,@n9eVk^VFc'/enm@9:1mM9jS"!dTMEqb2!l#N8#0#toX2(aMbe':>ZE_:<^TriioWjnAY&^gM+`4=1jRLW!YA=M/6)*KS9P +E`kN%="Tc_Aoh+fk'&t\ctIN)4XQLiVpoI(>.nOW?*DmIDOWebB%lA%.Q9k7iBquDi!)/,DC66[a5h8d>eXi0S^6MAH1IXb_>kP+oS^^pnX!PjdJ%0OEX9GI`IODGoc^+5,t$):"t/5eh:9Jl%POR,+@ +`"_L`O_e;>`Y"/@)9.H\bcnd!<%/i[Y`*t?_=A"g+ioftN?cOX9U-pGP&-[:aqBZ0.E[gS=!,Tp[!7W\AU%]<`,c@+1!Gh4biOO78m5==1Mkl+c4c.P3R3haDQ_#7bdP"(1[=9V:_X?B6-tiJ%7AMW9bg+EP\hF2dM.T+5>m:/p3KX>AMl9mPjLV0e.-I+ +;9h$MiB#L(9O0`\PKVQ@^%AEW8QM+YD-PU,c#m=DQ0j!,fG4pM7TNISG>'';n=`\3Q>N1*`,=fY;cL/)X]3i.h-D%%#lTZR=Eb4nESQm4c#_\W:"=CBQYkO)>Oo\eZ9)OOTmPZ5c1L%JpZ[0Wg66Z_J^/G][;ET8mCdbf2gud&iY[\%M;jo*/W8X+c8<7DOn7@"A/F)kOlVc9 +^)3Ge9rW_UOd6EWi=ABl\7;fC2k/tJc?5]@RI5KqkSaqa_.Km.go6f/p6Cg*RVnZ.P.HZTQKjTM?E@`h?=o5]Z1`sVll-GRZ0[r4c*QdV94+j1X)Q\"l2-M&\[hfjm0auaQE.^=g:P\4]pdY6[Q[ns%E%]U:DLk=S8TFgf6efTNuX[jXpsfhcS`t!`K*0qDjmR%^[MUq"i9b( +V]jU`SSqfcp)T3*g%L@P;VEAG)%4`6SaN"$GR)9CiV7X.NR2c*^IGJMX!^]GG3b3)l2%!TXm>j*caE/eQ7nhYXH?a[(jFjjc$Y/Y8_n5u[J@\l>l1/30nrI5r@g2*s$u,,K$Xi86eHe2?pm50OD'3`.#ehkC?13`/g`hCM%ekW9o;e+&1]-B=Tc<>Kb82T.F?BWiFFU#:Vn!h=76T);l"]Cl3bGMV]4Wc;2u&?-q?8a'&]:(O&>p4,e6EJR58t$Dg@nPFUfd3[gC4%QZZ/2mn@M!L*=8E0+>M6rbo!?HAt;Pg@F!Pa +-RLtXUI7F[c\\2^kS0tk'TOHc$;Af\,k7Oc)6K0C92"JS0qh);(/Xd56t7e^::+$::?`!QBh]Y?P\Q9/)Su+\9M.S#P# +nRLp>Og7M]Y.o;!=6gReVmKd&=3Ea3%.0[o;)lnU4&&mbql$mqY#O,<2/=>rCUOq_f/:0QCQ?/sV)R3o#s(Uj'5Tc(JAFje.r],,@">?eX^ia(ER&/Nr*1?WLZ($;Xljp4-Ea)CF"M$FjBia5n'ENVb+Z54tdgrGCqTu8t&24!oC +=[-S=2@6ut-O*(f`Ii,_"i9t'=KXb77P@3=_Xrl^5kbE009.3Od0I7JqCsq1.B/E@1&?)ob]u"CjNsK(690K%Nj>A(t^VEV!M/Gj>dE4G.cM?+OWWZR0-4SJMq,-+L6F'P1NKnSr$8`RdHY.;PcBo)o'5\VAMlN6.LBAj"/D/Tlkb6Z^DVeBoV-+dgP_ql;U +AT'[K]l_iL_OEPKmqCmkTJHok>RtZl+`kKdD[GB'2\Lgn*PkLE.2R>^9PuH&A+qV<:&/[9A__jO[%?aI'5Ml64WhBu2;mR7>CBp#pm1_L<3O\Q&Lu`Cc1lk:*.7*uF5D>kq>g'L>n?E_q`k?MT3H-u=LlgqdL>P-fKl=eM=hHOpGmU'>hIGX4KoQL?5 +hb386?d,SK[tO]DTCr25h>>AKSc&35pO5=7-b1dIrnfs9qEN4'O5U'lb4Q6VOKV\J.iJMO'_`i8$]lA%E$4>iI-=2.)\!ooLW&CCP5,6P*'"Rt4U_jDn3M[b]#"7SY\0M)d/9X:m!f+:nhcs5uN!t)n*$aC-Kd0Mn=[dqf^&MY:50>Q2!9bHC>&Fh==:n#Rh>5aL('(J*k&N]rq-PTE+__@rDaZU?=d0gOV$5$JUnR,AD^<&!@FQ@HT&TJ9_O;:]=%8\2X +J`?E3UDH:^A-!tn&FBtrLCZ(1%r/]eXjI[@ZOh#t)Nb[K0sFG.<+_)=&WguOEPVJ!,2J2@*$R6Z1!oI<6O;&%`UV\'1#R0$hZe&.qN9"N.0TZ!h]D<)'T`h3dH_i.i>,o<$no[b5dMUgLcE5_+gHFgOQ[4<,p?c[T]!F"%XT'imhq3W)9Qq;#h'\\=W5T',`o,N;GdU[mh)`8 +-'A!Lmctj/2&rmG,r0;P;:cKo2]\'&-LqB_E/>\mK-h4Co.a)5Eemr)=HLp9.?])u1'fTi$ta"t7;?-3Z5*VL[3>%k%YJj<&h#a()?j"m*`=j+&ifZl4JFSrP7g;0E`DO+9aWYJ*AR@9cNPs7P:pdD-;\t7Oi&fVitF%,-ZX=uZNV`IHQLUgoWn8;On/p9q(^s>.<5ABO^Bgt +4XqZg.V9AX.]=8K_?.NX1pXY.nE:ch;.D6K^DkS416[\3d!HC"V]PG\.M@9RkjT7$^3P(o0"NicmYSL1iA@2nf\HoWZD./5-n?NMZOR@@3[R=petkl'%WTdg6bf\7e;#Q +F:SU4b7aE#33laJF2($raN7C/&oqbRF#Q/)F[JpW3]&PtEsX78SKJUm&Q9o&n>es^.j*6Z4#BGpn:s-d%51X0/7QE(JB]o]],2$G"*Ar]oRTNjSOdhi!l38UoRf[jk=:U\if$RRN\7UBhW%?i2`(k(Ec"G@[7bVP9<-#[dg[T[]hE@67?]qVdU)n%a\?m19si_NkF53d+gY'&k>HFO;R>OX2).V=GRi5\#1Yk81kSA\I6Y(:8ee"Y/SM]Ek>,sC>BLQnl?-,Toi:SA,m$"u2/-,K[jKU2qUA]('m)RgAQX)27Z^VMl4*O^?'p+KVX@:KnS>F$44p5`HZ;/%lE>jo!r +U::q=V)2SXC:3):odO6iJf2#-?K6iq5uV-5qY%>rlEs>ciU(#f,@tuJ4Yu6SU.--rG>]Tj28Q")p@&oBol"8YDkUl`iFd*g"_p>&.5qYa!C:]LHkA:T%2U%)i;msX+*)QB&L)X0TgNen%efW#F125/iGsU&K5Yr'FJ5=6+h/KC40W)Utj\5Fa&%T +GIN!EQ@4!:Km7fuGdiZWpQ9\InTKt]@PrWr!o,>ZE#c+DDrG@V!c)h^,S,k6Hag\8i:[Zt`)BaY%=l3@ngk-7e-Ym&IC+_8^k$qnjaMF;#<1uR=7Lc!om[UW"IK(:p\rn/PQTP=J@40Cp^r'-jp)^eJ[abJQm$megM3CZ!Pl5i`nuCkf6fjQ%p1uIpd'Ql]5h%Tn.!b7/PZ_h`>#Bc(/afKVp9*Hn^ko'*+-ahN]mV2BMsMR]dGpp#`#0ISokMkYWB#.&!n_0,k4GUFs\Q?FOIX;Vr.)0jtZ=%.Ge4`d;mNjglb_)[Q#LQ?]TC*>*\Qq.b`"cs;B&Xa%T)#,Lp%?BG29=X/(:'MM971NBlNIddG +\M85lef5OKN/JUA2!8SnE:m\O%XCc*@/Z?KZ'AbVCK,k03!W!^2f)O7l'BLNG0a.]e=@B-q1ROhTrKFW;@gRbR%TM-o!ARn6^`10F#X)G@$-m#_jYg6'D\^I3O)*(nTgC(3k'!2D7t89Fdc^T#arm?g!Q*:6?;j="P=N=[#PSME"WsQ5'aZ9P3kAc>^bRfT=O-4i4]H-"FVCS +RAn/U@"Y.41QPt4TsP#!es2'N]7r?UU816]H81#&#GY^]USqj@g*<(uZ\^L,M.U100-6RG<#S\*HJ$,G`i*#Wg_k1c%m"PO^k\g5dKM<["8XQ_UP&^crW\gJJcM/H\ri(>r[AXVPP-#%cjHdU81U,3#I?p\Thgr>Z'Eh&R,F#r\oJ(%BpPoYQL:SW/S18_J!Zu!)g^9d\1+>e +I_ID;TceuT@=buFJ#Ls=)#K;'[+U[6-`UX\N/b"t@\Oce[;,QK82tu,[X))\J#&e6JOe\H'`J,AgSL?o*=p?0A([8E]n@ZS>&,X`sE[5M$t_onj>=es'BV%au>)egia>\5t67:FT^pe2;CCW1ZJk;VrCr*a1/]t$Jo>p?Qir,FQ6YI]!\]!R$L+ZY9DRMOYi]?Z2E%\^!6$+u,D +_ZI41);^r5b-net])/\['J/3ibFh/Er2)M&06!2?^_3RsGCo&V^'#Fn55CC]S)oI\5V%1Mc+NC'qgRbp)FjSU/0$N(Ho[f2d>?Uj21.j$ge"@Dou,h:VSMbCr9k'K[="N#;>$UL=DK]SmmoOSG<`ir#1<>b!&u$(V'%dQ*bSi6Tf: +8%sSqFLs-U_k!_b"]mh1@6n,MqKLR1$spHi_:X[Q4@g+KMB^hC,*@*c?>r@-;8%EkL0CSqrh+#>jX,of7;egI'#H(ot&+rrYPCbnsPssqDoHmWTnPcJ[!U48CRahnZpftT^u).Pr3,V)[\n5gBb``7hnQDp!H_[(b+4K4WV>bS7rP%8ps#E:C4nD`f:9tEQ&(hR+ +#mGrI+4-BS/f>+Q_;Z%DPX2&Z$Us(fR+-"6*KN_O&fDCD8K1f(hbokAY$!?C9BHkbbg'o[Rk3_'\^Zpj4eGO6'H.\rM++1:kX"K4(7@(Y;s'/;Ptn;VLK3XTRakjOr3'2g()n!G<0":_/JagTA3k'Vg[5jsQ-SW4G?sYRS(6rrRD2qp(`Pe#$$a&?nJ;Fj0,]biA+B"MPLCtG +b@U8_=0?E-S^1s@)BAA+8Pml7gH(HdY6D&[C\A\fQH1eg?>]>`*S0\)^#*c'*$*a3M6l5^q%H"XS'I)[A[uHH-=YCAK:c+R7`;KYm6>3f9@[/4,:@ +jcgPF3Q:>_SHEjG>8K`s\4[\s-Hl=7Wj0D?%7bEt\:Hu0!m$Ua&gUl_M,HXu,r%/aikA"TJV,CBd:g!>0[adC\$?Y-]#HKqRklcmCt\+$9_1VBHcF1$eMd^HKW-t,F/*(6KZ>A/pdETlq`d,-[0&J:D3-VB*4/,dRnrZdUBj`dH;u-s'I>8&;X*D%9es(U3deDTO\&5GFX9YO +"I2C1F]6G9!ehR(;9RoBNV4el^Z63XDb4jhEQ@,#\d]3`Q-V4VJ0_l_*.*YQtj-s^W9d'9acc>faKfk-qTDR=7KUq2<9V5P??tb,WB$)Mfd9>E&U?i' +)cR?>9p]GZ2.r1ODOk.%./B-4NjkD\HO*jH%>bHsLj"KI+EfY\TijD0>,O-_d#"T6HD4!$]sc(_U2+Mo]q@]<:9's$4!i4"Ynq$#]SG6R`1e-=LG:(2?e`E]J7)UD#lbW%#2R+7BeiGPBtQqKQB"(?$!;sFL,Hq[RIqV=o'0%7a)cR)13)p]S(j6.>j"c#7R8N_d+-Jb +9T\Q7G:*T8]qoqV_Kn6fXs&5=NNi*2/5+YFeXqEQ@98+qkA)Q>GNU-bT]pSEEBDi0*XFn5\#F='Ga^K/A+6;?K5ZUkG<((jYV1@QX>$di=c4 +7Yn2R_Y"*O@?\l[M!=*?GG>F9q9'2N.2A2)[.t>Uh/+]N84*A.)5:(s0!C[k5)7RRT3LYUn$qNdaKZ@%dXr;IFq2L`qCH+j>=JY91I*q8T:l#5HNPlU7eDXs`r'n/m-'h:(uZN7P7.h\>j4%X,mMJmBoR'M*>U%s6".]g6c<.-_P\)B,#Dm4;H3OEGqcQo\Yb+cg)H+;)'R/m +eckW1"U$8N\`+#k*Tc4&b5#HsAX'Ne!p3]TJ7gK9[&f,-jsWY4`t]\+pm@6\@NFF[s.m$F5(QaI7ohO"SkYY#fBYG>Vl8._K\7Nl8,&+Ug+!+'tKF(?Ak +eErI*/e_'E]c>&i'+Ip*\\ptd/La[MQ32`*7RUr@$\YOWPh)=&601jUeN9[np7A,ab>;pg6`=UWF](F]PP=QP<[)m9?QFQs3SeVc[^LA#bULM(.FpWsM[L*0@b7f(/kL/!6*at;,5Sd*fi5Z*)4UJ)CDNl"p4A=NY!JnGWe;L20Nl".2eF!)?)G`X@keM8`KhVVQ6I;j'=3iEc+j'6>Y=Cj`aZo9h9M*%DClBR@?QW;".]:>!W.ns\'+\+%nS?PJ9-2'+MiG!M31WB/;eQTDk#X_Tc2+kl1tCAB(P\k?G->tm>.pZr;8(\UmB_72Qa5qK)J^N1S1M%$Xtd;l>G4NNRBscJ.N9O)CXBo'eRIgqAQ1d=SN(H,.a!eRjun]]p(P`Q(o/@=,%n4mAbd[4I^J=0G(]8\b$)0&TjTJoFnM_9B)/"8sSA +2F0^Jq7`tF]*KbWieiW65C;P#MiMf/6qUS3Y4!1Foo6+O@!P]b5C%n%GlJqS4,9$jSla)n:F#"Lf:/rs((!T0?d(EP14adB^@Q4ec;']fkJ"B%SQd\Th[`)c=0o(>?OM6#JBU_n4l,cJF)#QLLM],eWP\AtrLN,N"b<]V.*k4E#PjkTDO*2HfR +mh@r7l0=mjn-:n5VSLm_Im)K%hC!s*I),sYO%&paO8BA"h4U5CJK)ui]4\f-RQWa%]hq9F1Y4m:YIXG5\d?tOUVn=dJ#oe)]>5A9dUGoK&"-:0K7"U$;> +pj4Z8Q(V@[XR$o]X=F_g!2,Iu^af%C3X%Z',f!QNV[;(mKJu/XYs>#35dJA4@Z:K^.4aI9#J8k3j5:jO1:?r^#2DO/4;3Kl'WG%HLLP_*R]V,(FMs(L.@_9T]Gdpe)oCg`W]3>`lo_?$,=MtuZ[3i^'#qe-R?jco7/3CSEQbd@R^T4\(t&,0>ZNA&:4t)G_YDHlapCDg_8Od_ +3C;c$C*Z7-]#-9&_qZMm]NIU)5.tD:`f]LQJ?ZqRd_hfu046EPls$LR3(F8#2cTa@[JP:5"A438i7E:@48!nG>X10As?Ur;@[*^0Gkf>4$?l/C-K62\fQo2rE431*L86gm?CkkQ/Le*%X8=YQ.XG]W^N(D-m!qHYKCl_*nIuN0E%)cGT]EKWb&#"gWg5Xi`IhA8;(%"*Rt\BClh.SRtkOeeD/ +/B\\@ZV:^NL"t*A'*uancV48"[UcKe1Z8HNS-fC!8bC?N%*kjmR]L1B:#+C$A:ao*d7t!%8dqDX7,^a!T2$*!9O+Jj<9F[SWM#KUaaDg$`2pD;Xig;'$#Hh='XC1BiC0aM5TJiNWA%*tSkaW2"Hj)'[(M^KElU!J#N8r&RL+W-r(J*I-%s1^m!-`I=IdMZ'V*5nPfZUd`ltOL +WZ5#4f[S0UHHrJ4c?uG4+C1^0e4CA)6-E_/WAQ!C)9qB_[f*)Xs$;;E9jm2i(M(K(SH[j;AS1u]XBU.u-h.GZ2ir8o/V-I*=hTNpa'FU8J`la=ClcJ:)XeJ97&Z%[S2c3s4cV".Df:X;0\#F+m=3XJ5SpQ<\pbMbsJ;IptK +h$#A.:Y9j:ofjck`6:fOU-Ul;KLsCHIaC@":fQ/K)"7RV#6rEY;RjltN1SD'k*$4(btQ;T>0b6hM2!l"$67[F2$MAoTZtW[eI!QUZD#^[92M@R!JO]"RhSk]Us_:-dS/%e>rG^$QVr,Gec_r"RKZTh?dP&h`>_ku4YG%90;"dhdi>`t8dD2%'*V&QJ9+gTOAtbj<,GSJ/QF:)?s(ZSO\Jp(Q%@@]SCO8Lf@fJoQqK;>eZ&pU]u82:PYsp0=TpWbCo5X7a3!_:+.\j"eOiuV+PG#1-l&:"ue/-4KncJ)?_>A=K!ICRX`IGFu`\sQ`,d%__#^KtbV>RGo7*Q$Sog>'oMgg-&tD3EdV>p*-R9atuBrKeXloh"8iT+0*#"fSo*6.R7KIB$-*<2?1m+(mGQ2WGH55&,"8>766TZ87:'MlWZC8q +Pg3K-JDQgEfJS=]h76Wns0<#Q?LX]#3HNW^MV,5drh*A#`s(h,!\k4mLEP%&)d\nLKV\!atb6j,"LR9>8;Obc6+SP(8+tMhMrH-Af9?H)Q![l +@9j?ul\u:(HN=m'$928O/k=n1ngE!4Tme5d%OC&XT&4+B!oC\OW8iS@@_)_SJM:Qdj5TIPfPKna%PcleYb1nN_8\=Z[KY].-=Crf@"p]"ONL@U+!E@0;/fJY7D8sI5L\a[i:o$>.P`B-;7)N&7&3GA4u`tj8>&s%c@+:)@=8=1Hm1pIk(RYMN@T]`J7TS)"%IlA?7O6K +RgeYOYd,Ne^g/Q>Bhp@.$sn+ZrK/4lMuqQEBULK+rf81ic\ER!koQ!RQt,AA,\X?@/G]Z0XNF]e-Kn18`ca&QAt'9LB5,Kl2oo%`iI(p=TN8Z@k?als/0^aPOUPi<$G&\@K+=QDV1?`kk7)TI*NRD)118[UC+bZ_2"KDpGb=t\c?3K.p51<5LM,"&6*@D!I3R+O'PJ&RAI2@L +jJ1I1Koo,bkJEd*0R2h7^a[!UTU(Q'$<7nnNs,HD*<*ilDT?HNA"]5)kq5G>@Kl"8a(t(IBS?e)5#5c@S/#Q-Bt7"'aCcVo56YZ>/c4;R^7oIh`+h#c+J,Bf?DX)?7$N3BmFhlR80/^6%cI&];tujdRPFp3jD*Oom%puLSXPM7Yb.etc;q7:1>ck>(h_UglYbm%m*FF66#2RW +/RH%W^:ZoNL*;;,Ct>4q?GgRt"mdk^CdsJYQB:QYr+N7SC)3u,(<[h$bYUp%jCZ\N72+bL:[J1BD'%+=B%(Ta5B"]5m;=ecNnA<\\a>P)l:"lk?S1Q.&4;DSCMdcF*)sk1td\9X:IIl1qfH'QQbq:_COK7e4Bu +o>K5PTml\(*p[d2Omdl*DjJE3VT!J^`cB*S0n0(oP`Gi`(t;UdTDnoVpB!2V\*uPl9kBh]=\j!L#*8K`TDm@3)'s6r"i)2gF;j$#-DR5?g4t_"nHNhAEj(2&,Y;V^A-WfP]c_lH1+^`flK45sj@ee@#p>QS>brb:hR%:f([fbXo^q3YN6d**=P!AOE3]37n<3CEHJ=+K"$1R,l@c-:$u?enX!;HV]-]g;:Y%kp'R8Va&MU/f +2>On7H-,ROhY(AR3.&pj0R'40?_[BU4aKV=qH#EG63$QnVsT7_qOae^O*Qc4b3oZ5FLgs[&$XO\*X+;S44CmB?Pn#0MH"em<7q]$;om:o]?\c[sa8145bqI,,p&"83^!5cu!5EIkmRY.>r"0(@ca4Po_8iW##f9E.-sjd;,V\gSY1(,q_opMM&B%EaSq4d6 +4'jL-;'\R@Sg=5B'Lkci`u;pZ]Q"pn`]SMaa31_T+NI*%>o+!V4F\Wu;I#U2+i@QXLX"R/h'9_+p;d@u188F&*1X8S_o"D8K]^W`ZPMGstcdVgk`h-3N#Y*1iSIhBRe61TsdFO9U/"/0e.;rDHtcCCulS*EReK(f?[rQq*"p-M-NR/m?!SR;&N;Ef[&3,BZB`C>m3;CS/lF;NKJL!bKoQdWn*LTfb7T<<)bGSP@6Orh""=[GhmS7kd),8^#(*'GMVR_8E6iDJDaNJGRWNIp(1Ng8%'7]iRiT&LuMO..>QlL^+kP6R,/,X9GK-(OO=ZUV2iL^:.:E/=^<+q +AXQsKR,lW:#,fd-^2ZDN=krg=:m;g#T]U5[9;:PD'e,s,FN0`GZslLuTuLQEWDVQ^,u88;XpnO55BA-fVeZ)I`EO->oIt9%<@qdaD9hWf\Esc.V7Op>FOp/RIrJUXR5?()D9+b\>p!5#]ResJ +=S>kB0oG\WO(mD.R+[nZ178#3cI'0MI+Ghh;`WfI5#7H>Gnd,b8,00c#-m>4]^MG=DOpFJj+l=W[K/&?9c\'M.5p[#*k8G&ba-)Lri=GQ5I2clLD+Jt:(=\#!Jpf7S'b3/)@/UFLp7(-J8caM"=sT7iK&nQJjn@32CJM1b?L'\j`/DZ6H%uZ3F3Vc +]t?]LAIQT^229K7*(-*9%:PbiLX=HiT@d=JQp=t_ME01t\;(^U4&cQ^H71LlD\U7(\p#dt-5;esRpK%3M^9h4]_BLBhIL,TO.=Q[(qrn>WFC2d]YH\?jIY&oqAKt&23jh!*mG[7N=R3*8/"`FA0cFQB^fNH85s2.]5N0H.ROn_qRC'>["'o"Ud.HZOPn;c%aof"'HrYgeL;aT +0ru>:Qn70+l+C+PE9b:(6;_.sn<1*4YsN/::Z4tsKp(k352f3ii]F)DDQ#Ti)3iA&J0f$Z;;9'&Bbi%#>B=]i02/Zs(g]UBI&:e"7X4oF@oV/0OgK>Q$.N<,S8sXcQq^=bIfog0iLFa35u3\68d5^p."YKM8?$Q3,\q:[oD2%Z.L)@f]`%u\Bi6kB>,hrI/>CSr("&;f_M-d- +JOQjPPj)B1AV&9q;u0\E\JHlq<5!sJreFDf"pufPkbcfDcV/SK9W@$.Da7_RMA`)*k*$[OP:C>p\@R-%Ph]tOg2Ke)^HKfrjdaeoFj?u?p>`)^X453LrVJ9PB(PJFlP[Mi.`sK/J?fL5eq0(tK_oAK[d*N`XY49Pg\n +.BbE(Q:r3&#jI%ZZc[Y`g),p]m2E@"(4Oa\0h6!D)]#BRBoYncR-EDmfpbu%Ut.T'<9g;\RoNq!`qm.;USofTeAt9fR`AP>ok(bMlKD9c#@&gnF'=j[F'!I=A^&C.T@NTm;(DX%aUi3V6AkCg5dPds>o5(6Hm?YgbMZ5&\QcG$!SD%t9SBQDqYa;XLdG!!(.orNbkHs2EE +)mna8b9m&S9rUgV3%"mfg`M2gSe]-;B+6IT,+32&/#nX%7@QU/N)P>P6_da/j4)_'5?tMKU(oD!c8U%>PoHqR%I4BaWKt(ph6_I$P?fibQu`\nc$A:/QsuHjF<6*g=4k]c6E?nPkg>-^:`S`:4/d9CV:6QISB;>.>9S'//[WH'talr[IW^m_smeqXK2?(QaVk2*$bV*U)lRK=KJ!Jd$n'-.9\*-l;+9h:9p$V4#meHLp\iOR^dA.Tq/6R-jlf8GUT#b'a8[qi=4K5mmZ[7XWN]dZ7K?DuTi)[#fhop1&pPYAP(NEd^`,)DDs0!kA"+h"X[$m&u@D_/0\qSi=0iq3+E1BrGeqo:bq!haG(UmjWC#K"LYlr9nHf'nB8;D00i#6sa5r;L0HriVLBcg[%Bo^f9]oIt%4 +TQ:K,I1),bXNsr?Yd"U'H;:0nbA\YnDNP!7me9M&$uk&Nn2CHR4P_\V:S@e"$J69dpB9ta&&UF=Yl_<5pCNEm?Edl[0P:k,Ym0AO#;5*DBpS$57$`6#qmS'0.=&#/ICU)o-+=0d&?@DXT-Z`ZbU,f$31^7W#[ET!6ejP&R>fRCDW)XP].oV`gm1YFUeuD +:CuaVOR,bnP8T6g"OWhSN<^!aVDE/=Zf$l`&If$M_YY_R(m)cMVN1s*,ohd>)%k150VDu"ruHq@#B;e1E=c4@QC^pB*AL0-O\Q)m;S@">'p64u9]cL/$4P9L(<>M(&T5N!F!)#L$kaWucYX+EE=J![%FQ1"Oc3'*OUeT\67a/[C1IYA7iq-d)NasL90X[&bpA<6qXM)a0teeC +1E7`K#:\l+5ZK1/8KC8h*f.,(6+87:QD-)trW.,<;=#i2nJ'=<'a`t::>[/aAq?#?SrJgEEj?P1[SmeO\^8.n18t625qJ(-Q4VE2:t6C0Ri$1b!HL"NE]Dkdm"%d]Z%29gYb1"(;oO$$;PBeRRQ*.]CaMZ"k65q*?+'Q<4b +LH?STp^8hSA5E(VkY;9P_9fqP:FDQnm29Vpd6(FSF5AgsY7<;!_#p)Qf,\0/Fh+EN'lWNjTC^&G$&:o*H!b%60DS0d]rQ_$rLur"Kgf1'a:(7RCc2Y*(6u1Fp@);d5j"ZiX7pq!3&$l[c3Da6S<(7k#BsJECPf`-pb=)nsXh<%$kia#:+48l*Ui#@77#c$:saqN@ZnbdS\Ij7I"=e[%fNJF>Ph>!0_C21nO/DUJ$O13jX4$'7bJpof.'#kEIkY'KRsY*DMdQ9o$JFM9R:LPsf_:8?bqlX&(f3 +&>&LMQNF!PeBH2]^JKacjorhJ.JsF9(/djTC!EfBciao^k.?UI84s(`1p&:Q/P,*Vjj^AG_)G=n"K/85"UgJ+d:du/=&kMii!3W=_c!N/'L?_GD(T+qSR:TK +?oA-cp'G@]f_PSOF>b:Bp)e)c?Xd'EfV_)Gd^N]e:Lf^FD:UjdbQhZ'$"RNRACaC.^rid8*AeA)A[D4Re`aCT$"f0c]9UE`XQQMReQF'ULG'f@o!Q"m7aCA+kh2RRNsGpbjW!nPD#_aS_aaPHSkbj\dNf$d^BQWP$VD:a8>p>L2< +4`4a)DRSqMoq?%+fdT5E&%;Kf72kg!;/6jlB!XZqIq,WpX;]r`H.p&1Y4lhpI*lfX`ULsFSATgpJlPi@l:]%Cj*d@F]WCgp9c@.G?3=?(_^$S=b)ip+@R:\G"6g7fYpK[L=TF$f:_!>*7Fp(^i1lt'!E!6MJe=&gpa.`IHEEO^"le!Vpb^EQ*8^d/^i;;d/N\W0&t;\n +r:i(2=[SEM;1#'U'tI):`8b?^F9?1\HW@f8@%9<-YXE1'DM2)h8d:*I,;dAM]_*@oO:lI]/VG=eh"6Q$9b,Rb72!Fg`,aBq(O&Ram=aF^(@.M4?KAQa"5fB?>`_SWQ8X%QWCJPLks+5EpHA*R<`]@,%;V1;A%;Sln2hU"\9^l_'[SE4C3PoE_)> +9mpmCLku6MqBD5FScmGSn+gUEpmir2EF7@oRolY[iRs+QQH=YGOEs^!$PK=7Z4_G>Mj_JN$'go]_eU-\UWMR.H?5NhK:9?kGT!`R=gaa1L)i='=BWgIHAl!1O]AtZT2"U0H.Pbng+eW;Xc_6Hq<)\M%8WfCU;0m=&@;[&q/H-fT@s;kg'=[If<'[>PbQa2(egRE]F9NtI#7G@ +J]s0_5*g.[(&BPd2^"JFop41*UR%mVl'8%^c_P9>)nR2B2R06JB3K%ZSsin)RZXHrK;Np\VQ4kkH(Kk=EY*P?Ql:=N<]R)bK;_t1S"!:r>:(A;@CB=,WQ3Ph):^_*q\_rgH_u;&"U>g$;0T9:Xf9>>Zr4\WjP0@UCmK%(&,V4rDmoPD]%WdLR6G.RJu2bJH2Fa$oK\W`_n;6% +S1L\;=s=aSY'h8*])+mJmTm9/@AWX$AI7Gc=;APsB=0YM@ChH5GNHOE=qFpWAX*phThi)O-_$,^_V?f^"Lb13>Jcml_qL$W*(..rpTf/$;Yh;CP2c8KHB,Uh:m#uhTn;d9WPWQi6TIDIp]*PB%;r#-,O*a]m3_u!`W*.Qn-Mt +>csRNdE>]QC2)6"X;8T?;,>pZtRq8L#uC&j?tM$3-H"fU%h1UaCLnWV5id#n(-f*I&A_En; +g$+jIf7D0cqoq\$VkB=<*OF$+Cn=qGS,L/=r_e8Pb%5rDR[&H\&S^'LfI)(T>CMe$*TbS;l(#I6dKW_/>ppeC/0@6-,RW2W*XCVZ`:EKr/;m@N$IGdLS8 +TWO..k?<;gM.c#)XlpZ^gf\`khM>`LNMiA1l5l;=?.tq,hs)3]l3U52ktE,OrOL[i;[Ak!Bu9[\dBZ4WgPn55ot9J=&'&nK!D.5"kFUp=R37i.@!NeP/hCO@53_bk*&rThJRq94/\:qo^Ri*S5AF6=u8B<8T`DFPhL7Cd8?lBlBN]=?B86kjofg3#Yume[>;`"u-FI%EQIt!$iGlD5mP=NQrpb9*^TX!Ylh:DW_-lc">W*JoM1&k'R)ET#\WP!Ei[bME^G2/#cYhFk +p4#B%d:i0@>lEtcWRMnFR8%k>,_aocF^&(qCN6o@DY#&8p;;HtMPiG&D'dYn.(aMFSDJHSU!`(D\t*-(gJ`:F,!2;IpO4/YnTD1O.84g--uJgtrndsp\4QLA5*GobV/c>+IeX;#o@!\)/p^tD5EIZF/AWiY(3R:S.5_Arn<1(p6EY/4OWK[/6ceoY/*_X?=NY0Pj>S`m#^7f-X4jQn^Q?Z]fXZ5-qWalV"S4H;)YkFT./T<"lGu[4UJN6oV7H!@BdZjR@?9Bmd<\;REd*85h)L$D5M"aELHXPPGki:='*j!=0E?71$Z# +\YiP.9cZ3c5:+9O2S[5E04$mu[;d0P,0[:!6-1Ap9ir"G.W.kE,#'Q,$ZnmM:^-Nq&u5/X#8GmsA6j&FscO'f;O"F*nSVdD0[X;)>=cN)CCcmU5(bPhH]0-lYU7Y>e7lh;T:L%nBM6/d7VS +1p/WnA>aQ4Ss^JI#.&.&$)B9)XU7-9Im93Z)V4a!0-/k+*a48'EiO''LEOfH+gAY#njfBpOk_tr^H=7%off7)Jd42#T<3t?rE7]D^1n6JafHb;6QIIsCCE]ra&]@Y((`#Uo](4kn$G,43^'@aqBEk#1'_+cIpT?_DZi4mW&qH$/WB$I="e4p"a4Th("EpJ=!fs>sh +FcCB"gh"hJl,\(^nlFkf=f5fCk_%c/huqn7;Y!;*j31^'5!lUtqRn1<4',aX?`82Jp8RG[>/)&cCS(sEYJpMh)6ka*iLf_O1)Cd[D;U5WqL9q'/+A#Q3.ZS`d@Uh;r)#m>#B3Kd"VkLO!D:f](b<_HY7dT/Qg<^K/Bpm>7k4gC':<3'BZ<5L*+X^b-Zi-j'cKSuD*cB!KVlCQ +6T8CYiG0BUMCoa0LN"TsF'*e:"lHs,!t*j6SL+g&*L&h,'3YGcj+@K'&k6=cqGB??EGr4G^A->X`?]YZ`#sb(;DOI]bArCAU,'d+.f]\\!b]pmMSO4+!p"CnE0;W.5mSb>b&L=?lY\P`#W/Ddj;r?'Je5dBoGJr3Os^=J +EcV6i+G$ITp!)/)Fslp$\r$=Pe/LtuW^`\.DaAP:H-%q9j_/ahtbKfQ+g#[i%L&T"%%PPm@pUg[0+NZcD'XVrJ>>=(,jLW8C6*#fl<,SAII&Ts3XhmDtuEV`A*B`^@D,jLK>+p(Ps)'e?"A'C7b"uu%'"Bm@khrg7I#Rd'Vs`8nLB5fC*lFq>kjkG??\\X[/6B\66[)o4O8L\)ATTP)g4DSIog.e9/$Hom^c35UG4+IG6T,rHfU=O)'-ir:=&=X)qtXf?Cb)k<)&D.')a$M/FP+ebqs=o8r&'Jh1n<%A1pClM[+cDXH0:-bShuqhgFQikhik=!cn?eDXJAhdT]sVQ]kM&B)17XUoTU5D_mug]%^U\Xg)6eSif*4=2R[QJN)1JV9^HV8ApSY>20%gXaM@;@7G;?s.=qHNA3f#?:.(@:kK8pBaP``K'I[)P[:N\F^jP:_1i7=s&^PO/\otSBE8hnY\U&8>[:`.'QY>e90@3GZ$Hj6-_:R&Rd]T-,Qa(VV.i322u^b[ACfc+ORahD?R_To.QjI!pb"AX96S<=WmRVf^GpF"pRh(!LXAG.%N>:)5nC]+*I>J&NheV;p)_9-HTu63ICH]ZT"!O&^No9>crg&`"GV(Bb9=Rna7Xp$h2S%oTaSXbq@q96"cmZr6jM?@+(sth^UNlbpYYljL[fgXamKk6FU59ft!Mgp9KP7e7E+,fYniU@aL:e/#Mphc15J^;6_.4=tF;McH'u&`H_5&!cZl?j"*5U,D^FUG>aIP$,4h_UR_BIYGlfSTP%72TlT+M3aMglp2NJ@'S[s/@cd3h/Bq2%@" +6K3\&/2+cjqNeWu/;u1`dN6:o1rE9M_dR(CF>q*j308eO6_lc:l/_q$R=f$5^c7Q';KSl@"uV$fQf/FD1K;/YlbKNJ5e6P-F_CO<*t^=5=Q>NLL`W88sR=, +[D6i'Mei[;5YX53'e*:A7\je=Ztm\"CrXtA`oM$W_ltXV:Ic*k5m$Sp]M'-/E^s):7prGeoMA%oGfPp7`@4rJcm2-"H,n9j`F-2BJNT>K---_t*<7a\Ub)mGG_#.7Vc5._Qu>$J4@XF@aIo;]P`*O,@k!pY\Qc\cA-bRar=j?eaK1P^dgX8B91M;P^Vl=-E/)DY4\:$hae4O3 +WKIY;>6=GcaY\I'Ck%JE=t1Y17fpsO7"`QGPlco@W)QlP`/'Vhjp'&$8t_#pA?3en#K-[t8E7k6o2K5npdEPH4h%e&DO%&%pRiZrG5icj`65c/dWu9Y^s>_'VHC5H#[-dMIJVdS*c-L,A%k;--@,kEV:m:%X<0W2WJ5F@JAXbj*&7>d-p13"3$!9f2.W0Gi&$"i1&$9lYH2I.trD:sG[":Q5.]%,@:R]UE[66KbhNNq2Md%;<""i_a4aXEDdLFdH^[+n?EOXK>j%UhDV+!X<1B<&uI'\@V">+-76_/eiJ>cGW!NQ1JW$']dHic0ZVA3iJ9/mUK9\.=7+f4C(I0l#BpKn!2$C!t'b4F)sdl(hI&>$-c=S].8'LhbX4M3e[/g+kuhi(M_DOBC4Z=RD.W)k:)H +*SD`B>0X44rKN>iQJJEBq?I#^`3:8\eNg<<:o.@#I#j@7gc=cUfp#aDb`@1V%PVI!p!"MbZV/`6"$P)=KUiQ@\$h_Sgdho'<Yg>TIZS2;KF5TEuWXgi[Vl +KufF@WnmcjgprX*?0@+,c46rc!sRm,FjX.A>_bK0JJIUZJRi%\eMg#I?QtoW^fi2R`!3'N?EpNJ`70P?gfc<'Te%\)p"n>tD;V&<-6in&h2TFrL!QGPYMBiE1,REl4nh`h/3I`XmAj+=>.je?WHUQ'1'iWQ%MOk?suH4*[?JQ#`c7;@R37e`?6JO'JkAY%B^5MSE>P]R@&]qLH;#^%POdM(?0$mYM^e?=l/+T0q,51;-L55OVcuR2&'I#;@mhVaL#=nCLAb:$A6EW>$5?t-=SDkj:2l5;!Nl!1?9l'id+[sONcaep+S!OW?l(924Q+/'e,MLAE*W\Lg&4R +7?B29jX'q]P<\)&;&?Rb.$`\$;.UJ`I>*L]M`s8#Aj,26^uOp+aEj`bQ<01Q6&k#7?`!!%Uo@i6@LqF+2YD525#e`8dU^'^k&tM%XkBZR0':U_N@fTk;"-fRo=es);-!h=.NY6m[q`d;@6Nf,ksl/kQOJB6pYB5.=ekTSD8`35/@^`U[#l%P6o@2.kOe/cD37oK7RFKs%l*e4bk.L$,OOatMcTi<6Ga[n%Y&4-$Ca'gUQ(@2piJe,B+b5DID5aCl,JN;?82+DOK2GY0,`2aFoT`mb5Scii`oJhWHUp!uDTOn@3Yphsnrn%QDPcJ.a&`_@QoE[M%[($BSEDK%Bn0[B+g0&c;5]P=UjKHm/Y +pBp8b$gOlID$#f>G7MT=onR4[>('4W;2?\&,h/+LD)W_sR9)p1[16geO&$\cE/*QjO(lYK[a/8h@;Cp!70K#j&li]g9)&aD`&:?:480Yf;f5LX[l.(o"57>QKr,W?BsLH5r)4)n\*!SO8LOQU]V>49=H +Dq:GWLoCPZAA;e.l1UbA:*XnH>BFcjioXB22[%?rF*+(IBWK(XL/W3G$ZtONKO8c$NIH!d%s&Rm*+C_;I;&1KagcN[86)jDHHOW6gsc3q&h;82j=&-PkeCGq.H#hD%q8N +R/*):q59\W\!Vd!SGCd-q<+@FpRh9eTGA?;qBr$62l$4>V#"/hqIc]%GGk:mW;;j[qPU@i\#]AGX*YT=joKhR\%DOX]_gC@;ur?,*>^eg84@#f?B5j?$^_;rU91Rp[A+enG>l<>pqMH1r@!e;076]=qA:GEkqg[H%\(uP3r;YC+H-??+5_'oK8N7p.%*O;biD/$92B<G%6DV:Of*]O#MX]B/SSJ&#H2=?IP[%/.VKEEKkc-0pV!44!9rHKUF]uIj[p?2iCj'#GVUaM3ghq=?^#o';^Yj'THWP[VM9"[kpfn7=0:gGI`M2/uVcSl"lum_]]oIBsamXJ%?9]cd\``U2F?X&E\)$NDB0KZeVpjW!omVBrD>u!Ys1f0Rpu]@g/.D]Pcm/bm6',n'#IZOS@&S,LF7kq;b*lns$-OE*Me%GO`CUB=T0=#Da]WdQXUqe\)],N9D%!h-]99STpH-$St]ct[a/BoupYuK6330(Yuo>!%Zf'#NNS#\Ko'?aB1\IZ=24\uXDrB\ekAA^d^%.+DmcnoQq$;T*0.lgL,X9R$:e87';bk-7C92\W?>^"#J'hqWW'hbH$-"D/"(M;fM(*pi>odGSl='aiL\'K6EP36jC@iqT*.MU]/sF'ZhS&_g[Rd>gbfAMp!-QK2/.++.2A +eWXQIRE>,7kDT;6C$6>7YG']0lJHl!H;9_]A'dZd$0c\f!D6cZAj**Y%5s=%?hai39l%?KbG/m4f#7%Cm`oBbl+!=a[agjoXgIM\#1j.K(pmXIj>htn^ZsRugQ5nb"A>$3R5Rp[6sN4uO`C;1A%U^J5&Hdlq:1n)kF)=#BkUZjXeP0nhWrY`%;uDl@TP2Henr&0("DM31M*od +PCCj6k.<9oGkW6%B?E+1?44;gf,bOTG[>17i\fRe?+nf$D[X[6*m,Yj>[/NRm6j'[=iFtP"?l8qS+e0!83Varb?4\_1X/Mhje'k?o"RQ>9:[ENm@JD#Fmj;72"p5$)JcWe0F(l&SJu(TW/+8^3ZIj+F]du\L_:/Ua4/]_cD6+;E8D\A\9/qQlS+Il.1sV.bn1XX7Yq^(,paCr'22A$M?Zg)0A+;dAO:X'`qh8F +Qk7-JFab*fdtCLBP^PFd^CTE*8r_nQ"X>_9K5Hp*b<$FZR-.?:hMt2P/dbR8lV$gtcqMJ-R/OemB)5C/KN`"L0)Q8?54gZ,j +7;+$\jk4LH8eC[!qFaK>`6"kjbk+O$h$If%;bour8Od]-;G*1!VD=fYP5bGG'K=6g#u9GE)Delp=$lU>MM7tP(qWmm^-@euq'Kt>k3b5^;b&mr$^IMV5E53qlkYI3Z4=B"BjVr_Bm<\DBogDsejKorZA3lG,.%&,8Wm]J-b +]">o^Aks^oZkK0g=.:jWkuFUFerJp5s2u9HAc7orto) +^@`7\AK/#GMC3hIda,M\@@Qq>^MTRY%B,nf0^;k"!`81*#6=-cPg:e!5<:K%`\.GRTE/dNDs2._)Np^fSeKk1-P!FR4c21/7Fb5L/G\Zmj9r.rh!tABu"q:!or$>JhjHS_2BBXAm?L4YiQ#)WLF:XPi7A'G&`h0;\.sTVhhT),fJ5#'OmPuMXbQ1\l[bRk%tR$lW-)E +GinR1Xpaj:R3ookLFj!]X>b6" +ep',nn6/2^2ACDfBp2lmQqP?,LCDh'f&'pQjg&sQbEKOsB2;Gkfdch\]0V7R_V/'LLfbZ0=/E2e(TaF+76O%\)0s@kC*Vjm^mt6jaLFX3IZn,rV#i%*c$qO'u'1LS(MthXl;Gi9W\MPB)U+MpVai*&g*2*IUC@qs$u>P?a'0PhoI+Y +J=Z[+X835hloDi$&o8oQUCn0A5M-j/ri!miY(+ADrGNru'V"6$'Z/B%-538A"1):21o0N8T[=:B.R#r#`l0Ot>`BEW9j"0cbI0QdV>Glo0V#OlO4?s#iO5>+Vb<%kS6Ck$18;\",I`^W"'B?#S=3C&@Dan1CKjc +$fJQ(+[lfKCo-*q%,hF#+H[+P2?_BO"*!3)?s3nVkRk&d$/r6WO%;,0&/enB&+E[45f""Ned2mu#9ZqW0S9T13sW#2#Co5U0S0JU-jT8o#iM?bEAS8i3=2qZ[_ci!O[L!?8/2_2!$[X?O3S@-=TK+?!9&DC,?,D_Bbg/T(@cA\0m*KU0H)0>)3KIdDo`nqLdCAi5!d"&+UoTW#CoAa0KKL0Q4UmC)X96?a"[4(Pau:[W_pSP0uY,Hi:eZcM9K4rjLDs=o_NR`*V&(=/'=R1h",==*lSX,m[deUi_]#8*KgFG.fR1\"X()[+R1Mln^Se')'Q:++n=(%&cV8HaW7,61a+.i0]`o;3?tgm,P",G1.;9F0dNEI,iKOc+i>U93;(6%rrL=SP%>*.7jbNY-Lu.( ++d"-gM'33')=i:`P(b8;G71'"-:%>_146:r.\A6L*-.](@5ofg:F`Z,.e9hH0YR`8U^XJr*E']qAb;\X#T3-W$NP`.0Q[M^fbP`[?S]^1bRckRE=ah^"*2pEnrYI(e:&$8Y`Y(g!AuQ?aX32$0_0#aEtf&s(_r5T09:]K!Rif5O;25p%WY;MEpk^r3@?N/&7\ZjP<1UB8Mmac +0u6sf_*'Ys3#^7O+/7bhTf4lKZih#F&V2Gk.iTY*q_tj02o=euMhrCiqCiN'3:i7+$0^c;G4!^#g26('F/:#jY,kR"3qKU<1(>F+[6!^,40uaH1TJqTIlqJ\3V/o`'@AsW8AmM9nm4>.Q6nc18i]0_%=8E(R21Us&rq^]!37MMO$E7uF"oG_nR?]lt^Z`Y+/\HTdh5np(f0JF'&a?Ggn9N9D61-ZP*=u2$3'D16>JZhgi^sjM(:@nf(2"WQ0p.J>6:\02u +:D5R[*SPgriUYU#qW*Gs`0!o4%\P?4$/-PS6P2*emN.ONLj#8CJW25O@(Q6'o%-"4[t+OgJc\QJNK0(eQBZM:]2ZS-i;>kDA@d*?$kT?+&EiG%#!+BX5$'B!Rh'[W,'MWkT9;7+PVbokRFtDcJVQ]s*2R@4A01.XDZ=>?qp=2bl&HP22+h#\2FF4j3;/Wha=S*jCdWQK9'g"3P'@bA9pB>2E.:)4!'LA]1PbT,Eq"h$8+MhD=f'c[JGB0s=)3$d.asS;F-645bF8%%O((Xgr[<+?%.lJBqp*!0e&Pcc(QiD)UES3dH]fOd=2en*aaCO\Ha4`?lgPQHflZs_,9\@KeZ>M;]m\J:=Z=O_Ep_.A14_)idWJb=15@=L=Vt6#hR$*l"%"\'nS#f.%#M5=1]+5'5,)\7H9H;DV;0 +Fd!>Yf3l=XSH>%NG(;Ci(klJoFs".]GKYtj!qBgqKfM)K*7rMMPGnU24eBXLi#pVgiJbDiruME&j(GLXA%08=WX)B_U$!QQ=+^7rDEO8/*EfC=e-*\pSp&bU?6&n)tD#@8!&O>X^(pdQ&7.lpTb=*JNiGU[rrM[pYU=*>g@C;^[o +8WjgL&XXk&2`46#rriFo#(T^d,L3RL!8bZ[P-[#0L^7bFl20XZrFblB.M"m*h=I-KWRo&mPMADnC=-JQj$].37h2Uh4:nDNZ$'*H-j9uNLm\!@'udC3;J#;r@aT-9j%^k$Q(t@?_FffOSKbtW]^[!s'+.GLJtG` +TRBma\,u?TH!%YP_#pHTO.SF#X2.B'3ZD2pl3.m')f+%S\N:,f-jAd+Y+)^6"2WI9n?$H2Br2ZiXX^K%Y1IC'[R/UBqm1/U/d71qD"1k2DdI!UU?qnpCVs5UF=br/%\(G!A.bB9ejIi\bf8=gIVB#;A!=$]&9?q0bOXHdC'rlK^(HS&qgOVaf_*N]_g$-UZk03 +ah8YL^%_I[)[jA!l+Gt`^A(-56g0V>ruZ9#_rr$=NFh6PbXN4+kN'cX9&=EF>n`2?,DlgJ*:@5EH&`qMP63;]=`)DjAb\Pb@CH7L[!4d)f=FjioTd!L2]jdOs\W]b^\*IlZ3cc-mC +PYou^>0g6?NH[:G4a^Jf,dF>*5MASZ`Dc$SVME0SeYJtRTej`M;(MtD8/An_au.d,S?^!iQc*eUfa7,!;Ur"FHeu7R$o6?h4gg_N`Ckc-6@a4:3Ji[sEMttZ1pYaUgqdbgNJt(:1LR]NRnFK4+`0Q7-/P>BMumi24#]"Q!XDZ1Fk7?bddOTZll$pNc^FTugl6Ij +3RIaBW4ll=Zl?c$%paFq*57!"]hQN?QTk2&eL6FA4]dJ"Q.=\t*5/?*]rWs%Z0K'*lMe'S5.0^$f>83_NOG$O5.L!o^$C-Fm/GBrg`A0kf6j0bmJ<7mhV7H>UVX\3mf)_r?C\#ZoC'5\m[i065,CI6[k1R>$/X*p2.m%8V3CK^r1:W+HNu8+&b%t^RUMgj8QKlJ-;qA*fkN:P4hlY+:kCb%LE;k6(]iu<%]$tL;"iBGa(rP +'oPN?:MA6q3?=/Nj:W='':IA<:E,lgA5jEdnqBE&dH$MV7,EhrVc2jq)O4'O(op*cFaDP4W?JCqlkUMaL,!2D=mZ`EKs'*G[p/8:)jS_5DhhWe&?Dr$q0]R,lrD^"Es3L"iPO6;<\G>M`g604>V.TO>K:=H(t5p2BgQZLo/[l.:J"3D +A@3>H<-J?VC?rb6*>Zs6dG%*K)kEkP.tOk^1/bR$%sQ"4)0lj#?S7r2k70NmDCJM`3h[)]*A#&T\Jm9tqcJs;O.>9lFgVm)GH\oB?2N]rJcE1uUe/nmbqI\tBP[VhO981P]d\NO!sW^3prnZ#A-A)9n:S^i_+_Y4$QW'^*=YATj-7A*YbN%%`,(m!&#A:q;\63H6s?KQ$>GD9 +2B]XH_hKKpEYc]8=RdIWC[0W&aDrPa+eOocP9ie@A=.eenq4\LUJA`@o\g]1trokjdTZ\(4jYC.>eMp'u%cEA7EACNOn_Z/P9^W*eD#Ip=Or]:aY"A]1We^KGENU0gZoGG[C&B#alQ3j<\5$7pZ9&;l%t+`.jXI+EPhQAfDAS[M21tiU91P'Lc"a>'*4-H9uo;iXSb*f,B-qbGp +&OsrZ>pPB^1u91FBR2"`UF*=5.raOKSrWoDg)bgEC2.k`67ilEIB+Srg$Pn;QUY8*8DZ"_aS./'!6spA6(_\p"KXVilO`Xb@&,mEas&GAgPY9I0HR3>1!e`Nea/mg)Td/qJi@/7L*E,&tPlLG'(36G)lp" +jb4Tj^')L.VM"&ibSEB1*$ffW_0b?ZhLmbAi\;a-V.mHM6XaJ,kB*A[hZR![%;>>`P`HF\':28CQeNm"hh7hrrb*(j/T!>230*i"kPP9Dns7^*!NSr@@ACU`i;TBJ;JWCW[Pjrdf+R[VJd$_46$CQPMp*#Sn5]g_-RMh4H5(6KaJFj::p>nZH6b*4;n(qd!o]9C0C&WRK4o3q +9%]noLo_-)p(UMlj)&7YOarJ"r2IR*9870?,D$c*Y_.=%F@:i2+[poOKTo\,6OGJ3Lfj>,J7sms[0[mP:rks1m69jLBb"*UY`:t[9[=-8\3\@M_"to(@G%E]V4\#9;36;@('1s9W5R^0Y*!Com4ji1;d_$o*"l:#!Yc=TUss=1VEsgfPn**4[Cq?A,a\nMX`%=;qCf>TPIN:pNc/LfL,/b>D0A]?J:41.s_?2)(!n6<:$_`cTss@;[c]pfs`UJe".:bd7lucjH[K.h]1qYg.gZ$>5MP&TcMH3@K_.`Ou(h%$4gk<:1`>'#InHhC=ZoY(E%'*f]\8m63OT9Ok=Y*Agd6!TVlMkg:oS-h;8uEFDCC^r)t1eU8*M +fh,9WngS%jQT9l70VtU%-*L$Ad('rYb)n*7cYc:<=`Qua,st+1MPCe#b_T-fk[e\4;'^EZqkZ]YPt^=Q&F!Gm+e:HjQ$0>X8g6sj_b?tF3j@0B!ErqOCP#QjeP.KR>>sp0Xp&QR=*"+:dcG^N("BH^6W#_%jOe3Y/T!$]\RK1H*h4siI+G1s=t/_["BJPJQA7SY6"QOW"Br4\ +27b&6'^>ipNlW3^r9oW$m'W-1NmZ>?:'ge:$g4r]7!Gfq$$-586JC'b*4OsVBobB-<,R\+qi9!Si*d#,\_lVb?<>,l^@W\mDJ^C%!d/("d+.K6I*X9!ij'bYD.''7;_EmUjK_R0(pVp$(8"7,JYR2,_4 +@59KC0[XmTA1nCjHn\U&")]h&^rX"eQ7d/T_@>/+f+H1FE3+KuJXBPd3e2I4_nJ2d#T.PXj:j$u'qV$(mZWf!eWNrK8I\eKjj+5cY_GVG`T1ph*nt3qXmibb6?b(eS%),CW'`_@^G@V7kAUs'10s'j0rui-*,\eI-DS17/C6A\L44IsiEnf#.[P\NjYg'5AclWHThcNEjJVAK +MQC7D5u:Gl5=7u8<0Sh0jT:4:og8M])t/5/b#cKWkq9`=@A(#/X2%ggQrZ5\!m<^UmrkfouPt,XZ,Ht)D+J0s'_&l;Ue;@P*=B?>,j\dsp:o,6jg>/D;)pg4&\Zn,(@6FgCd#-/8^+,5"=V"T"&f),`gW$@>N^8()]a`p'$Q;f%Jfe9[H[;>i6YFR;\(nF'PqI<2JkY-6IS(Lufs@BoN4dFq,h=kMOYJp!+0gj>B/m[_tAGCJl54-s(1 +7u"s9cILiCc[T%`j26"j\`-X(m1Qhe_0GtOr6Cs77==/J1SOE=`a>3;6N>AUDU8g*'#J"./'*$Z)BSiT_ED?gSX7VO&.r7"94ARh+JGLsC;4*LHPF*4e.el[hm&`9\#`@J;R!O3W;2//=,/FFnXm9sbmn.P[UJ^WrV+S'Ie2t=XfHHTn(H@?A;'EJKSB_5OArdL"Tr,j4;lu@ +$-921s*j.X5M&:&M%cVk"/D9Z]K!l#"._u'f[#_bK2-'6$c!j"m(=C+CQ%6pWb5Jt#re"AqkrkJ8r5R[ZZ4/Kju0#1Fa74_@aA-P<+$q(dk6Ln/GA*uDe;+6mB5h&t$A.LB\'fol%7I4AMr*ViYVT%;"6"&qCFBaQ?DoPm"`bAj$ +GWEAT`.m=9]P>'u9BMYc(5$TAZ,1cGZ(8$upu8'r.4u`1[aW\3.OM9KD`> +5NGQPCek\>@&6hc8$l4;4JYSA]Y?!%`E\TjS>Vi-=?^P(8h=Ml[&Z8V>d)q)7F\$Rr3/g&Ttq.6_-7P6Uj`AkD9H1m95M(1I(2h.\P%i0L-Sa3]I8E2&51\b,eG-fPT,kb7foVV9J"(T4N'oe`CsKO9PhaCI)o!?a\85Gb?OFu\qZ7`'nl5)2'`[C:lVt%(D0k2b3NOB*7P`8 +kQ/W']#2dI=^_B%fh*s/8&5*od4L&/h%3PtKiF($(l#pN-kBu(:+GIqgss+e9"JDIc=p],?m/6[V^si,`^Hdifu/T53=\H>:'Bf3g^V@nK#f1@4$8f4+^mJAFU)V$JS>9XC,a87ou*r%`4VXroU`W6T:^M(P)QXY`:'O=V,/06:b8Qd*3;CVWQsl$cQho$XT64T"ON*9T<#E4 +g_A*5%8bjj:rNdRMnVhEbY]An()2Ha6tt%#'iA)t2q6$6ZeGU+(!$17bk'&jO@R^?'nGZm(fRn**9N"/@0/S9:nnNJ8Q3_;7_OJ0OJLYEdmsK[.1^)?d]D?QBSAdoj$%bu7PNjnHW&$i@8a$PdPCcUV)/r%[*lH`dqV&Th$-GF!74s":D?mW4K'257*0.A]EgZ!q%^4):9a)S +&>Ygfe=Fq/Thj>fcft7%laP>!VpI:n<3-8GA5tn.3_:n.;p5]tKh57no2Q3*:p^b[ohs:nue!C52_&@J.pK?'nca".^[O6M2bBj%Zsj^B"]RV]<)#e7V+)>n7iB!@'`ohe]5H,+Qc=]tVog:^3N@S-;7di^Pl0iM +E@nN$G?2V=f$Lp-i:b:0%0fP8-rCT./N\a'NQ@L\Jb?W)]ibg#G;%Y%L&k]b28EDs7b5+Kf$/c$bJm#R\5L!I=rY:['^O99\C`BcO^#)HSK\+q"T[)u4ih:tAVgrZME?docc(g='o^eqNJH=jf_(?^IFq$&JlNct>]g'PQ,VE.Q!>!b=`*".h3]\*R9gVt?7k2+m@7A9=P%,Z +hIt`D]/\LM;VMblDccq#qi?93]Bt%rK"\e\8=n,i`R'[BdCXPLh*'7n8:FiJ<7pS9?&fk4^#)c6 +*5+NE]/AAA?'@C):gdeKiSGaaA`0G.iSmktibg,*`T45ISR0Sk%GZH^+ALk<,N7pgg+Fl7pu:/be-I!FQ4[t@*ND3.i=T477h)H/`NG>/YMqNrhhW-,R($G$m9dG**M?"VlJGt9#.u)JOHG6)-(W,#$F&q$Prg=&TSDBE(#XcM@$sg7i(mbC9hMiH4"_!%"s;W[b#@DT3cTjD +q&9`))S1'ZEI +"QkI&]2?KnG@$D?5T5l>@25]m>JVY3N])49h9tO_Q">\Q)1Gb'IMh3_UZf^dBs(oIjUUCY]4o0nl.&==k*o!ZT0'c\l0]Dp*gnLJ!U<Xs30=W'C84W2dd*$#_J%Y+iP-@0B'JCC[!'*f^ss]2#%,ClB%naPH)D7ql;`D6B23p8H+4cQA1hmI&k7[\-IJd(>=rm(Ls"g^?faWlL*G'C::sg(%9e7mboX/R8_R"C2N+sjh:7#4Q10T.p&ji\?jC,juQQp +[3%!kf"ppi'Cu._=PfV:J:2I1%!i"4.@=)q%]2#3YI'915QR:QoFL^2!-o3LAI0qa"[i3>a>s0!bVb$^Bfgk$&CXALf6)1GkTBh%(gPIgMfLMl2"Q_&Su6ok?1aRDcDM> +i!+$U8*8hTi),dT)"F4Yo4Kj@`uKb%qp=JqD+P'[$b<^>&;8)E7JBoD(F;Za-MLb=Edp'PY<$i&H$>kBn`LkcY8_Z!SF[8;DPo=7[7>HErp!!&l=bnl/XN:6`Qst@(IO_?Q"$m(pn"b+-q=YC3nJf'fd/"bb*;3-LCPOMTH-c^t@6T0UF)QVQhU*'%dWX4_m6;&'nHE(m[p"YP&5XSJGd[9),S0'[`:nG%]UiuTKm6r^GON:nq4.:\@.PT?r"8dQ,bb,p^a3(#Eqb'qQD+3EIrfPAr3+:h-\gte(9C;fp^=[DTi9C$&Vupg +Gf^;;hO=6*UpPoS&>AXl_'p*M2@u\%H!^X7Z#Q(TBF*KGaAe,-8"5nYcbV?S\iO[W1CHgW6'cc0BJdpgTm'o^S.+eFHAki:rB3miTkB;KZ8pL:EDQ\W%_+8L6PCu'85?C:NSg13WfcOQZuIbsB,,Y8VQIt%I)A3E+i,?u?Un-ZaV5u:f(#/SZ6+U+LBS1+f^d(D!46VuL$oW+&n5nLt3*(^d;8gI*T/WX,eogLJ&pD:hC'*t,I +B[gf46cp*[*N7?GJKW$3*/LK4dQEVS/-1\.[#9iIDNB_hS,T\,`@CGlb+Q'>91EbC2MiLh(hGJ;iagF^_o:]i/V:qMi8_jdXQ_YZ1VCI7$o?\o8PdT?(BVA3>mT.4jZO1FPI+S&M$S3MQMiT%RuWB@:]$TJKll,*>uT4r6HG'@EALM)ki'uic-=Tu0qT!se=adbqHZ$D&!U]& +^@/u3LRpC$ar*#[2CdcdE!K +`Yn4^kFeYb`c1ZN.<(cPc,r4drD@geel8(La^Sc[p,g%rH(rPp$*ObODk'b=N%]OnH:A.L?Z;'S%eF*me>T6%I9M`!Pn20*Fil(S2s4OnHe:e`USO_MoN0D%hS8kW +@!q`Th=OKfdrBHiUcc9l2ePH$VqeM7eepCt7aJ>ejpuFam\Oq@l0u>tO3-L`UVG1GY3'PEU:bA[L6<#GSDBut^63[`Rc!#(Z$)mi_EVSd-QjXf?OfZe'd>u6KM2hG#&SaaG0Y,"\CZ>JD@@R?[g(cB*-B6Z4i.nfh-hQTKZH=&_O+=1TM-qkd(U>a(hF,uZIO\fiYt7-XU\dh +4bqCe+>#R#;IU%sL2dtS7$s5Piabc?d68s;[IFLJF/TJNZ6>o-E>I#F+V/?ks1<=_&DY3$6N\Mh-K-0fb%t[2`EAZf?qc'eP]_iE2<,#(g]c`rjH%]NbFI);#:(P2+#)6Y";qo'hWScoK/uOE0_$FJ0hrdq?2#7fI4!+,6'EZfpb.1I.+<,PPf'M#8-^9RKS"(tTRl\[8'i:* +Eh\br:/rPVP7LKc%"ZdB-5hikVE9_UB)#=a\Hr[hYXU5=096>fG>`O^e`&PV]9]:F,WN:\q.5PWh"OH*gSi"VjbL:5hjZQo/R;r;t1g7F6^>pV5P5FV_qF[(VNa?7e\8O:.O>b.]lgL.hRlj>qd*_Xg7A#DTjlt-Z4CYJS'fh@ri4p:s"0.qZWdMNO(aHW6\_muk[;H=TSek@P<\Kr7*rrliU7q_<=;g!*jm$'$[<>qG\V.-O'ZDMR[es>p<-Z_;5EOEqa.DSN$L<]UR^Ouh?-F%8n72j0'I*k.XP@Y\X^d^.pGD!UJtP$mU#QPa?:7`H2c&&\)[gb6OBoh1%s'$0^FVKif9^6.Js]edHb8m7\t6&!euaO4C0(B9u*TL$YVPRfImaSYpirlUmsAp]8E[Uk0)oA?!p/mJS/iBK5S9!YrgH.($BVt_n9bDqj@KPWT/&H +Hs[K_=#]O4cR7_9"SFY[cQA'(K=Y4N,`[FK;(c9-:[b`WcmEqt5+UB=5RLa0n_^Lg*mfW*4Ud/3b?]s/D= +hJdEujr]&c;1Iaqr@b>@7(QCC-G_*D]rh"RaB[%!kka>*Fhq7NWBS\4.':fK!t+,^Y-a;kK"PfV[$)EmtBI0;TU-d]EZ!47egR,>iFO0pK&(r]+@%KgY25X#Jr6[$6P4'"B;m(!kfQUDb=&A?WNm/B9-Pn-nKb[`103iEi2cA&)lfD<11p&s,#s33-P7IN&!nIh??`'( +Ak(:7@4<)"M^ZNI+#2-rTt(Af_c#AE;WfZqlRlrh0%0>E;YMi-q^umK.['rg6HT]-$K861s+*.Sk@9"lc/fphD\?a7"EX2tm1'5PY1QssY'8JB:N28q/1t*^1ZK;S%RlAff0i7g#aHC7LR4l[`\H,bj_&YV$Y!Nc,2$gjt1;c5!8/!1WBam5S^bbT#XqT&O;p.\\Rn;,%8ee$Re)O&"X%Lgh54l$O<4>MZ%-hqQ9E6Y'P[s@W-VQ>t8#.4]oZp6q'1**8-5%CpZ_9@a>:jnt6^(di`MVR5&KjiH/TaZZF)rp(//mha +:33#O;f+1)@`[(5+B3D6P]f[+dm%kl*&Af^iJg$CN&#L:Xn7rZ;SPl492sG;<>9jRPuC\J>!^ZEcnl=O^(Z'&=lH!Ei;'bLIIlcA=or^43O:/TiI+omo>jCFXkr?5)j-_\H,W +X]0H3/6-=i$%&X5((:7@]iR-2/CoMJ#a%0S)bK#7F:QgsmDoB*mMIbSFG'U.$)qZ>nSB"KFr+XAG-c?nCL&G*G1UeZ6nT$U:!9!)e=*]7a*"d[G?>N0=;J]]Bn;Wmd5JUg(ai\0VZrjB%4*&$?pfR4JQF)g#+.ak96q00_AZ>M]@S/1=BBTGRP)(96$Q[K(S<93#.qn)bu`RaLu_N, +=]9K44dWN6(V'&!4OtY$M$')sJ4!t&04hPt:j-81KdNH'dKqn:LK"bl/A-sN,8#Nm8uP^te:8@/)iVdJ2iih#kiI,TDgsOgIq-N9e=(%&XpH>=]U+9Yorgs^$V<;g<*1T2=U0MF*KZ[!DO;`4)&H8_'p4n+433VIA13MTaL=HiXKkG2YBl,J]d@.H%Cnij=\"^:'9f@]U^.5> +O^u">*l4WS"@3N005Z'\tM_7V5,$/?eVW_>.:1DYq;ETT,PDE1]mFgRrl=/\9c8]&Bb0je:Dm<]]WO>5'QdnLV9IXP3WW<2Hf; +qlk.rYe(RR>8OQ58[.d3Z+;ftoA?i7A$U5OZF_omgFi'o2*@?gZkM]14$u*a4g`s>[2W$q4%TN9@4rI9t,JM]+W`*)mcUBVn:]u]GducLekZEhn49q]XrI%oBX(OgRanc=o5D: +)s6-A\%\$I^"`.n>PF3umV\NiYWMe7gY9MJ&\o@sO?URCY/&L'p_]1JM>W9Qj42]i<`#M._>Xu`&9>oU]`>hgq>Z\n7>K,B)`Z/L.>\D'HCW>.J`uK0@>^+5YHcOoka;fiR>_gCjMoa\7aW-Md>aNR&S&sHXarI2!>c5`7X305$b8dk3>dqnH]?B!E +bT+OE>fY'YbKSbfboG3W>h@5jgWeO2c5bli>j'D&ld";ScQ)Q&>kcR7qp4'tclE58>mJ`I$dd]?d2`nJ>o1nZ)q!I`dN'R\>pn'k/(36,diC6n>rU6'44E"Me/^p+>tLhP:efA8O?"_`ZCY%<[f,\qa?$FnkHe7)'fH#Us?&.('MqHjHfc?:0?'j68 +S(ZVig)ZsB?)QDIX4lC5gE!WT?+8RZ]A)/Vg`=;f?,t`kbM:q"h&Xu#?.[o'gYL]ChAtY5?0C(8le^Idh];=G?2*6Iqqp60i#W!Y?3fD[$fKkPi>rZk?5MRl)r]WqiZ9?(?74a(/)oD=iuU#:?8po946,0^j;p\L?:X(J9B=r*jW7@^?NO^KjrS$p?>&DlCZaJlk8n^- +??bS(Hfs78kT5B??AIa9Ms0#YkoQ&Q?C0oJS*Ae%l5l_c?Dm([X6SQFlQ3Cu?FT6l]Be=gllO(2?H;E(bO"*3m2jaD?J"S9g[3kTmN1EV?K^aJlgEWumiM)h?MEo[qsWDAn/hc%?O-(m$h3$anK/G7?Pi7))tDf-nfK+I?RPE:/+VRNo,fd[?T7SK47h>ooH-Hm?Usa\9D%+; +ocI-*?WZom>P6l\p)df7Kg\p$erZC2"?g%E\li,f1ru^k4?haSmqu=M5s+*GnOB==\&IF.XiK2]64s:Mp7,j>2ZsGI)NCMrj +f^sVY+d#=VP$'W5;(7c&jc\;=^0raa9]hOA[,,d_SPJ@3g%>8p6(q-=PZfpcO\)BIl'0nE5+tiQ<9f`P[9g+@X]FbQg@]p2@Bir$QX(B>jdq_[GLG!]jC/og\(RIJ\ba`Qs;Nk&W+J9nX/*T59Z02AFc-n[U1bWc"?R8h"H4`U![QGRU%hD;5r)\opX][ +^L=D#D"a?([bl)8h/;tVh=gl"_;TA.S6e,rOic^*q4-;c5G?KhFS_P7[pQDnm<8AthY2N9iUM0jSmOFKdHU=MrLVnj^Z"_YI/]aF\)6`OrI4d=ht-jJ5VNlW!^NtH%g50P<#5a)Y]Lrm684WO$::u(0+:3%e2Ik)Yk1-k6noBG&k&u]:D?5P<*'i(Z#j=i7PU-?)Fh!=D]D8% +e9;s(Z1NMg82:m7,"T!rO!I:P<0nq'Z?2]e8huX/.S@"PL4Fd~> +EI + \ No newline at end of file diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/fonts/NOTICE.txt b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/fonts/NOTICE.txt index 1bd55b66cb..adbfd10344 100644 --- a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/fonts/NOTICE.txt +++ b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/fonts/NOTICE.txt @@ -10,3 +10,4 @@ This software uses the following test resources under the following licenses: | cmr10.pfb | SIL OFL-1.1 | LICENSE-SIL-1.1.txt | https://www.ams.org/arc/resources/amsfonts-about.html (13.09.2023) | cmr10.pfm | SIL OFL-1.1 | LICENSE-SIL-1.1.txt | https://www.ams.org/arc/resources/amsfonts-about.html (13.09.2023) | SourceHanSansHW-Regular.otf | LICENCE-SIL-1.1.txt | https://github.com/adobe-fonts/source-han-sans/releases/tag/2.004R (File: Static Language Specific OTFs, path in zip folder:OTF/japanesHW) (07.09.2023) +| glyphs.ttf, glyphs-fmt-6.ttf | MIT | Derived from https://github.com/RazrFalcon/ttf-parser/tree/337e7d1c08b06478a84c4345f4f289fc2cb9210c/tests/fonts-src diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/fonts/glyphs-fmt-6.ttf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/fonts/glyphs-fmt-6.ttf new file mode 100644 index 0000000000..941a4cd173 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/fonts/glyphs-fmt-6.ttf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/fonts/glyphs.ttf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/fonts/glyphs.ttf new file mode 100644 index 0000000000..60436aeb3c Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/fonts/glyphs.ttf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/layer/PdfLayerTest/cmp_output_layered_2.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/layer/PdfLayerTest/cmp_output_layered_2.pdf new file mode 100644 index 0000000000..92af7c8e89 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/layer/PdfLayerTest/cmp_output_layered_2.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/layer/PdfLayerTest/input_complex_layers.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/layer/PdfLayerTest/input_complex_layers.pdf new file mode 100644 index 0000000000..4dbe49cf99 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/layer/PdfLayerTest/input_complex_layers.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/xobject/GetImageBytesTest/SUP4582.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/xobject/GetImageBytesTest/SUP4582.pdf deleted file mode 100644 index 630fd83910..0000000000 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/xobject/GetImageBytesTest/SUP4582.pdf and /dev/null differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/xobject/GetImageBytesTest/separationCSWithDeviceCMYKAsAlternative.png b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/xobject/GetImageBytesTest/separationCSWithDeviceCMYKAsAlternative.png deleted file mode 100644 index 56403e86cf..0000000000 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/xobject/GetImageBytesTest/separationCSWithDeviceCMYKAsAlternative.png and /dev/null differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/xobject/GetImageBytesTest/separationCSWithDeviceRgbAsAlternative-clean.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/xobject/GetImageBytesTest/separationCSWithDeviceRgbAsAlternative-clean.pdf deleted file mode 100644 index 2421f078ab..0000000000 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/xobject/GetImageBytesTest/separationCSWithDeviceRgbAsAlternative-clean.pdf and /dev/null differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/xobject/GetImageBytesTest/testSeparationRemovedCSWithDeviceRGBAsAlternative.png b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/xobject/GetImageBytesTest/testSeparationRemovedCSWithDeviceRGBAsAlternative.png deleted file mode 100644 index dd87c48276..0000000000 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/xobject/GetImageBytesTest/testSeparationRemovedCSWithDeviceRGBAsAlternative.png and /dev/null differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/xobject/PdfImageXObjectTest/indexed1BpcImage.png b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/xobject/PdfImageXObjectTest/indexed1BpcImage.png deleted file mode 100644 index 570cfc97e5..0000000000 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/xobject/PdfImageXObjectTest/indexed1BpcImage.png and /dev/null differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/xobject/PdfImageXObjectTest/rgbWithoutSaveColorProfile.png b/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/xobject/PdfImageXObjectTest/rgbWithoutSaveColorProfile.png deleted file mode 100644 index 8fdd680eb6..0000000000 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/xobject/PdfImageXObjectTest/rgbWithoutSaveColorProfile.png and /dev/null differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/utils/PdfMergerTest/cmp_mergedResult04.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/utils/PdfMergerTest/cmp_mergedResult04.pdf index f362958bff..6bbe3fdc55 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/utils/PdfMergerTest/cmp_mergedResult04.pdf and b/itext.tests/itext.kernel.tests/resources/itext/kernel/utils/PdfMergerTest/cmp_mergedResult04.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/utils/PdfMergerTest/cmp_mergedTags.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/utils/PdfMergerTest/cmp_mergedTags.pdf new file mode 100644 index 0000000000..e0c63b3f78 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/utils/PdfMergerTest/cmp_mergedTags.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/utils/PdfMergerTest/cmp_pdfWithCycleRefInParentTag.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/utils/PdfMergerTest/cmp_pdfWithCycleRefInParentTag.pdf new file mode 100644 index 0000000000..666750776c Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/utils/PdfMergerTest/cmp_pdfWithCycleRefInParentTag.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/utils/PdfMergerTest/pdfWithCycleRefInParentTag.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/utils/PdfMergerTest/pdfWithCycleRefInParentTag.pdf new file mode 100644 index 0000000000..4f08885bc3 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/utils/PdfMergerTest/pdfWithCycleRefInParentTag.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/utils/PdfMergerTest/tagRootKidsDoc1.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/utils/PdfMergerTest/tagRootKidsDoc1.pdf new file mode 100644 index 0000000000..102a320161 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/utils/PdfMergerTest/tagRootKidsDoc1.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/utils/PdfMergerTest/tagRootKidsDoc2.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/utils/PdfMergerTest/tagRootKidsDoc2.pdf new file mode 100644 index 0000000000..a07b23bd54 Binary files /dev/null and b/itext.tests/itext.kernel.tests/resources/itext/kernel/utils/PdfMergerTest/tagRootKidsDoc2.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/utils/flatteningTest/remove_quadPoints.pdf b/itext.tests/itext.kernel.tests/resources/itext/kernel/utils/flatteningTest/remove_quadPoints.pdf deleted file mode 100644 index cbd8c63cdf..0000000000 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/utils/flatteningTest/remove_quadPoints.pdf and /dev/null differ diff --git a/itext.tests/itext.layout.tests/Properties/AssemblyInfo.cs b/itext.tests/itext.layout.tests/Properties/AssemblyInfo.cs index 1a09d3ae6f..c8e7833b29 100644 --- a/itext.tests/itext.layout.tests/Properties/AssemblyInfo.cs +++ b/itext.tests/itext.layout.tests/Properties/AssemblyInfo.cs @@ -15,9 +15,9 @@ [assembly: Guid("9ad347a8-ea5b-462b-810c-998f04471bb7")] -[assembly: AssemblyVersion("8.0.5.0")] -[assembly: AssemblyFileVersion("8.0.5.0")] -[assembly: AssemblyInformationalVersion("8.0.5")] +[assembly: AssemblyVersion("9.0.0.0")] +[assembly: AssemblyFileVersion("9.0.0.0")] +[assembly: AssemblyInformationalVersion("9.0.0")] #if !NETSTANDARD2_0 [assembly: NUnit.Framework.Timeout(600000)] diff --git a/itext.tests/itext.layout.tests/itext/layout/AlignmentTest.cs b/itext.tests/itext.layout.tests/itext/layout/AlignmentTest.cs index 2f394a9a6c..6f2c7aeeac 100644 --- a/itext.tests/itext.layout.tests/itext/layout/AlignmentTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/AlignmentTest.cs @@ -507,7 +507,7 @@ public virtual void FlexItemHorizontalAlignmentTest() { flexContainerRenderer.SetParent(documentRenderer); div.SetNextRenderer(flexContainerRenderer); Div innerDiv = new Div(); - innerDiv.SetProperty(Property.BORDER, new SolidBorder(1)); + innerDiv.SetBorder(new SolidBorder(1)); innerDiv.SetProperty(Property.WIDTH, UnitValue.CreatePointValue(50)); innerDiv.SetProperty(Property.HEIGHT, UnitValue.CreatePointValue(100)); innerDiv.SetProperty(Property.BACKGROUND, new Background(ColorConstants.GREEN)); diff --git a/itext.tests/itext.layout.tests/itext/layout/BorderTest.cs b/itext.tests/itext.layout.tests/itext/layout/BorderTest.cs index 359c76e3bc..b7cd9233c9 100644 --- a/itext.tests/itext.layout.tests/itext/layout/BorderTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/BorderTest.cs @@ -218,8 +218,8 @@ public virtual void BorderBoxTest() { doc.Add(new Paragraph(textBefore).SetMargins(25, 60, 70, 80)); Paragraph p = new Paragraph(text).SetBackgroundColor(ColorConstants.GRAY); p.SetMargins(25, 60, 70, 80); - p.SetBorderLeft(new DoubleBorder(ColorConstants.RED, 25)); p.SetBorder(new DoubleBorder(ColorConstants.BLACK, 6)); + p.SetBorderLeft(new DoubleBorder(ColorConstants.RED, 25)); doc.Add(p); doc.Add(new Paragraph(textAfter).SetBorder(new DottedBorder(ColorConstants.BLACK, 3)).SetBorderRight(new DottedBorder (ColorConstants.BLACK, 12))); diff --git a/itext.tests/itext.layout.tests/itext/layout/DefaultLayoutTest.cs b/itext.tests/itext.layout.tests/itext/layout/DefaultLayoutTest.cs index a2d440518a..23d3c442ac 100644 --- a/itext.tests/itext.layout.tests/itext/layout/DefaultLayoutTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/DefaultLayoutTest.cs @@ -24,11 +24,11 @@ You should have received a copy of the GNU Affero General Public License using System.Collections.Generic; using System.IO; using iText.Kernel.Colors; -using iText.Kernel.Events; using iText.Kernel.Font; using iText.Kernel.Geom; using iText.Kernel.Pdf; using iText.Kernel.Pdf.Canvas; +using iText.Kernel.Pdf.Event; using iText.Kernel.Pdf.Layer; using iText.Kernel.Utils; using iText.Layout.Borders; @@ -241,8 +241,8 @@ public virtual void CloseEmptyDocumentWithRemovingPageEventOnAddingPageTest() { , "diff")); } - private class ParagraphAdderHandler : iText.Kernel.Events.IEventHandler { - public virtual void HandleEvent(Event @event) { + private class ParagraphAdderHandler : AbstractPdfDocumentEventHandler { + protected override void OnAcceptedEvent(AbstractPdfDocumentEvent @event) { PdfDocumentEvent docEvent = (PdfDocumentEvent)@event; PdfPage page = docEvent.GetPage(); PdfDocument pdfDoc = ((PdfDocumentEvent)@event).GetDocument(); @@ -257,12 +257,12 @@ public virtual void HandleEvent(Event @event) { } } - private class PageRemoverHandler : iText.Kernel.Events.IEventHandler { - public virtual void HandleEvent(Event @event) { + private class PageRemoverHandler : AbstractPdfDocumentEventHandler { + protected override void OnAcceptedEvent(AbstractPdfDocumentEvent @event) { PdfDocumentEvent docEvent = (PdfDocumentEvent)@event; PdfPage page = docEvent.GetPage(); - PdfDocument pdfDoc = ((PdfDocumentEvent)@event).GetDocument(); - pdfDoc.RemovePage(1); + PdfDocument pdfDoc = @event.GetDocument(); + pdfDoc.RemovePage(page); } } } diff --git a/itext.tests/itext.layout.tests/itext/layout/FixedHeightTest.cs b/itext.tests/itext.layout.tests/itext/layout/FixedHeightTest.cs index dbd9e34773..8bf16b3963 100644 --- a/itext.tests/itext.layout.tests/itext/layout/FixedHeightTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/FixedHeightTest.cs @@ -33,10 +33,10 @@ namespace iText.Layout { [NUnit.Framework.Category("IntegrationTest")] public class FixedHeightTest : ExtendedITextTest { private static readonly String sourceFolder = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext - .CurrentContext.TestDirectory) + "/resources/itext/layout/FloatAndAlignmentTest/"; + .CurrentContext.TestDirectory) + "/resources/itext/layout/FixedHeightTest/"; private static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory - + "/test/itext/layout/FloatAndAlignmentTest/"; + + "/test/itext/layout/FixedHeightTest/"; private const String textByron = "When a man hath no freedom to fight for at home,\n" + " Let him combat for that of his neighbours;\n" + "Let him think of the glories of Greece and of Rome,\n" + " And get knocked on the head for his labours.\n" diff --git a/itext.tests/itext.layout.tests/itext/layout/HyphenateTest.cs b/itext.tests/itext.layout.tests/itext/layout/HyphenateTest.cs index fc76af163f..b47b613cea 100644 --- a/itext.tests/itext.layout.tests/itext/layout/HyphenateTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/HyphenateTest.cs @@ -22,7 +22,6 @@ You should have received a copy of the GNU Affero General Public License */ using System; using System.Collections.Generic; -using System.Linq; using System.Text; using iText.Commons.Utils; using iText.Layout.Hyphenation; @@ -30,23 +29,9 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Layout { [NUnit.Framework.Category("IntegrationTest")] - [NUnit.Framework.TestFixtureSource("HyphenationPropertiesTestFixtureData")] public class HyphenateTest : ExtendedITextTest { - private readonly String lang; - - private readonly String testWord; - private IList errors = new List(); - public HyphenateTest(String testName, String lang, String testWord) { - this.lang = lang; - this.testWord = testWord; - } - - public HyphenateTest(String[] array) - : this(array[0], array[1], array[2]) { - } - public static IEnumerable HyphenationProperties() { return JavaUtil.ArraysAsList(new Object[][] { new Object[] { "African", "af", "country" }, new Object[] { "Assamese", "as", "\u09A8\u09AE\u09B8\u09CD\u0995\u09BE\u09F0" }, new Object[] { "Bulgarian", "bg", "\u0417\u0434\u0440\u0430\u0432\u0435\u0439" @@ -90,12 +75,8 @@ public static IEnumerable HyphenationProperties() { }, new Object[] { "Chinese Latin", "zh_Latn", "country" } }); } - public static ICollection HyphenationPropertiesTestFixtureData() { - return HyphenationProperties().Select(array => new NUnit.Framework.TestFixtureData(array)).ToList(); - } - - [NUnit.Framework.Test] - public virtual void RunTest() { + [NUnit.Framework.TestCaseSource("HyphenationProperties")] + public virtual void RunTest(String name, String lang, String testWord) { errors.Clear(); TryHyphenate(lang, testWord); NUnit.Framework.Assert.IsTrue(errors.IsEmpty(), BuildReport()); diff --git a/itext.tests/itext.layout.tests/itext/layout/LayoutTaggingPdf2Test.cs b/itext.tests/itext.layout.tests/itext/layout/LayoutTaggingPdf2Test.cs index d9a21f648c..1580383842 100644 --- a/itext.tests/itext.layout.tests/itext/layout/LayoutTaggingPdf2Test.cs +++ b/itext.tests/itext.layout.tests/itext/layout/LayoutTaggingPdf2Test.cs @@ -592,7 +592,7 @@ private void AddContentToDocInCustomNs(PdfDocument pdfDocument, PdfNamespace def if (defaultNamespace == null) { Text i = new Text("italic text"); i.GetAccessibilityProperties().SetRole("I"); - Paragraph pi = new Paragraph(i.SetItalic()); + Paragraph pi = new Paragraph(i.SimulateItalic()); document.Add(pi); } } diff --git a/itext.tests/itext.layout.tests/itext/layout/LayoutTaggingTest.cs b/itext.tests/itext.layout.tests/itext/layout/LayoutTaggingTest.cs index 5235d7dcc3..f732e5361c 100644 --- a/itext.tests/itext.layout.tests/itext/layout/LayoutTaggingTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/LayoutTaggingTest.cs @@ -997,7 +997,7 @@ private IBlockElement CreateTable(bool useCaption) { Div div = new Div(); div.GetAccessibilityProperties().SetRole(StandardRoles.TABLE); Paragraph p = new Paragraph("Caption").SetNeutralRole(); - p.SetTextAlignment(TextAlignment.CENTER).SetBold(); + p.SetTextAlignment(TextAlignment.CENTER).SimulateBold(); Div caption = new Div().Add(p); caption.GetAccessibilityProperties().SetRole(StandardRoles.CAPTION); div.Add(caption); diff --git a/itext.tests/itext.layout.tests/itext/layout/ListAlignmentDirectionTest.cs b/itext.tests/itext.layout.tests/itext/layout/ListAlignmentDirectionTest.cs index e86ec25fd6..14513d4924 100644 --- a/itext.tests/itext.layout.tests/itext/layout/ListAlignmentDirectionTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/ListAlignmentDirectionTest.cs @@ -23,7 +23,6 @@ You should have received a copy of the GNU Affero General Public License using System; using System.Collections.Generic; using System.IO; -using System.Linq; using iText.Commons.Utils; using iText.IO.Util; using iText.Kernel.Colors; @@ -36,7 +35,6 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Layout { [NUnit.Framework.Category("IntegrationTest")] - [NUnit.Framework.TestFixtureSource("AlignItemsAndJustifyContentPropertiesTestFixtureData")] public class ListAlignmentDirectionTest : ExtendedITextTest { public static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext .CurrentContext.TestDirectory) + "/resources/itext/layout/ListAlignmentDirectionTest/"; @@ -52,31 +50,11 @@ public class ListAlignmentDirectionTest : ExtendedITextTest { + "
  • Usual line
  • " + "
  • Specific line
  • " + ""; - private TextAlignment? itemTextAlignment; - - private BaseDirection? itemBaseDirection; - - private TextAlignment? listTextAlignment; - - private BaseDirection? listBaseDirection; - [NUnit.Framework.OneTimeSetUp] public static void BeforeClass() { CreateOrClearDestinationFolder(DESTINATION_FOLDER); } - public ListAlignmentDirectionTest(Object itemTextAlignment, Object itemBaseDirection, Object listTextAlignment - , Object listBaseDirection) { - this.itemTextAlignment = (TextAlignment?)itemTextAlignment; - this.itemBaseDirection = (BaseDirection?)itemBaseDirection; - this.listTextAlignment = (TextAlignment?)listTextAlignment; - this.listBaseDirection = (BaseDirection?)listBaseDirection; - } - - public ListAlignmentDirectionTest(Object[] array) - : this(array[0], array[1], array[2], array[3]) { - } - public static IEnumerable AlignItemsAndJustifyContentProperties() { TextAlignment?[] alignmentTestValues = new TextAlignment?[] { TextAlignment.LEFT, TextAlignment.CENTER, TextAlignment .RIGHT, TextAlignment.JUSTIFIED, TextAlignment.JUSTIFIED_ALL }; @@ -95,18 +73,14 @@ public static IEnumerable AlignItemsAndJustifyContentProperties() { return objectList; } - public static ICollection AlignItemsAndJustifyContentPropertiesTestFixtureData - () { - return AlignItemsAndJustifyContentProperties().Select(array => new NUnit.Framework.TestFixtureData(array)).ToList(); - } - - [NUnit.Framework.Test] + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] [LogMessage(iText.IO.Logs.IoLogMessageConstant.TYPOGRAPHY_NOT_FOUND, Count = 8)] - public virtual void AlignmentDirectionTest() { + public virtual void AlignmentDirectionTest(TextAlignment? itemTextAlignment, BaseDirection? itemBaseDirection + , TextAlignment? listTextAlignment, BaseDirection? listBaseDirection) { // TODO DEVSIX-5727 direction of the first list-item should define the symbol indent's side. Once the issue // is fixed, the corresponding cmps should be updated. // Create an HTML for this test - CreateHtml(); + CreateHtml(itemTextAlignment, itemBaseDirection, listTextAlignment, listBaseDirection); String fileName = MessageFormatUtil.Format(RESULTANT_FILE_NAME_PATTERN, FormatTextAlignment(itemTextAlignment ), FormatBaseDirection(itemBaseDirection), FormatTextAlignment(listTextAlignment), FormatBaseDirection (listBaseDirection)); @@ -145,7 +119,8 @@ private static List CreateTestList(Style secondItemStyle) { return list; } - private void CreateHtml() { + private void CreateHtml(TextAlignment? itemTextAlignment, BaseDirection? itemBaseDirection, TextAlignment? + listTextAlignment, BaseDirection? listBaseDirection) { String fileName = MessageFormatUtil.Format(RESULTANT_FILE_NAME_PATTERN, FormatTextAlignment(itemTextAlignment ), FormatBaseDirection(itemBaseDirection), FormatTextAlignment(listTextAlignment), FormatBaseDirection (listBaseDirection)); diff --git a/itext.tests/itext.layout.tests/itext/layout/ListItemPositionAlignmentTest.cs b/itext.tests/itext.layout.tests/itext/layout/ListItemPositionAlignmentTest.cs index ef93a3b5c1..9d9304075c 100644 --- a/itext.tests/itext.layout.tests/itext/layout/ListItemPositionAlignmentTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/ListItemPositionAlignmentTest.cs @@ -23,7 +23,6 @@ You should have received a copy of the GNU Affero General Public License using System; using System.Collections.Generic; using System.IO; -using System.Linq; using iText.Commons.Utils; using iText.IO.Util; using iText.Kernel.Colors; @@ -36,7 +35,6 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Layout { [NUnit.Framework.Category("IntegrationTest")] - [NUnit.Framework.TestFixtureSource("BaseDirectionAndSymbolAlignmentPropertiesTestFixtureData")] public class ListItemPositionAlignmentTest : ExtendedITextTest { public static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext .CurrentContext.TestDirectory) + "/resources/itext/layout/ListItemPositionAlignmentTest/"; @@ -53,34 +51,11 @@ public class ListItemPositionAlignmentTest : ExtendedITextTest { + "
  • Specific item
  • " + ""; - private BaseDirection? listBaseDirection; - - private BaseDirection? listItemBaseDirection; - - private ListSymbolAlignment listSymbolAlignment; - - private ListSymbolPosition listSymbolPosition; - - private int? comparisonPdfId; - [NUnit.Framework.OneTimeSetUp] public static void BeforeClass() { CreateOrClearDestinationFolder(DESTINATION_FOLDER); } - public ListItemPositionAlignmentTest(Object listBaseDirection, Object listItemBaseDirection, Object listSymbolAlignment - , Object listSymbolPosition, Object comparisonPdfId) { - this.listBaseDirection = (BaseDirection?)listBaseDirection; - this.listItemBaseDirection = (BaseDirection?)listItemBaseDirection; - this.listSymbolAlignment = (ListSymbolAlignment)listSymbolAlignment; - this.listSymbolPosition = (ListSymbolPosition)listSymbolPosition; - this.comparisonPdfId = (int?)comparisonPdfId; - } - - public ListItemPositionAlignmentTest(Object[] array) - : this(array[0], array[1], array[2], array[3], array[4]) { - } - public static IEnumerable BaseDirectionAndSymbolAlignmentProperties() { BaseDirection?[] directionTestValues = new BaseDirection?[] { BaseDirection.LEFT_TO_RIGHT, BaseDirection.RIGHT_TO_LEFT }; @@ -103,16 +78,13 @@ public static IEnumerable BaseDirectionAndSymbolAlignmentProperties() return objectList; } - public static ICollection BaseDirectionAndSymbolAlignmentPropertiesTestFixtureData - () { - return BaseDirectionAndSymbolAlignmentProperties().Select(array => new NUnit.Framework.TestFixtureData(array)).ToList(); - } - - [NUnit.Framework.Test] + [NUnit.Framework.TestCaseSource("BaseDirectionAndSymbolAlignmentProperties")] [LogMessage(iText.IO.Logs.IoLogMessageConstant.TYPOGRAPHY_NOT_FOUND, Count = 8)] - public virtual void DefaultListIemPositionAlignmentTest() { + public virtual void DefaultListIemPositionAlignmentTest(BaseDirection? listBaseDirection, BaseDirection? listItemBaseDirection + , ListSymbolAlignment listSymbolAlignment, ListSymbolPosition listSymbolPosition, int? comparisonPdfId + ) { // Create an HTML for this test - CreateHtml(); + CreateHtml(listBaseDirection, listItemBaseDirection, listSymbolAlignment, listSymbolPosition); String fileName = MessageFormatUtil.Format(RESULTANT_FILE_NAME_PATTERN, FormatSymbolPosition(listSymbolPosition ), FormatSymbolAlignment(listSymbolAlignment), FormatBaseDirection(listItemBaseDirection), FormatBaseDirection (listBaseDirection)); @@ -120,7 +92,8 @@ public virtual void DefaultListIemPositionAlignmentTest() { String cmpFileName = SOURCE_FOLDER + "cmp_defaultListItemTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - List list = CreateTestList(); + List list = CreateTestList(listBaseDirection, listItemBaseDirection, listSymbolAlignment, listSymbolPosition + ); document.Add(list); document.Close(); System.Console.Out.WriteLine("HTML: " + UrlUtil.GetNormalizedFileUriString(DESTINATION_FOLDER + fileName + @@ -129,7 +102,8 @@ public virtual void DefaultListIemPositionAlignmentTest() { , "diff")); } - private List CreateTestList() { + private List CreateTestList(BaseDirection? listBaseDirection, BaseDirection? listItemBaseDirection, ListSymbolAlignment + listSymbolAlignment, ListSymbolPosition listSymbolPosition) { List list = new List(); list.SetSymbolIndent(20); list.SetListSymbol("\u2022"); @@ -149,7 +123,8 @@ private List CreateTestList() { return list; } - private void CreateHtml() { + private void CreateHtml(BaseDirection? listBaseDirection, BaseDirection? listItemBaseDirection, ListSymbolAlignment + listSymbolAlignment, ListSymbolPosition listSymbolPosition) { String fileName = MessageFormatUtil.Format(RESULTANT_FILE_NAME_PATTERN, FormatSymbolPosition(listSymbolPosition ), FormatSymbolAlignment(listSymbolAlignment), FormatBaseDirection(listItemBaseDirection), FormatBaseDirection (listBaseDirection)); diff --git a/itext.tests/itext.layout.tests/itext/layout/LocationTextExtractionStrategyTest.cs b/itext.tests/itext.layout.tests/itext/layout/LocationTextExtractionStrategyTest.cs index 2e7ad79cb8..92c3e10178 100644 --- a/itext.tests/itext.layout.tests/itext/layout/LocationTextExtractionStrategyTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/LocationTextExtractionStrategyTest.cs @@ -62,7 +62,7 @@ public virtual void TestXPosition() { NUnit.Framework.Assert.AreEqual("A AA B BB C CC D DD", text); } - // Assert.assertEquals("A\tAA\tB\tBB\tC\tCC\tD\tDD", text); + // Assertions.assertEquals("A\tAA\tB\tBB\tC\tCC\tD\tDD", text); [NUnit.Framework.Test] public virtual void TestRotatedPage() { byte[] bytes = CreateSimplePdf(new Rectangle(792, 612), "A\nB\nC\nD"); diff --git a/itext.tests/itext.layout.tests/itext/layout/PdfUA2AnnotationsTest.cs b/itext.tests/itext.layout.tests/itext/layout/PdfUA2AnnotationsTest.cs index 4dedd6cc2c..6477523093 100644 --- a/itext.tests/itext.layout.tests/itext/layout/PdfUA2AnnotationsTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/PdfUA2AnnotationsTest.cs @@ -153,7 +153,7 @@ public virtual void PdfUA2RubberStampAnnotationsTest() { [NUnit.Framework.Test] public virtual void PdfUA2RubberStampNoContentsAnnotationsTest() { - String outFile = DESTINATION_FOLDER + "pdfuaRubberstampAnnotationTest.pdf"; + String outFile = DESTINATION_FOLDER + "pdfuaRubberstampNoContentAnnotationTest.pdf"; using (PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFile, new WriterProperties().SetPdfVersion (PdfVersion.PDF_2_0)))) { CreateSimplePdfUA2Document(pdfDocument); diff --git a/itext.tests/itext.layout.tests/itext/layout/PdfUA2Test.cs b/itext.tests/itext.layout.tests/itext/layout/PdfUA2Test.cs index 88489d939f..236ef7354f 100644 --- a/itext.tests/itext.layout.tests/itext/layout/PdfUA2Test.cs +++ b/itext.tests/itext.layout.tests/itext/layout/PdfUA2Test.cs @@ -72,7 +72,7 @@ public virtual void CheckXmpMetadataTest() { PdfFont font = PdfFontFactory.CreateFont(FONT_FOLDER + "FreeSans.ttf", "WinAnsi", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); Paragraph paragraph = new Paragraph("Hello PdfUA2").SetFont(font); - byte[] byteMetaData = pdfDocument.GetXmpMetadata(); + byte[] byteMetaData = pdfDocument.GetXmpMetadataBytes(); documentMetaData = iText.Commons.Utils.JavaUtil.GetStringForBytes(byteMetaData); document.Add(paragraph); } diff --git a/itext.tests/itext.layout.tests/itext/layout/RotationTest.cs b/itext.tests/itext.layout.tests/itext/layout/RotationTest.cs index ca5c9dbb56..123ed88e62 100644 --- a/itext.tests/itext.layout.tests/itext/layout/RotationTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/RotationTest.cs @@ -21,12 +21,15 @@ You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ using System; +using iText.IO.Font.Constants; using iText.IO.Image; using iText.IO.Util; using iText.Kernel.Colors; +using iText.Kernel.Font; using iText.Kernel.Geom; using iText.Kernel.Pdf; using iText.Kernel.Pdf.Canvas; +using iText.Kernel.Pdf.Extgstate; using iText.Kernel.Utils; using iText.Layout.Borders; using iText.Layout.Element; @@ -38,10 +41,10 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Layout { [NUnit.Framework.Category("IntegrationTest")] public class RotationTest : ExtendedITextTest { - public static readonly String sourceFolder = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + public static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext .CurrentContext.TestDirectory) + "/resources/itext/layout/RotationTest/"; - public static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory + public static readonly String DESTINATION_FOLDER = NUnit.Framework.TestContext.CurrentContext.TestDirectory + "/test/itext/layout/RotationTest/"; public const String cmpPrefix = "cmp_"; @@ -62,13 +65,13 @@ public class RotationTest : ExtendedITextTest { [NUnit.Framework.OneTimeSetUp] public static void BeforeClass() { - CreateOrClearDestinationFolder(destinationFolder); + CreateOrClearDestinationFolder(DESTINATION_FOLDER); } [NUnit.Framework.Test] public virtual void FixedTextRotationTest01() { - String outFileName = destinationFolder + "fixedTextRotationTest01.pdf"; - String cmpFileName = sourceFolder + cmpPrefix + "fixedTextRotationTest01.pdf"; + String outFileName = DESTINATION_FOLDER + "fixedTextRotationTest01.pdf"; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + "fixedTextRotationTest01.pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); SolidBorder border = new SolidBorder(0.5f); @@ -88,14 +91,14 @@ public virtual void FixedTextRotationTest01() { width2)); document.Add(new Paragraph(longText).SetMargin(0).SetFixedPosition(x2, y2, width2)); document.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [NUnit.Framework.Test] public virtual void FixedTextRotationTest02() { - String outFileName = destinationFolder + "fixedTextRotationTest02.pdf"; - String cmpFileName = sourceFolder + cmpPrefix + "fixedTextRotationTest02.pdf"; + String outFileName = DESTINATION_FOLDER + "fixedTextRotationTest02.pdf"; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + "fixedTextRotationTest02.pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); String longText = "loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo" @@ -104,14 +107,14 @@ public virtual void FixedTextRotationTest02() { , 450)); document.Add(new Paragraph(longText).SetMargin(0).SetFixedPosition(50, 50, 450)); document.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [NUnit.Framework.Test] public virtual void FixedTextRotationTest03() { - String outFileName = destinationFolder + "fixedTextRotationTest03.pdf"; - String cmpFileName = sourceFolder + cmpPrefix + "fixedTextRotationTest03.pdf"; + String outFileName = DESTINATION_FOLDER + "fixedTextRotationTest03.pdf"; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + "fixedTextRotationTest03.pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); String simpleText = "text simple text"; @@ -124,14 +127,14 @@ public virtual void FixedTextRotationTest03() { PdfCanvas canvas = new PdfCanvas(pdfDocument.GetFirstPage()); DrawCross(canvas, x, y); document.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [NUnit.Framework.Test] public virtual void FixedTextRotationTest04() { - String outFileName = destinationFolder + "fixedTextRotationTest04.pdf"; - String cmpFileName = sourceFolder + cmpPrefix + "fixedTextRotationTest04.pdf"; + String outFileName = DESTINATION_FOLDER + "fixedTextRotationTest04.pdf"; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + "fixedTextRotationTest04.pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); String simpleText = "text simple text"; @@ -143,15 +146,15 @@ public virtual void FixedTextRotationTest04() { PdfCanvas canvas = new PdfCanvas(pdfDocument.GetFirstPage()); DrawCross(canvas, x, y); document.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [LogMessage(LayoutLogMessageConstant.ELEMENT_DOES_NOT_FIT_AREA)] [NUnit.Framework.Test] public virtual void StaticTextRotationTest01() { - String outFileName = destinationFolder + "staticTextRotationTest01.pdf"; - String cmpFileName = sourceFolder + cmpPrefix + "staticTextRotationTest01.pdf"; + String outFileName = DESTINATION_FOLDER + "staticTextRotationTest01.pdf"; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + "staticTextRotationTest01.pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); Paragraph p = new Paragraph(); @@ -162,15 +165,15 @@ public virtual void StaticTextRotationTest01() { document.Add(new Paragraph("text line text line text line text line text line text line text line text line text line text line text line" )); document.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [LogMessage(LayoutLogMessageConstant.ELEMENT_DOES_NOT_FIT_AREA, Count = 2)] [NUnit.Framework.Test] public virtual void StaticTextRotationTest02() { - String outFileName = destinationFolder + "staticTextRotationTest02.pdf"; - String cmpFileName = sourceFolder + cmpPrefix + "staticTextRotationTest02.pdf"; + String outFileName = DESTINATION_FOLDER + "staticTextRotationTest02.pdf"; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + "staticTextRotationTest02.pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); document.Add(new Paragraph(para1Text)); @@ -179,15 +182,15 @@ public virtual void StaticTextRotationTest02() { (-Math.PI / 12)).SetBackgroundColor(ColorConstants.BLUE)); document.Add(new Paragraph(para3Text)); document.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [LogMessage(LayoutLogMessageConstant.ELEMENT_DOES_NOT_FIT_AREA)] [NUnit.Framework.Test] public virtual void StaticTextRotationTest03() { - String outFileName = destinationFolder + "staticTextRotationTest03.pdf"; - String cmpFileName = sourceFolder + cmpPrefix + "staticTextRotationTest03.pdf"; + String outFileName = DESTINATION_FOLDER + "staticTextRotationTest03.pdf"; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + "staticTextRotationTest03.pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); document.Add(new Paragraph(para1Text)); @@ -196,14 +199,14 @@ public virtual void StaticTextRotationTest03() { document.Add(new Paragraph(para2Text).SetRotationAngle((-Math.PI / 3))); document.Add(new Paragraph(para3Text)); document.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [NUnit.Framework.Test] public virtual void StaticTextRotationTest04() { - String outFileName = destinationFolder + "staticTextRotationTest04.pdf"; - String cmpFileName = sourceFolder + cmpPrefix + "staticTextRotationTest04.pdf"; + String outFileName = DESTINATION_FOLDER + "staticTextRotationTest04.pdf"; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + "staticTextRotationTest04.pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); document.Add(new Paragraph(para1Text)); @@ -211,14 +214,14 @@ public virtual void StaticTextRotationTest04() { .RED)); document.Add(new Paragraph(para3Text)); document.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [NUnit.Framework.Test] public virtual void SplitTextRotationTest01() { - String outFileName = destinationFolder + "splitTextRotationTest01.pdf"; - String cmpFileName = sourceFolder + cmpPrefix + "splitTextRotationTest01.pdf"; + String outFileName = DESTINATION_FOLDER + "splitTextRotationTest01.pdf"; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + "splitTextRotationTest01.pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); document.Add(new Paragraph(para1Text)); @@ -227,15 +230,15 @@ public virtual void SplitTextRotationTest01() { document.Add(new Paragraph(para2Text).SetRotationAngle((-Math.PI / 3))); document.Add(new Paragraph(para3Text)); document.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [LogMessage(LayoutLogMessageConstant.ELEMENT_DOES_NOT_FIT_AREA, Count = 2)] [NUnit.Framework.Test] public virtual void SplitTextRotationTest02() { - String outFileName = destinationFolder + "splitTextRotationTest02.pdf"; - String cmpFileName = sourceFolder + cmpPrefix + "splitTextRotationTest02.pdf"; + String outFileName = DESTINATION_FOLDER + "splitTextRotationTest02.pdf"; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + "splitTextRotationTest02.pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); document.Add(new Paragraph(para1Text)); @@ -248,21 +251,21 @@ public virtual void SplitTextRotationTest02() { document.Add(new Paragraph(extremelyLongText).SetRotationAngle(Math.PI / 2)); document.Add(new Paragraph(extremelyLongText).SetRotationAngle(Math.PI / 4)); document.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [NUnit.Framework.Test] public virtual void RotationInfiniteLoopTest01() { String fileName = "rotationInfiniteLoopTest01.pdf"; - String outFileName = destinationFolder + fileName; - String cmpFileName = sourceFolder + cmpPrefix + fileName; + String outFileName = DESTINATION_FOLDER + fileName; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + fileName; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); pdfDocument.SetDefaultPageSize(PageSize.A5.Rotate()); Document document = new Document(pdfDocument); document.Add(new Paragraph(para1Text).SetRotationAngle((Math.PI / 2))); document.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } @@ -270,22 +273,22 @@ public virtual void RotationInfiniteLoopTest01() { [NUnit.Framework.Test] public virtual void RotationInfiniteLoopTest02() { String fileName = "rotationInfiniteLoopTest02.pdf"; - String outFileName = destinationFolder + fileName; - String cmpFileName = sourceFolder + cmpPrefix + fileName; + String outFileName = DESTINATION_FOLDER + fileName; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + fileName; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); pdfDocument.SetDefaultPageSize(PageSize.A5.Rotate()); Document document = new Document(pdfDocument); document.Add(new List().Add(para1Text).SetRotationAngle((Math.PI / 2))); document.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [LogMessage(iText.IO.Logs.IoLogMessageConstant.TABLE_WIDTH_IS_MORE_THAN_EXPECTED_DUE_TO_MIN_WIDTH)] [NUnit.Framework.Test] public virtual void TableRotationTest02() { - String outFileName = destinationFolder + "tableRotationTest02.pdf"; - String cmpFileName = sourceFolder + cmpPrefix + "tableRotationTest02.pdf"; + String outFileName = DESTINATION_FOLDER + "tableRotationTest02.pdf"; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + "tableRotationTest02.pdf"; PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outFileName)); Document doc = new Document(pdfDoc); Table table = new Table(new float[] { 50, 50 }); @@ -296,15 +299,15 @@ public virtual void TableRotationTest02() { SetRotationAngle((Math.PI)))); doc.Add(table); doc.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [LogMessage(LayoutLogMessageConstant.ELEMENT_DOES_NOT_FIT_AREA)] [NUnit.Framework.Test] public virtual void TableRotationTest03() { - String outFileName = destinationFolder + "tableRotationTest03.pdf"; - String cmpFileName = sourceFolder + cmpPrefix + "tableRotationTest03.pdf"; + String outFileName = DESTINATION_FOLDER + "tableRotationTest03.pdf"; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + "tableRotationTest03.pdf"; PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outFileName)); Document doc = new Document(pdfDoc); Table table = new Table(new float[] { 25, 50 }); @@ -316,14 +319,14 @@ public virtual void TableRotationTest03() { ((Math.PI)))); doc.Add(table); doc.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [NUnit.Framework.Test] public virtual void CellRotationTest01() { - String outFileName = destinationFolder + "cellRotationTest01.pdf"; - String cmpFileName = sourceFolder + cmpPrefix + "cellRotationTest01.pdf"; + String outFileName = DESTINATION_FOLDER + "cellRotationTest01.pdf"; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + "cellRotationTest01.pdf"; PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outFileName)); Document doc = new Document(pdfDoc); Table table = new Table(UnitValue.CreatePercentArray(1)).UseAllAvailableWidth(); @@ -332,14 +335,14 @@ public virtual void CellRotationTest01() { (ColorConstants.GREEN)); doc.Add(table); doc.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [NUnit.Framework.Test] public virtual void CellRotationTest02() { - String outFileName = destinationFolder + "cellRotationTest02.pdf"; - String cmpFileName = sourceFolder + cmpPrefix + "cellRotationTest02.pdf"; + String outFileName = DESTINATION_FOLDER + "cellRotationTest02.pdf"; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + "cellRotationTest02.pdf"; PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outFileName)); Document doc = new Document(pdfDoc); Table table = new Table(UnitValue.CreatePercentArray(new float[] { 5, 95 })); @@ -348,14 +351,14 @@ public virtual void CellRotationTest02() { ))); doc.Add(table); doc.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [NUnit.Framework.Test] public virtual void CellRotationTest03() { - String outFileName = destinationFolder + "cellRotationTest03.pdf"; - String cmpFileName = sourceFolder + cmpPrefix + "cellRotationTest03.pdf"; + String outFileName = DESTINATION_FOLDER + "cellRotationTest03.pdf"; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + "cellRotationTest03.pdf"; PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outFileName)); Document doc = new Document(pdfDoc); Table table = new Table(UnitValue.CreatePointArray(new float[] { -1, -1 })); @@ -364,14 +367,14 @@ public virtual void CellRotationTest03() { ))); doc.Add(table); doc.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [NUnit.Framework.Test] public virtual void CellRotationDependsOnNeighbourCell() { - String outFileName = destinationFolder + "cellRotationDependsOnNeighbourCell.pdf"; - String cmpFileName = sourceFolder + cmpPrefix + "cellRotationDependsOnNeighbourCell.pdf"; + String outFileName = DESTINATION_FOLDER + "cellRotationDependsOnNeighbourCell.pdf"; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + "cellRotationDependsOnNeighbourCell.pdf"; PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outFileName)); Document doc = new Document(pdfDoc, new PageSize(300, 180)); doc.Add(CreateTable(60)); @@ -380,7 +383,7 @@ public virtual void CellRotationDependsOnNeighbourCell() { doc.Add(new AreaBreak()); doc.Add(CreateTable(100)); doc.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } @@ -388,8 +391,8 @@ public virtual void CellRotationDependsOnNeighbourCell() { public virtual void CellRotationParagraphIsGone() { // TODO DEVSIX-5029 Content of the first cell is missing String testName = "cellRotationParagraphIsGone.pdf"; - String outFileName = destinationFolder + testName; - String cmpFileName = sourceFolder + cmpPrefix + testName; + String outFileName = DESTINATION_FOLDER + testName; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + testName; PdfDocument pdf = new PdfDocument(new PdfWriter(outFileName)); Document doc = new Document(pdf); Table table = new Table(2); @@ -405,7 +408,7 @@ public virtual void CellRotationParagraphIsGone() { table.AddCell(cell); doc.Add(table); doc.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } @@ -423,8 +426,8 @@ private Table CreateTable(float height) { [NUnit.Framework.Test] public virtual void DivRotationTest01() { - String outFileName = destinationFolder + "divRotationTest01.pdf"; - String cmpFileName = sourceFolder + cmpPrefix + "divRotationTest01.pdf"; + String outFileName = DESTINATION_FOLDER + "divRotationTest01.pdf"; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + "divRotationTest01.pdf"; PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outFileName)); Document doc = new Document(pdfDoc); Div div = new Div().SetBackgroundColor(ColorConstants.GREEN); @@ -434,15 +437,15 @@ public virtual void DivRotationTest01() { div.Add(new Paragraph(para1Text)).SetRotationAngle(Math.PI / 2); doc.Add(div); doc.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [LogMessage(LayoutLogMessageConstant.ELEMENT_DOES_NOT_FIT_AREA, Count = 2)] [NUnit.Framework.Test] public virtual void DivRotationTest02() { - String outFileName = destinationFolder + "divRotationTest02.pdf"; - String cmpFileName = sourceFolder + cmpPrefix + "divRotationTest02.pdf"; + String outFileName = DESTINATION_FOLDER + "divRotationTest02.pdf"; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + "divRotationTest02.pdf"; PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outFileName)); Document doc = new Document(pdfDoc); doc.Add(new Paragraph(para1Text)); @@ -455,14 +458,14 @@ public virtual void DivRotationTest02() { doc.Add(new Div().Add(new Paragraph(extremelyLongText)).SetRotationAngle(Math.PI / 2)); doc.Add(new Div().Add(new Paragraph(extremelyLongText)).SetRotationAngle(Math.PI / 4)); doc.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [NUnit.Framework.Test] public virtual void ListRotationTest01() { - String outFileName = destinationFolder + "listRotationTest01.pdf"; - String cmpFileName = sourceFolder + cmpPrefix + "listRotationTest01.pdf"; + String outFileName = DESTINATION_FOLDER + "listRotationTest01.pdf"; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + "listRotationTest01.pdf"; PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outFileName)); Document doc = new Document(pdfDoc); doc.Add(new Paragraph(para1Text)); @@ -473,15 +476,15 @@ public virtual void ListRotationTest01() { doc.Add(list); doc.Add(new Paragraph(para2Text)); doc.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [LogMessage(LayoutLogMessageConstant.ELEMENT_DOES_NOT_FIT_AREA)] [NUnit.Framework.Test] public virtual void ListRotationTest02() { - String outFileName = destinationFolder + "listRotationTest02.pdf"; - String cmpFileName = sourceFolder + cmpPrefix + "listRotationTest02.pdf"; + String outFileName = DESTINATION_FOLDER + "listRotationTest02.pdf"; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + "listRotationTest02.pdf"; PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outFileName)); Document doc = new Document(pdfDoc); doc.Add(new Paragraph(para1Text)); @@ -495,14 +498,14 @@ public virtual void ListRotationTest02() { doc.Add(list); doc.Add(new Paragraph(para2Text)); doc.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [NUnit.Framework.Test] public virtual void AlignedTextRotationTest01() { - String outFileName = destinationFolder + "alignedTextRotationTest01.pdf"; - String cmpFileName = sourceFolder + cmpPrefix + "alignedTextRotationTest01.pdf"; + String outFileName = DESTINATION_FOLDER + "alignedTextRotationTest01.pdf"; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + "alignedTextRotationTest01.pdf"; PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outFileName)); Document doc = new Document(pdfDoc); doc.Add(new Paragraph(para1Text)); @@ -513,29 +516,29 @@ public virtual void AlignedTextRotationTest01() { doc.Add(p); doc.Add(new Paragraph(para3Text)); doc.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [NUnit.Framework.Test] public virtual void InnerRotationTest01() { - String outFileName = destinationFolder + "innerRotationTest01.pdf"; - String cmpFileName = sourceFolder + cmpPrefix + "innerRotationTest01.pdf"; + String outFileName = DESTINATION_FOLDER + "innerRotationTest01.pdf"; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + "innerRotationTest01.pdf"; PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outFileName)); Document doc = new Document(pdfDoc); doc.Add(new Div().SetBackgroundColor(ColorConstants.GREEN).SetHeight(300).SetWidth(300).Add(new Div().SetBackgroundColor (ColorConstants.RED).SetHeight(100).SetWidth(100).SetRotationAngle(Math.PI / 4)).SetRotationAngle(Math .PI / 8)); doc.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [LogMessage(LayoutLogMessageConstant.ELEMENT_DOES_NOT_FIT_AREA, Count = 3)] [NUnit.Framework.Test] public virtual void InnerRotationTest02() { - String outFileName = destinationFolder + "innerRotationTest02.pdf"; - String cmpFileName = sourceFolder + cmpPrefix + "innerRotationTest02.pdf"; + String outFileName = DESTINATION_FOLDER + "innerRotationTest02.pdf"; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + "innerRotationTest02.pdf"; PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outFileName)); Document doc = new Document(pdfDoc, new PageSize(6400, 6400)); String longText = para1Text + para2Text + para3Text; @@ -545,14 +548,14 @@ public virtual void InnerRotationTest02() { ))).Add(new Paragraph("smaaaaaaaaaaaaaaaaaaaall taaaaaaaaaaaaaaaaaaalk")).Add(new Paragraph("smaaaaaaaaaaaaaaaaaaaall taaaaaaaaaaaaaaaaaaalk" )).SetRotationAngle(Math.PI / 8)); doc.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [NUnit.Framework.Test] public virtual void FixedWidthRotationTest01() { - String outFileName = destinationFolder + "fixedWidthRotationTest01.pdf"; - String cmpFileName = sourceFolder + cmpPrefix + "fixedWidthRotationTest01.pdf"; + String outFileName = DESTINATION_FOLDER + "fixedWidthRotationTest01.pdf"; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + "fixedWidthRotationTest01.pdf"; Document doc = new Document(new PdfDocument(new PdfWriter(outFileName))); Text text = new Text("Hello. I am a fairly long paragraph. I really want you to process me correctly. You heard that? Correctly!!! Even if you will have to wrap me." ); @@ -561,14 +564,14 @@ public virtual void FixedWidthRotationTest01() { .BLUE, 5)); doc.Add(d.Add(p)); doc.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [NUnit.Framework.Test] public virtual void FixedWidthRotationTest02() { - String outFileName = destinationFolder + "fixedWidthRotationTest02.pdf"; - String cmpFileName = sourceFolder + cmpPrefix + "fixedWidthRotationTest02.pdf"; + String outFileName = DESTINATION_FOLDER + "fixedWidthRotationTest02.pdf"; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + "fixedWidthRotationTest02.pdf"; Document doc = new Document(new PdfDocument(new PdfWriter(outFileName))); Text text = new Text("Hello. I am a fairly long paragraph. I really want you to process me correctly. You heard that? Correctly!!! Even if you will have to wrap me." ); @@ -577,14 +580,14 @@ public virtual void FixedWidthRotationTest02() { (ColorConstants.BLUE, 5)); doc.Add(d.Add(p)); doc.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [NUnit.Framework.Test] public virtual void FixedWidthRotationTest03() { - String outFileName = destinationFolder + "fixedWidthRotationTest03.pdf"; - String cmpFileName = sourceFolder + cmpPrefix + "fixedWidthRotationTest03.pdf"; + String outFileName = DESTINATION_FOLDER + "fixedWidthRotationTest03.pdf"; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + "fixedWidthRotationTest03.pdf"; Document doc = new Document(new PdfDocument(new PdfWriter(outFileName))); Text text = new Text("Hello. I am a fairly long paragraph. I really want you to process me correctly. You heard that? Correctly!!! Even if you will have to wrap me." ); @@ -593,17 +596,17 @@ public virtual void FixedWidthRotationTest03() { SolidBorder(ColorConstants.BLUE, 5)); doc.Add(d.Add(d1)); doc.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [NUnit.Framework.Test] public virtual void ImageInRotatedBlockTest01() { - String outFileName = destinationFolder + "imageInRotatedBlockTest01.pdf"; - String cmpFileName = sourceFolder + "cmp_imageInRotatedBlockTest01.pdf"; + String outFileName = DESTINATION_FOLDER + "imageInRotatedBlockTest01.pdf"; + String cmpFileName = SOURCE_FOLDER + "cmp_imageInRotatedBlockTest01.pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document doc = new Document(pdfDocument); - iText.Layout.Element.Image image = new Image(ImageDataFactory.Create(sourceFolder + "Desert.jpg")); + iText.Layout.Element.Image image = new Image(ImageDataFactory.Create(SOURCE_FOLDER + "Desert.jpg")); image.SetWidth(200); Div div = new Div(); div.SetRotationAngle(Math.PI / 2); @@ -612,7 +615,7 @@ public virtual void ImageInRotatedBlockTest01() { doc.Add(div); doc.Add(new Paragraph("Hello!!!").SetBackgroundColor(ColorConstants.RED)); doc.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } @@ -621,12 +624,12 @@ public virtual void ImageInRotatedBlockTest01() { [LogMessage(iText.IO.Logs.IoLogMessageConstant.ROTATION_WAS_NOT_CORRECTLY_PROCESSED_FOR_RENDERER, Count = 2)] public virtual void ImageInRotatedBlockTest02() { - String outFileName = destinationFolder + "imageInRotatedBlockTest02.pdf"; - String cmpFileName = sourceFolder + "cmp_imageInRotatedBlockTest02.pdf"; + String outFileName = DESTINATION_FOLDER + "imageInRotatedBlockTest02.pdf"; + String cmpFileName = SOURCE_FOLDER + "cmp_imageInRotatedBlockTest02.pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document doc = new Document(pdfDocument); - iText.Layout.Element.Image image = new iText.Layout.Element.Image(ImageDataFactory.Create(sourceFolder + "Desert.jpg" - )); + iText.Layout.Element.Image image = new iText.Layout.Element.Image(ImageDataFactory.Create(SOURCE_FOLDER + + "Desert.jpg")); image.SetWidth(200); Div div = new Div(); div.SetHeight(100); @@ -636,14 +639,14 @@ public virtual void ImageInRotatedBlockTest02() { doc.Add(div); doc.Add(new Paragraph("Hello!!!").SetBackgroundColor(ColorConstants.RED)); doc.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [NUnit.Framework.Test] public virtual void BlockWithBorderBoxSizingTest01() { - String outFileName = destinationFolder + "blockWithBorderBoxSizingTest01.pdf"; - String cmpFileName = sourceFolder + "cmp_blockWithBorderBoxSizingTest01.pdf"; + String outFileName = DESTINATION_FOLDER + "blockWithBorderBoxSizingTest01.pdf"; + String cmpFileName = SOURCE_FOLDER + "cmp_blockWithBorderBoxSizingTest01.pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document doc = new Document(pdfDocument); Div div = new Div(); @@ -656,15 +659,15 @@ public virtual void BlockWithBorderBoxSizingTest01() { div.SetProperty(Property.BOX_SIZING, BoxSizingPropertyValue.BORDER_BOX); doc.Add(div); doc.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [NUnit.Framework.Test] public virtual void MarginsRotatedTest01() { //TODO: currently is incorrect. See DEVSIX-989 - String outFileName = destinationFolder + "marginsRotatedTest01.pdf"; - String cmpFileName = sourceFolder + cmpPrefix + "marginsRotatedTest01.pdf"; + String outFileName = DESTINATION_FOLDER + "marginsRotatedTest01.pdf"; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + "marginsRotatedTest01.pdf"; Document doc = new Document(new PdfDocument(new PdfWriter(outFileName))); Text text = new Text("Hello. I am a fairly long paragraph. I really want you to process me correctly. You heard that? Correctly!!! Even if you will have to wrap me." ); @@ -673,15 +676,15 @@ public virtual void MarginsRotatedTest01() { , 100, 10).SetBorder(new SolidBorder(ColorConstants.BLUE, 5)); doc.Add(d.Add(d1)); doc.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [NUnit.Framework.Test] public virtual void MarginsRotatedTest02() { //TODO: currently is incorrect. See DEVSIX-989 - String outFileName = destinationFolder + "marginsRotatedTest02.pdf"; - String cmpFileName = sourceFolder + cmpPrefix + "marginsRotatedTest02.pdf"; + String outFileName = DESTINATION_FOLDER + "marginsRotatedTest02.pdf"; + String cmpFileName = SOURCE_FOLDER + cmpPrefix + "marginsRotatedTest02.pdf"; Document doc = new Document(new PdfDocument(new PdfWriter(outFileName))); doc.SetProperty(Property.COLLAPSING_MARGINS, true); Text text = new Text("Hello. I am a fairly long paragraph. I really want you to process me correctly. You heard that? Correctly!!! Even if you will have to wrap me." @@ -692,15 +695,15 @@ public virtual void MarginsRotatedTest02() { doc.Add(d.Add(d1).Add(new Paragraph("Hello").SetMargin(50).SetBorder(new SolidBorder(ColorConstants.GREEN, 5)))); doc.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER , "diff")); } [NUnit.Framework.Test] public virtual void ZeroDegreeRotatedWithAlignmentParagraphInDivTest() { //TODO: update cmp file after fixing DEVSIX-4458 - String outFileName = destinationFolder + "zeroDegreeRotatedWithAlignmentParagraphInDiv.pdf"; - String cmpFileName = sourceFolder + "cmp_zeroDegreeRotatedWithAlignmentParagraphInDiv.pdf"; + String outFileName = DESTINATION_FOLDER + "zeroDegreeRotatedWithAlignmentParagraphInDiv.pdf"; + String cmpFileName = SOURCE_FOLDER + "cmp_zeroDegreeRotatedWithAlignmentParagraphInDiv.pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document doc = new Document(pdfDocument); Div div = new Div().SetBorder(new SolidBorder(ColorConstants.BLACK, 1)); @@ -713,15 +716,15 @@ public virtual void ZeroDegreeRotatedWithAlignmentParagraphInDivTest() { (MathUtil.ToRadians(0))); doc.Add(div); doc.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER )); } [NUnit.Framework.Test] public virtual void Rotated180DegreesWithAlignmentParagraphInDivTest() { //TODO: update cmp file after fixing DEVSIX-4458 - String outFileName = destinationFolder + "rotated180DegreesWithAlignmentParagraphInDiv.pdf"; - String cmpFileName = sourceFolder + "cmp_rotated180DegreesWithAlignmentParagraphInDiv.pdf"; + String outFileName = DESTINATION_FOLDER + "rotated180DegreesWithAlignmentParagraphInDiv.pdf"; + String cmpFileName = SOURCE_FOLDER + "cmp_rotated180DegreesWithAlignmentParagraphInDiv.pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document doc = new Document(pdfDocument); Div div = new Div().SetBorder(new SolidBorder(ColorConstants.BLACK, 1)); @@ -734,15 +737,15 @@ public virtual void Rotated180DegreesWithAlignmentParagraphInDivTest() { (MathUtil.ToRadians(180))); doc.Add(div); doc.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER )); } [NUnit.Framework.Test] public virtual void Rotated90DegreesWithAlignmentParagraphInDivTest() { //TODO: update cmp file after fixing DEVSIX-4458 - String outFileName = destinationFolder + "rotated90DegreesWithAlignmentParagraphInDiv.pdf"; - String cmpFileName = sourceFolder + "cmp_rotated90DegreesWithAlignmentParagraphInDiv.pdf"; + String outFileName = DESTINATION_FOLDER + "rotated90DegreesWithAlignmentParagraphInDiv.pdf"; + String cmpFileName = SOURCE_FOLDER + "cmp_rotated90DegreesWithAlignmentParagraphInDiv.pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document doc = new Document(pdfDocument); Div div = new Div().SetBorder(new SolidBorder(ColorConstants.BLACK, 1)); @@ -755,15 +758,15 @@ public virtual void Rotated90DegreesWithAlignmentParagraphInDivTest() { (MathUtil.ToRadians(90))); doc.Add(div); doc.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER )); } [NUnit.Framework.Test] public virtual void RotatedWithAlignmentCellInTableTest() { //TODO: update cmp file after fixing DEVSIX-4458 - String outFileName = destinationFolder + "rotatedWithAlignmentCellInTable.pdf"; - String cmpFileName = sourceFolder + "cmp_rotatedWithAlignmentCellInTable.pdf"; + String outFileName = DESTINATION_FOLDER + "rotatedWithAlignmentCellInTable.pdf"; + String cmpFileName = SOURCE_FOLDER + "cmp_rotatedWithAlignmentCellInTable.pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document doc = new Document(pdfDocument); Table table = new Table(1); @@ -776,8 +779,41 @@ public virtual void RotatedWithAlignmentCellInTableTest() { table.AddCell(cell); doc.Add(table); doc.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER + )); + } + + [NUnit.Framework.Test] + public virtual void IgnorePageRotationForContentTest() { + String inputFile = SOURCE_FOLDER + "rotated.pdf"; + String compareFile = SOURCE_FOLDER + "cmp_ignorePageRotationForContent.pdf"; + String outputFile = DESTINATION_FOLDER + "ignorePageRotationForContent.pdf"; + using (PdfDocument pdfDoc = new PdfDocument(new PdfReader(inputFile), new PdfWriter(outputFile))) { + using (Document doc = new Document(pdfDoc)) { + PdfExtGState gs1 = new PdfExtGState().SetFillOpacity(0.5f); + PdfFont font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA); + Paragraph paragraph = new Paragraph("My watermark (text)").SetFont(font).SetFontSize(30); + PdfPage pdfPage = pdfDoc.GetPage(1); + Rectangle pageSize = pdfPage.GetPageSizeWithRotation(); + // When "true": in case the page has a rotation, then new content will be automatically rotated in the + // opposite direction. On the rotated page this would look as if new content ignores page rotation. + pdfPage.SetIgnorePageRotationForContent(true); + float x = (pageSize.GetLeft() + pageSize.GetRight()) / 2; + float y = (pageSize.GetTop() + pageSize.GetBottom()) / 2; + PdfCanvas over = new PdfCanvas(pdfPage); + over.SaveState(); + over.SetExtGState(gs1); + // Each showTextAligned call creates new PdfCanvas instance for the same page. + doc.ShowTextAligned(paragraph, x, y + 100, 1, TextAlignment.CENTER, VerticalAlignment.TOP, 0); + doc.ShowTextAligned(paragraph, x, y, 1, TextAlignment.CENTER, VerticalAlignment.TOP, 0); + doc.ShowTextAligned(paragraph, x, y - 100, 1, TextAlignment.CENTER, VerticalAlignment.TOP, 0); + over.RestoreState(); + } + } + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outputFile, compareFile, DESTINATION_FOLDER )); + NUnit.Framework.Assert.IsNull(new CompareTool().CompareVisually(outputFile, compareFile, DESTINATION_FOLDER + , "diff_")); } private void DrawCross(PdfCanvas canvas, float x, float y) { diff --git a/itext.tests/itext.layout.tests/itext/layout/TableBorderTest.cs b/itext.tests/itext.layout.tests/itext/layout/TableBorderTest.cs index 58ebb343e3..8dcab2cdcb 100644 --- a/itext.tests/itext.layout.tests/itext/layout/TableBorderTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/TableBorderTest.cs @@ -696,7 +696,10 @@ public virtual void SplitCellsTest02() { table.SetBorder(new SolidBorder(ColorConstants.YELLOW, 3)); doc.Add(table); doc.Add(new AreaBreak()); - table.DeleteOwnProperty(Property.BORDER); + table.DeleteOwnProperty(Property.BORDER_LEFT); + table.DeleteOwnProperty(Property.BORDER_BOTTOM); + table.DeleteOwnProperty(Property.BORDER_RIGHT); + table.DeleteOwnProperty(Property.BORDER_TOP); table.SetBorderCollapse(BorderCollapsePropertyValue.SEPARATE); table.SetHorizontalBorderSpacing(20); table.SetVerticalBorderSpacing(20); @@ -1184,7 +1187,10 @@ public virtual void TableWithHeaderFooterTest05() { doc.Add(table); doc.Add(new Table(UnitValue.CreatePercentArray(1)).UseAllAvailableWidth().AddCell("Hello").SetBorder(new SolidBorder (ColorConstants.ORANGE, 5))); - table.DeleteOwnProperty(Property.BORDER); + table.DeleteOwnProperty(Property.BORDER_LEFT); + table.DeleteOwnProperty(Property.BORDER_BOTTOM); + table.DeleteOwnProperty(Property.BORDER_RIGHT); + table.DeleteOwnProperty(Property.BORDER_TOP); doc.Add(table); doc.Add(new Table(UnitValue.CreatePercentArray(1)).UseAllAvailableWidth().AddCell("Hello").SetBorder(new SolidBorder (ColorConstants.ORANGE, 5))); @@ -1196,7 +1202,10 @@ public virtual void TableWithHeaderFooterTest05() { doc.Add(table); doc.Add(new Table(UnitValue.CreatePercentArray(1)).UseAllAvailableWidth().AddCell("Hello").SetBorder(new SolidBorder (ColorConstants.ORANGE, 5))); - table.DeleteOwnProperty(Property.BORDER); + table.DeleteOwnProperty(Property.BORDER_LEFT); + table.DeleteOwnProperty(Property.BORDER_BOTTOM); + table.DeleteOwnProperty(Property.BORDER_RIGHT); + table.DeleteOwnProperty(Property.BORDER_TOP); doc.Add(table); doc.Add(new Table(UnitValue.CreatePercentArray(1)).UseAllAvailableWidth().AddCell("Hello").SetBorder(new SolidBorder (ColorConstants.ORANGE, 5))); @@ -1590,7 +1599,7 @@ public virtual void TableWithHeaderFooterTest14() { } } table.GetHeader().SetBorderTop(new SolidBorder(2)).SetBorderBottom(new SolidBorder(1)); - table.GetFooter().SetBold().SetBorderTop(new SolidBorder(10)).SetBorderBottom(new SolidBorder(1)).SetBackgroundColor + table.GetFooter().SimulateBold().SetBorderTop(new SolidBorder(10)).SetBorderBottom(new SolidBorder(1)).SetBackgroundColor (ColorConstants.LIGHT_GRAY); doc.Add(table); doc.Add(new AreaBreak()); diff --git a/itext.tests/itext.layout.tests/itext/layout/TableTest.cs b/itext.tests/itext.layout.tests/itext/layout/TableTest.cs index 8dffade6d2..7c1a1f3d57 100644 --- a/itext.tests/itext.layout.tests/itext/layout/TableTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/TableTest.cs @@ -1879,11 +1879,11 @@ public virtual void AutoLayoutTest01() { doc.Add(table); doc.Add(new Paragraph("A cell with bold text:")); table = new Table(new float[1]); - table.AddCell("A cell").SetBold(); + table.AddCell("A cell").SimulateBold(); doc.Add(table); doc.Add(new Paragraph("A cell with italic text:")); table = new Table(new float[1]); - table.AddCell("A cell").SetItalic(); + table.AddCell("A cell").SimulateItalic(); doc.Add(table); doc.Close(); NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder @@ -2762,7 +2762,7 @@ public virtual void InheritHeaderPropsWhileMinMaxWidthCalculationsTest() { table.AddCell(new Cell().Add(new Paragraph("He"))); // If this property is not inherited while calculating min/max widths, // then while layouting header will request more space than the layout box's width - table.GetHeader().SetBold(); + table.GetHeader().SimulateBold(); document.Add(table); document.Close(); NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + filename, sourceFolder @@ -2928,7 +2928,7 @@ public virtual void PreciseFittingBoldSimulatedTextInCellsTest() { table.UseAllAvailableWidth(); table.SetFixedLayout(); for (int i = 0; i < numberOfColumns; i++) { - table.AddCell(new Cell().Add(new Paragraph("Description").SetBold())); + table.AddCell(new Cell().Add(new Paragraph("Description").SimulateBold())); } doc.Add(table); } diff --git a/itext.tests/itext.layout.tests/itext/layout/TextWritingTest.cs b/itext.tests/itext.layout.tests/itext/layout/TextWritingTest.cs index 7e3f42cd31..13d8faa717 100644 --- a/itext.tests/itext.layout.tests/itext/layout/TextWritingTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/TextWritingTest.cs @@ -30,6 +30,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Kernel.Utils; using iText.Layout.Borders; using iText.Layout.Element; +using iText.Layout.Exceptions; using iText.Layout.Properties; using iText.Test; @@ -210,12 +211,12 @@ public virtual void FontStyleSimulationTest01() { document.Add(new Paragraph("I'm underlined").SetUnderline()); document.Add(new Paragraph("I'm strikethrough").SetLineThrough()); document.Add(new Paragraph(new Text("I'm a bold simulation font").SetBackgroundColor(ColorConstants.GREEN) - ).SetBold()); + ).SimulateBold()); document.Add(new Paragraph(new Text("I'm an italic simulation font").SetBackgroundColor(ColorConstants.GREEN - )).SetItalic()); + )).SimulateItalic()); document.Add(new Paragraph(new Text("I'm a super bold italic underlined linethrough piece of text and no one can be better than me, even if " + "such a long description will cause me to occupy two lines").SetBackgroundColor(ColorConstants.GREEN - )).SetItalic().SetBold().SetUnderline().SetLineThrough()); + )).SimulateItalic().SimulateBold().SetUnderline().SetLineThrough()); document.Close(); NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder , "diff")); @@ -295,6 +296,12 @@ public virtual void LineThroughTest() { , "diff_")); } + [NUnit.Framework.Test] + public virtual void TextInitializationWithNullValueThrowsException() { + Exception e = NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => new Text(null)); + NUnit.Framework.Assert.AreEqual(LayoutExceptionMessageConstant.TEXT_CONTENT_CANNOT_BE_NULL, e.Message); + } + [NUnit.Framework.Test] public virtual void LeadingAndFloatInTextTest() { // TODO: update cmp file after fixing DEVSIX-4604 diff --git a/itext.tests/itext.layout.tests/itext/layout/XMPWriterTest.cs b/itext.tests/itext.layout.tests/itext/layout/XMPWriterTest.cs index cc95e2cb79..bff812327c 100644 --- a/itext.tests/itext.layout.tests/itext/layout/XMPWriterTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/XMPWriterTest.cs @@ -83,8 +83,8 @@ public virtual void CreatePdfTest() { [NUnit.Framework.Test] public virtual void AddUAXMPMetaDataNotTaggedTest() { String fileName = "addUAXMPMetaDataNotTaggedTest.pdf"; - PdfDocument pdf = new PdfDocument(new PdfWriter(destinationFolder + fileName, new WriterProperties().AddUAXmpMetadata - ())); + WriterProperties writerProperties = new WriterProperties().AddPdfUaXmpMetadata(PdfUAConformance.PDF_UA_1); + PdfDocument pdf = new PdfDocument(new PdfWriter(destinationFolder + fileName, writerProperties)); ManipulatePdf(pdf, false); NUnit.Framework.Assert.IsNull(new CompareTool().CompareXmp(destinationFolder + fileName, sourceFolder + "cmp_" + fileName, true)); @@ -93,8 +93,8 @@ public virtual void AddUAXMPMetaDataNotTaggedTest() { [NUnit.Framework.Test] public virtual void AddUAXMPMetaDataTaggedTest() { String fileName = "addUAXMPMetaDataTaggedTest.pdf"; - PdfDocument pdf = new PdfDocument(new PdfWriter(destinationFolder + fileName, new WriterProperties().AddUAXmpMetadata - ())); + WriterProperties writerProperties = new WriterProperties().AddPdfUaXmpMetadata(PdfUAConformance.PDF_UA_1); + PdfDocument pdf = new PdfDocument(new PdfWriter(destinationFolder + fileName, writerProperties)); ManipulatePdf(pdf, true); NUnit.Framework.Assert.IsNull(new CompareTool().CompareXmp(destinationFolder + fileName, sourceFolder + "cmp_" + fileName, true)); diff --git a/itext.tests/itext.layout.tests/itext/layout/element/FlexContainerColumnTest.cs b/itext.tests/itext.layout.tests/itext/layout/element/FlexContainerColumnTest.cs index 01afece1ab..0bd568088d 100644 --- a/itext.tests/itext.layout.tests/itext/layout/element/FlexContainerColumnTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/element/FlexContainerColumnTest.cs @@ -22,7 +22,6 @@ You should have received a copy of the GNU Affero General Public License */ using System; using System.Collections.Generic; -using System.Linq; using iText.Commons.Utils; using iText.IO.Image; using iText.Kernel.Colors; @@ -37,7 +36,6 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Layout.Element { [NUnit.Framework.Category("IntegrationTest")] - [NUnit.Framework.TestFixtureSource("AlignItemsAndJustifyContentPropertiesTestFixtureData")] public class FlexContainerColumnTest : ExtendedITextTest { public static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext .CurrentContext.TestDirectory) + "/resources/itext/layout/FlexContainerColumnTest/"; @@ -45,34 +43,11 @@ public class FlexContainerColumnTest : ExtendedITextTest { public static readonly String DESTINATION_FOLDER = NUnit.Framework.TestContext.CurrentContext.TestDirectory + "/test/itext/layout/FlexContainerColumnTest/"; - private AlignmentPropertyValue alignItemsValue; - - private JustifyContent justifyContentValue; - - private FlexWrapPropertyValue wrapValue; - - private FlexDirectionPropertyValue directionValue; - - private int? comparisonPdfId; - [NUnit.Framework.OneTimeSetUp] public static void BeforeClass() { CreateDestinationFolder(DESTINATION_FOLDER); } - public FlexContainerColumnTest(Object alignItemsValue, Object justifyContentValue, Object wrapValue, Object - directionValue, Object comparisonPdfId) { - this.alignItemsValue = (AlignmentPropertyValue)alignItemsValue; - this.justifyContentValue = (JustifyContent)justifyContentValue; - this.wrapValue = (FlexWrapPropertyValue)wrapValue; - this.directionValue = (FlexDirectionPropertyValue)directionValue; - this.comparisonPdfId = (int?)comparisonPdfId; - } - - public FlexContainerColumnTest(Object[] array) - : this(array[0], array[1], array[2], array[3], array[4]) { - } - public static IEnumerable AlignItemsAndJustifyContentProperties() { return JavaUtil.ArraysAsList(new Object[][] { new Object[] { AlignmentPropertyValue.FLEX_END, JustifyContent .FLEX_END, FlexWrapPropertyValue.NOWRAP, FlexDirectionPropertyValue.COLUMN, 1 }, new Object[] { AlignmentPropertyValue @@ -86,20 +61,16 @@ public static IEnumerable AlignItemsAndJustifyContentProperties() { .CENTER, FlexWrapPropertyValue.WRAP_REVERSE, FlexDirectionPropertyValue.COLUMN_REVERSE, 7 } }); } - public static ICollection AlignItemsAndJustifyContentPropertiesTestFixtureData - () { - return AlignItemsAndJustifyContentProperties().Select(array => new NUnit.Framework.TestFixtureData(array)).ToList(); - } - - [NUnit.Framework.Test] - public virtual void DefaultFlexContainerTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void DefaultFlexContainerTest(AlignmentPropertyValue alignItemsValue, JustifyContent justifyContentValue + , FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue, int? comparisonPdfId) { String outFileName = DESTINATION_FOLDER + "defaultFlexContainerTest" + comparisonPdfId + ".pdf"; String cmpFileName = SOURCE_FOLDER + "cmp_defaultFlexContainerTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); flexContainer.SetProperty(Property.MARGIN_TOP, UnitValue.CreatePointValue(50)); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.PADDING_LEFT, UnitValue.CreatePointValue(40)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); Div innerDiv = new Div(); @@ -114,15 +85,17 @@ public virtual void DefaultFlexContainerTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void FlexContainerFixedHeightWidthTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void FlexContainerFixedHeightWidthTest(AlignmentPropertyValue alignItemsValue, JustifyContent + justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue, int? + comparisonPdfId) { String outFileName = DESTINATION_FOLDER + "flexContainerFixedHeightWidthTest" + comparisonPdfId + ".pdf"; String cmpFileName = SOURCE_FOLDER + "cmp_flexContainerFixedHeightWidthTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); flexContainer.SetProperty(Property.MARGIN_TOP, UnitValue.CreatePointValue(50)); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.PADDING_LEFT, UnitValue.CreatePointValue(40)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); flexContainer.SetProperty(Property.WIDTH, UnitValue.CreatePointValue(450)); @@ -140,14 +113,16 @@ public virtual void FlexContainerFixedHeightWidthTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void FlexContainerDifferentChildrenTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void FlexContainerDifferentChildrenTest(AlignmentPropertyValue alignItemsValue, JustifyContent + justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue, int? + comparisonPdfId) { String outFileName = DESTINATION_FOLDER + "flexContainerDifferentChildrenTest" + comparisonPdfId + ".pdf"; String cmpFileName = SOURCE_FOLDER + "cmp_flexContainerDifferentChildrenTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); Div innerDiv = new Div(); innerDiv.Add(CreateNewDiv()).Add(CreateNewDiv()).Add(CreateNewDiv()); @@ -167,17 +142,19 @@ public virtual void FlexContainerDifferentChildrenTest() { , "diff")); } - [NUnit.Framework.Test] + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] [LogMessage(LayoutLogMessageConstant.ELEMENT_DOES_NOT_FIT_AREA, Ignore = true)] - public virtual void FlexContainerDifferentChildrenDontFitVerticallyTest() { + public virtual void FlexContainerDifferentChildrenDontFitVerticallyTest(AlignmentPropertyValue alignItemsValue + , JustifyContent justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue + , int? comparisonPdfId) { String outFileName = DESTINATION_FOLDER + "flexContainerDifferentChildrenDontFitHorizontallyTest" + comparisonPdfId + ".pdf"; String cmpFileName = SOURCE_FOLDER + "cmp_flexContainerDifferentChildrenDontFitHorizontallyTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); flexContainer.SetProperty(Property.HEIGHT, UnitValue.CreatePointValue(300)); Div innerDiv = new Div(); @@ -197,16 +174,18 @@ public virtual void FlexContainerDifferentChildrenDontFitVerticallyTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void FlexContainerDifferentChildrenWithGrowTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void FlexContainerDifferentChildrenWithGrowTest(AlignmentPropertyValue alignItemsValue, JustifyContent + justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue, int? + comparisonPdfId) { String outFileName = DESTINATION_FOLDER + "flexContainerDifferentChildrenWithGrowTest" + comparisonPdfId + ".pdf"; String cmpFileName = SOURCE_FOLDER + "cmp_flexContainerDifferentChildrenWithGrowTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); Div innerDiv = new Div(); innerDiv.Add(CreateNewDiv()).Add(CreateNewDiv()).Add(CreateNewDiv()); @@ -231,16 +210,18 @@ public virtual void FlexContainerDifferentChildrenWithGrowTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void FlexContainerDifferentChildrenWithFlexBasisTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void FlexContainerDifferentChildrenWithFlexBasisTest(AlignmentPropertyValue alignItemsValue + , JustifyContent justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue + , int? comparisonPdfId) { String outFileName = DESTINATION_FOLDER + "flexContainerDifferentChildrenWithFlexBasisTest" + comparisonPdfId + ".pdf"; String cmpFileName = SOURCE_FOLDER + "cmp_flexContainerDifferentChildrenWithFlexBasisTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); Table table = new Table(UnitValue.CreatePercentArray(new float[] { 50, 50 })); for (int i = 0; i < 2; i++) { @@ -261,17 +242,19 @@ public virtual void FlexContainerDifferentChildrenWithFlexBasisTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void FlexContainerDifferentChildrenWithFlexShrinkTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void FlexContainerDifferentChildrenWithFlexShrinkTest(AlignmentPropertyValue alignItemsValue + , JustifyContent justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue + , int? comparisonPdfId) { String outFileName = DESTINATION_FOLDER + "flexContainerDifferentChildrenWithFlexShrinkTest" + comparisonPdfId + ".pdf"; String cmpFileName = SOURCE_FOLDER + "cmp_flexContainerDifferentChildrenWithFlexShrinkTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); flexContainer.SetHeight(450); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); Table table = new Table(UnitValue.CreatePercentArray(new float[] { 50, 50 })); for (int i = 0; i < 2; i++) { @@ -294,14 +277,16 @@ public virtual void FlexContainerDifferentChildrenWithFlexShrinkTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void FlexContainerInsideFlexContainerTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void FlexContainerInsideFlexContainerTest(AlignmentPropertyValue alignItemsValue, JustifyContent + justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue, int? + comparisonPdfId) { String outFileName = DESTINATION_FOLDER + "flexContainerInsideFlexContainerTest" + comparisonPdfId + ".pdf"; String cmpFileName = SOURCE_FOLDER + "cmp_flexContainerInsideFlexContainerTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); Div innerFlex = new FlexContainer(); innerFlex.SetProperty(Property.FLEX_DIRECTION, FlexDirectionPropertyValue.COLUMN); @@ -318,16 +303,18 @@ public virtual void FlexContainerInsideFlexContainerTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void MultipleFlexContainersInsideFlexContainerTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void MultipleFlexContainersInsideFlexContainerTest(AlignmentPropertyValue alignItemsValue, + JustifyContent justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue + , int? comparisonPdfId) { String outFileName = DESTINATION_FOLDER + "multipleFlexContainersInsideFlexContainerTest" + comparisonPdfId + ".pdf"; String cmpFileName = SOURCE_FOLDER + "cmp_multipleFlexContainersInsideFlexContainerTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); Div innerFlex1 = new FlexContainer(); innerFlex1.SetProperty(Property.FLEX_DIRECTION, FlexDirectionPropertyValue.COLUMN); @@ -352,14 +339,16 @@ public virtual void MultipleFlexContainersInsideFlexContainerTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void FlexContainerRotationAngleTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void FlexContainerRotationAngleTest(AlignmentPropertyValue alignItemsValue, JustifyContent + justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue, int? + comparisonPdfId) { String outFileName = DESTINATION_FOLDER + "flexContainerRotationAngleTest" + comparisonPdfId + ".pdf"; String cmpFileName = SOURCE_FOLDER + "cmp_flexContainerRotationAngleTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); flexContainer.SetProperty(Property.ROTATION_ANGLE, 20f); Table table = new Table(UnitValue.CreatePercentArray(new float[] { 10, 10, 10 })); @@ -377,14 +366,15 @@ public virtual void FlexContainerRotationAngleTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void FlexItemBoxSizingTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void FlexItemBoxSizingTest(AlignmentPropertyValue alignItemsValue, JustifyContent justifyContentValue + , FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue, int? comparisonPdfId) { String outFileName = DESTINATION_FOLDER + "flexItemBoxSizingTest" + comparisonPdfId + ".pdf"; String cmpFileName = SOURCE_FOLDER + "cmp_flexItemBoxSizingTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(ColorConstants.BLUE, 30)); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); + flexContainer.SetBorder(new SolidBorder(ColorConstants.BLUE, 30)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); flexContainer.SetWidth(250); flexContainer.SetHeight(400); @@ -418,14 +408,15 @@ public virtual void FlexItemBoxSizingTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void FlexContainerBoxSizingTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void FlexContainerBoxSizingTest(AlignmentPropertyValue alignItemsValue, JustifyContent justifyContentValue + , FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue, int? comparisonPdfId) { String outFileName = DESTINATION_FOLDER + "flexContainerBoxSizingTest" + comparisonPdfId + ".pdf"; String cmpFileName = SOURCE_FOLDER + "cmp_flexContainerBoxSizingTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(ColorConstants.BLUE, 30)); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); + flexContainer.SetBorder(new SolidBorder(ColorConstants.BLUE, 30)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); flexContainer.SetWidth(450); flexContainer.SetProperty(Property.BOX_SIZING, BoxSizingPropertyValue.BORDER_BOX); @@ -443,13 +434,14 @@ public virtual void FlexContainerBoxSizingTest() { , "diff")); } - [NUnit.Framework.Test] + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] [LogMessage(LayoutLogMessageConstant.ELEMENT_DOES_NOT_FIT_AREA, Ignore = true)] - public virtual void FlexContainerPaginationTest() { + public virtual void FlexContainerPaginationTest(AlignmentPropertyValue alignItemsValue, JustifyContent justifyContentValue + , FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue, int? comparisonPdfId) { String outFileName = DESTINATION_FOLDER + "flexContainerPaginationTest" + comparisonPdfId + ".pdf"; String cmpFileName = SOURCE_FOLDER + "cmp_flexContainerPaginationTest" + comparisonPdfId + ".pdf"; using (Document document = new Document(new PdfDocument(new PdfWriter(outFileName)))) { - Div flexContainer = CreateFlexContainer(); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); flexContainer.DeleteOwnProperty(Property.HEIGHT); flexContainer.SetBorder(new SolidBorder(ColorConstants.BLUE, 10)); flexContainer.Add(CreateNewDiv().Add(new Paragraph("1"))).Add(CreateNewDiv().Add(new Paragraph("2")).SetWidth @@ -466,12 +458,14 @@ public virtual void FlexContainerPaginationTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void FlexContainerWithFixedHeightPaginationTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void FlexContainerWithFixedHeightPaginationTest(AlignmentPropertyValue alignItemsValue, JustifyContent + justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue, int? + comparisonPdfId) { String outFileName = DESTINATION_FOLDER + "flexContainerWithFixedHeightPagination" + comparisonPdfId + ".pdf"; String cmpFileName = SOURCE_FOLDER + "cmp_flexContainerWithFixedHeightPagination" + comparisonPdfId + ".pdf"; using (Document document = new Document(new PdfDocument(new PdfWriter(outFileName)))) { - Div flexContainer = CreateFlexContainer(); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); flexContainer.SetHeight(1000); flexContainer.SetBorder(new SolidBorder(ColorConstants.PINK, 10)); flexContainer.Add(CreateNewDiv().Add(new Paragraph("1"))).Add(CreateNewDiv().Add(new Paragraph("2")).SetWidth @@ -487,14 +481,16 @@ public virtual void FlexContainerWithFixedHeightPaginationTest() { , "diff")); } - [NUnit.Framework.Test] + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] [LogMessage(iText.IO.Logs.IoLogMessageConstant.CLIP_ELEMENT, Ignore = true)] - public virtual void FlexContainerInsideDivPaginationTest() { + public virtual void FlexContainerInsideDivPaginationTest(AlignmentPropertyValue alignItemsValue, JustifyContent + justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue, int? + comparisonPdfId) { String outFileName = DESTINATION_FOLDER + "flexContainerInsideDivPaginationTest" + comparisonPdfId + ".pdf"; String cmpFileName = SOURCE_FOLDER + "cmp_flexContainerInsideDivPaginationTest" + comparisonPdfId + ".pdf"; using (Document document = new Document(new PdfDocument(new PdfWriter(outFileName)))) { Div div = new Div().SetHeight(1800).SetWidth(350).SetBorder(new SolidBorder(ColorConstants.RED, 20)); - Div flexContainer = CreateFlexContainer(); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); flexContainer.DeleteOwnProperty(Property.HEIGHT); flexContainer.SetBorder(new SolidBorder(ColorConstants.BLUE, 10)); flexContainer.Add(CreateNewDiv().Add(new Paragraph("1"))).Add(CreateNewDiv().Add(new Paragraph("2")).SetWidth @@ -512,14 +508,15 @@ public virtual void FlexContainerInsideDivPaginationTest() { , "diff")); } - [NUnit.Framework.Test] + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] [LogMessage(iText.IO.Logs.IoLogMessageConstant.CLIP_ELEMENT, Ignore = true)] - public virtual void FlexContainerInsideDivTest() { + public virtual void FlexContainerInsideDivTest(AlignmentPropertyValue alignItemsValue, JustifyContent justifyContentValue + , FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue, int? comparisonPdfId) { String outFileName = DESTINATION_FOLDER + "flexContainerInsideDivTest" + comparisonPdfId + ".pdf"; String cmpFileName = SOURCE_FOLDER + "cmp_flexContainerInsideDivTest" + comparisonPdfId + ".pdf"; using (Document document = new Document(new PdfDocument(new PdfWriter(outFileName)))) { Div div = new Div().SetHeight(400).SetWidth(140).SetBorder(new SolidBorder(ColorConstants.PINK, 10)); - Div flexContainer = CreateFlexContainer(); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); flexContainer.DeleteOwnProperty(Property.HEIGHT); flexContainer.SetBorder(new SolidBorder(ColorConstants.YELLOW, 5)); flexContainer.Add(CreateNewDiv().Add(new Paragraph("1"))).Add(CreateNewDiv().Add(new Paragraph("2"))).Add( @@ -534,7 +531,8 @@ public virtual void FlexContainerInsideDivTest() { , "diff")); } - private FlexContainer CreateFlexContainer() { + private FlexContainer CreateFlexContainer(AlignmentPropertyValue alignItemsValue, JustifyContent justifyContentValue + , FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue) { FlexContainer flexContainer = new FlexContainer(); flexContainer.SetProperty(Property.ALIGN_ITEMS, alignItemsValue); flexContainer.SetProperty(Property.JUSTIFY_CONTENT, justifyContentValue); @@ -548,7 +546,7 @@ private FlexContainer CreateFlexContainer() { private static Div CreateNewDiv() { Div newDiv = new Div(); - newDiv.SetProperty(Property.BORDER, new SolidBorder(1)); + newDiv.SetBorder(new SolidBorder(1)); newDiv.SetProperty(Property.WIDTH, UnitValue.CreatePointValue(50)); newDiv.SetProperty(Property.HEIGHT, UnitValue.CreatePointValue(100)); return newDiv; diff --git a/itext.tests/itext.layout.tests/itext/layout/element/FlexContainerSplitTest.cs b/itext.tests/itext.layout.tests/itext/layout/element/FlexContainerSplitTest.cs index 5e11e384d9..05a6ca5fb0 100644 --- a/itext.tests/itext.layout.tests/itext/layout/element/FlexContainerSplitTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/element/FlexContainerSplitTest.cs @@ -200,7 +200,7 @@ public virtual void ReverseWrapStartTest() { } [NUnit.Framework.Test] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.TYPOGRAPHY_NOT_FOUND, Count = 556)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.TYPOGRAPHY_NOT_FOUND, Count = 553)] public virtual void RowWrapRtlStartTest() { String outFileName = DESTINATION_FOLDER + "rowWrapRtlStartTest.pdf"; String cmpFileName = SOURCE_FOLDER + "cmp_rowWrapRtlStartTest.pdf"; @@ -219,7 +219,7 @@ public virtual void RowWrapRtlStartTest() { } [NUnit.Framework.Test] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.TYPOGRAPHY_NOT_FOUND, Count = 556)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.TYPOGRAPHY_NOT_FOUND, Count = 553)] public virtual void ReverseRowWrapRtlStartTest() { String outFileName = DESTINATION_FOLDER + "reverseRowWrapRtlStartTest.pdf"; String cmpFileName = SOURCE_FOLDER + "cmp_reverseRowWrapRtlStartTest.pdf"; @@ -308,9 +308,33 @@ public virtual void SimpleWrapCenterTest() { , "diff")); } + [NUnit.Framework.Test] + public virtual void TableInFlexOnSplitTest() { + String outFileName = DESTINATION_FOLDER + "tableInFlexOnSplitTest.pdf"; + String cmpFileName = SOURCE_FOLDER + "tableInFlexOnSplitTest.pdf"; + using (PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName))) { + Document document = new Document(pdfDocument); + pdfDocument.SetDefaultPageSize(PageSize.A5); + Div flexContainer = new FlexContainer(); + flexContainer.SetBackgroundColor(ColorConstants.LIGHT_GRAY); + flexContainer.SetBorder(new SolidBorder(2)); + Table table = new Table(UnitValue.CreatePercentArray(new float[] { 10, 10, 10 })); + for (int i = 1; i <= 3; i++) { + table.AddHeaderCell("Header" + i); + } + for (int i = 1; i <= 150; i++) { + table.AddCell("Cell" + i); + } + flexContainer.Add(table); + document.Add(flexContainer); + } + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER + , "diff")); + } + private Div CreateDefaultFlexContainer() { Div flexContainer = new FlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); Paragraph p1 = new Paragraph(SHORT_TEXT).SetWidth(UnitValue.CreatePercentValue(25)).SetBackgroundColor(ColorConstants .BLUE); @@ -327,7 +351,7 @@ private Div CreateDefaultFlexContainer() { private Div CreateDefaultFlexContainerForWrap() { Div flexContainer = new FlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); Paragraph p1 = new Paragraph(SHORT_TEXT).SetWidth(UnitValue.CreatePercentValue(20)).SetBackgroundColor(ColorConstants .BLUE); diff --git a/itext.tests/itext.layout.tests/itext/layout/element/FlexContainerTest.cs b/itext.tests/itext.layout.tests/itext/layout/element/FlexContainerTest.cs index 39f6d40538..2d7f293004 100644 --- a/itext.tests/itext.layout.tests/itext/layout/element/FlexContainerTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/element/FlexContainerTest.cs @@ -22,7 +22,6 @@ You should have received a copy of the GNU Affero General Public License */ using System; using System.Collections.Generic; -using System.Linq; using iText.Commons.Utils; using iText.IO.Image; using iText.Kernel.Colors; @@ -37,7 +36,6 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Layout.Element { [NUnit.Framework.Category("IntegrationTest")] - [NUnit.Framework.TestFixtureSource("AlignItemsAndJustifyContentPropertiesTestFixtureData")] public class FlexContainerTest : ExtendedITextTest { public static readonly String sourceFolder = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext .CurrentContext.TestDirectory) + "/resources/itext/layout/FlexContainerTest/"; @@ -45,34 +43,11 @@ public class FlexContainerTest : ExtendedITextTest { public static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory + "/test/itext/layout/FlexContainerTest/"; - private AlignmentPropertyValue alignItemsValue; - - private JustifyContent justifyContentValue; - - private FlexWrapPropertyValue wrapValue; - - private FlexDirectionPropertyValue directionValue; - - private int? comparisonPdfId; - [NUnit.Framework.OneTimeSetUp] public static void BeforeClass() { CreateDestinationFolder(destinationFolder); } - public FlexContainerTest(Object alignItemsValue, Object justifyContentValue, Object wrapValue, Object directionValue - , Object comparisonPdfId) { - this.alignItemsValue = (AlignmentPropertyValue)alignItemsValue; - this.justifyContentValue = (JustifyContent)justifyContentValue; - this.wrapValue = (FlexWrapPropertyValue)wrapValue; - this.directionValue = (FlexDirectionPropertyValue)directionValue; - this.comparisonPdfId = (int?)comparisonPdfId; - } - - public FlexContainerTest(Object[] array) - : this(array[0], array[1], array[2], array[3], array[4]) { - } - public static IEnumerable AlignItemsAndJustifyContentProperties() { return JavaUtil.ArraysAsList(new Object[][] { new Object[] { AlignmentPropertyValue.FLEX_START, JustifyContent .FLEX_START, FlexWrapPropertyValue.NOWRAP, FlexDirectionPropertyValue.ROW, 1 }, new Object[] { AlignmentPropertyValue @@ -93,20 +68,16 @@ public static IEnumerable AlignItemsAndJustifyContentProperties() { .ROW, 12 } }); } - public static ICollection AlignItemsAndJustifyContentPropertiesTestFixtureData - () { - return AlignItemsAndJustifyContentProperties().Select(array => new NUnit.Framework.TestFixtureData(array)).ToList(); - } - - [NUnit.Framework.Test] - public virtual void DefaultFlexContainerTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void DefaultFlexContainerTest(AlignmentPropertyValue alignItemsValue, JustifyContent justifyContentValue + , FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue, int? comparisonPdfId) { String outFileName = destinationFolder + "defaultFlexContainerTest" + comparisonPdfId + ".pdf"; String cmpFileName = sourceFolder + "cmp_defaultFlexContainerTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); flexContainer.SetProperty(Property.MARGIN_TOP, UnitValue.CreatePointValue(50)); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.PADDING_LEFT, UnitValue.CreatePointValue(40)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); Div innerDiv = new Div(); @@ -120,15 +91,17 @@ public virtual void DefaultFlexContainerTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void FlexContainerFixedHeightWidthTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void FlexContainerFixedHeightWidthTest(AlignmentPropertyValue alignItemsValue, JustifyContent + justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue, int? + comparisonPdfId) { String outFileName = destinationFolder + "flexContainerFixedHeightWidthTest" + comparisonPdfId + ".pdf"; String cmpFileName = sourceFolder + "cmp_flexContainerFixedHeightWidthTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); flexContainer.SetProperty(Property.MARGIN_TOP, UnitValue.CreatePointValue(50)); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.PADDING_LEFT, UnitValue.CreatePointValue(40)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); flexContainer.SetProperty(Property.WIDTH, UnitValue.CreatePointValue(450)); @@ -144,14 +117,16 @@ public virtual void FlexContainerFixedHeightWidthTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void FlexContainerDifferentChildrenTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void FlexContainerDifferentChildrenTest(AlignmentPropertyValue alignItemsValue, JustifyContent + justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue, int? + comparisonPdfId) { String outFileName = destinationFolder + "flexContainerDifferentChildrenTest" + comparisonPdfId + ".pdf"; String cmpFileName = sourceFolder + "cmp_flexContainerDifferentChildrenTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); Div innerDiv = new Div(); innerDiv.Add(CreateNewDiv()).Add(CreateNewDiv()).Add(CreateNewDiv()); @@ -171,16 +146,18 @@ public virtual void FlexContainerDifferentChildrenTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void FlexContainerHeightClippedTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void FlexContainerHeightClippedTest(AlignmentPropertyValue alignItemsValue, JustifyContent + justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue, int? + comparisonPdfId) { // If height is clipped the behavior strongly depends on the child renderers // and the results are not expected sometimes String outFileName = destinationFolder + "flexContainerHeightClippedTest" + comparisonPdfId + ".pdf"; String cmpFileName = sourceFolder + "cmp_flexContainerHeightClippedTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); flexContainer.SetHeight(250); Div innerDiv = new Div(); @@ -201,9 +178,11 @@ public virtual void FlexContainerHeightClippedTest() { , "diff")); } - [NUnit.Framework.Test] + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] [LogMessage(LayoutLogMessageConstant.ELEMENT_DOES_NOT_FIT_AREA, Ignore = true)] - public virtual void FlexContainerDifferentChildrenDontFitHorizontallyTest() { + public virtual void FlexContainerDifferentChildrenDontFitHorizontallyTest(AlignmentPropertyValue alignItemsValue + , JustifyContent justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue + , int? comparisonPdfId) { // TODO DEVSIX-5042 HEIGHT property is ignored when FORCED_PLACEMENT is true String outFileName = destinationFolder + "flexContainerDifferentChildrenDontFitHorizontallyTest" + comparisonPdfId + ".pdf"; @@ -211,8 +190,8 @@ public virtual void FlexContainerDifferentChildrenDontFitHorizontallyTest() { + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); flexContainer.SetProperty(Property.WIDTH, UnitValue.CreatePointValue(300)); Div innerDiv = new Div(); @@ -232,8 +211,10 @@ public virtual void FlexContainerDifferentChildrenDontFitHorizontallyTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void FlexContainerDifferentChildrenDontFitHorizontallyForcedPlacementTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void FlexContainerDifferentChildrenDontFitHorizontallyForcedPlacementTest(AlignmentPropertyValue + alignItemsValue, JustifyContent justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue + directionValue, int? comparisonPdfId) { // TODO DEVSIX-5042 HEIGHT property is ignored when FORCED_PLACEMENT is true String outFileName = destinationFolder + "flexContainerDifferentChildrenDontFitHorizontallyForcedPlacementTest" + comparisonPdfId + ".pdf"; @@ -241,8 +222,8 @@ public virtual void FlexContainerDifferentChildrenDontFitHorizontallyForcedPlace + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); flexContainer.SetProperty(Property.FORCED_PLACEMENT, true); Div innerDiv = new Div(); @@ -262,17 +243,19 @@ public virtual void FlexContainerDifferentChildrenDontFitHorizontallyForcedPlace , "diff")); } - [NUnit.Framework.Test] + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] [LogMessage(iText.IO.Logs.IoLogMessageConstant.CLIP_ELEMENT, Ignore = true)] - public virtual void FlexContainerDifferentChildrenDontFitVerticallyTest() { + public virtual void FlexContainerDifferentChildrenDontFitVerticallyTest(AlignmentPropertyValue alignItemsValue + , JustifyContent justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue + , int? comparisonPdfId) { String outFileName = destinationFolder + "flexContainerDifferentChildrenDontFitVerticallyTest" + comparisonPdfId + ".pdf"; String cmpFileName = sourceFolder + "cmp_flexContainerDifferentChildrenDontFitVerticallyTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); flexContainer.SetHeight(500); Div innerDiv = new Div(); @@ -296,17 +279,19 @@ public virtual void FlexContainerDifferentChildrenDontFitVerticallyTest() { , "diff")); } - [NUnit.Framework.Test] + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] [LogMessage(iText.IO.Logs.IoLogMessageConstant.CLIP_ELEMENT, Ignore = true)] - public virtual void FlexContainerDifferentChildrenFitContainerDoesNotFitVerticallyTest() { + public virtual void FlexContainerDifferentChildrenFitContainerDoesNotFitVerticallyTest(AlignmentPropertyValue + alignItemsValue, JustifyContent justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue + directionValue, int? comparisonPdfId) { String outFileName = destinationFolder + "flexContainerDifferentChildrenFitContainerDoesNotFitVerticallyTest" + comparisonPdfId + ".pdf"; String cmpFileName = sourceFolder + "cmp_flexContainerDifferentChildrenFitContainerDoesNotFitVerticallyTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); flexContainer.SetHeight(600); Div innerDiv = new Div(); @@ -330,15 +315,17 @@ public virtual void FlexContainerDifferentChildrenFitContainerDoesNotFitVertical , "diff")); } - [NUnit.Framework.Test] - public virtual void FlexContainerDifferentChildrenWithGrowTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void FlexContainerDifferentChildrenWithGrowTest(AlignmentPropertyValue alignItemsValue, JustifyContent + justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue, int? + comparisonPdfId) { String outFileName = destinationFolder + "flexContainerDifferentChildrenWithGrowTest" + comparisonPdfId + ".pdf"; String cmpFileName = sourceFolder + "cmp_flexContainerDifferentChildrenWithGrowTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); Div innerDiv = new Div(); innerDiv.Add(CreateNewDiv()).Add(CreateNewDiv()).Add(CreateNewDiv()); @@ -363,16 +350,18 @@ public virtual void FlexContainerDifferentChildrenWithGrowTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void FlexContainerDifferentChildrenWithFlexBasisTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void FlexContainerDifferentChildrenWithFlexBasisTest(AlignmentPropertyValue alignItemsValue + , JustifyContent justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue + , int? comparisonPdfId) { String outFileName = destinationFolder + "flexContainerDifferentChildrenWithFlexBasisTest" + comparisonPdfId + ".pdf"; String cmpFileName = sourceFolder + "cmp_flexContainerDifferentChildrenWithFlexBasisTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); Table table = new Table(UnitValue.CreatePercentArray(new float[] { 50, 50 })); for (int i = 0; i < 2; i++) { @@ -393,16 +382,18 @@ public virtual void FlexContainerDifferentChildrenWithFlexBasisTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void FlexContainerDifferentChildrenWithFlexShrinkTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void FlexContainerDifferentChildrenWithFlexShrinkTest(AlignmentPropertyValue alignItemsValue + , JustifyContent justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue + , int? comparisonPdfId) { String outFileName = destinationFolder + "flexContainerDifferentChildrenWithFlexShrinkTest" + comparisonPdfId + ".pdf"; String cmpFileName = sourceFolder + "cmp_flexContainerDifferentChildrenWithFlexShrinkTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); Table table = new Table(UnitValue.CreatePercentArray(new float[] { 50, 50 })); for (int i = 0; i < 2; i++) { @@ -425,14 +416,16 @@ public virtual void FlexContainerDifferentChildrenWithFlexShrinkTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void FlexContainerInsideFlexContainerTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void FlexContainerInsideFlexContainerTest(AlignmentPropertyValue alignItemsValue, JustifyContent + justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue, int? + comparisonPdfId) { String outFileName = destinationFolder + "flexContainerInsideFlexContainerTest" + comparisonPdfId + ".pdf"; String cmpFileName = sourceFolder + "cmp_flexContainerInsideFlexContainerTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); Div innerFlex = new FlexContainer(); innerFlex.Add(CreateNewDiv()).Add(CreateNewDiv()).Add(CreateNewDiv()); @@ -448,26 +441,32 @@ public virtual void FlexContainerInsideFlexContainerTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void FlexContainerInsideFlexContainerWithHugeBordersTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void FlexContainerInsideFlexContainerWithHugeBordersTest(AlignmentPropertyValue alignItemsValue + , JustifyContent justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue + , int? comparisonPdfId) { String outFileName = destinationFolder + "flexContainerInsideFlexContainerWithHugeBordersTest" + comparisonPdfId + ".pdf"; String cmpFileName = sourceFolder + "cmp_flexContainerInsideFlexContainerWithHugeBordersTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(ColorConstants.BLUE, 20)); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); + flexContainer.SetBorder(new SolidBorder(ColorConstants.BLUE, 20)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); Div innerFlex = new FlexContainer(); innerFlex.Add(CreateNewDiv()).Add(CreateNewDiv()).Add(CreateNewDiv()); foreach (IElement children in innerFlex.GetChildren()) { children.SetProperty(Property.FLEX_GROW, 1f); - children.SetProperty(Property.BORDER, new SolidBorder(ColorConstants.YELLOW, 10)); + SolidBorder border = new SolidBorder(ColorConstants.YELLOW, 10); + children.SetProperty(Property.BORDER_TOP, border); + children.SetProperty(Property.BORDER_RIGHT, border); + children.SetProperty(Property.BORDER_BOTTOM, border); + children.SetProperty(Property.BORDER_LEFT, border); } innerFlex.SetProperty(Property.BACKGROUND, new Background(ColorConstants.RED)); innerFlex.SetProperty(Property.FLEX_GROW, 1f); - innerFlex.SetProperty(Property.BORDER, new SolidBorder(ColorConstants.RED, 15)); + innerFlex.SetBorder(new SolidBorder(ColorConstants.RED, 15)); flexContainer.Add(innerFlex).Add(CreateNewDiv().SetBorder(new SolidBorder(ColorConstants.GREEN, 10))); document.Add(flexContainer); document.Close(); @@ -475,16 +474,18 @@ public virtual void FlexContainerInsideFlexContainerWithHugeBordersTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void MultipleFlexContainersInsideFlexContainerTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void MultipleFlexContainersInsideFlexContainerTest(AlignmentPropertyValue alignItemsValue, + JustifyContent justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue + , int? comparisonPdfId) { String outFileName = destinationFolder + "multipleFlexContainersInsideFlexContainerTest" + comparisonPdfId + ".pdf"; String cmpFileName = sourceFolder + "cmp_multipleFlexContainersInsideFlexContainerTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); Div innerFlex1 = new FlexContainer(); innerFlex1.Add(CreateNewDiv()).Add(CreateNewDiv()).Add(CreateNewDiv()); @@ -507,16 +508,18 @@ public virtual void MultipleFlexContainersInsideFlexContainerTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void MultipleFlexContainersWithPredefinedPointWidthsInsideFlexContainerTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void MultipleFlexContainersWithPredefinedPointWidthsInsideFlexContainerTest(AlignmentPropertyValue + alignItemsValue, JustifyContent justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue + directionValue, int? comparisonPdfId) { String outFileName = destinationFolder + "multipleFlexContainersWithPredefinedPointWidthsInsideFlexContainerTest" + comparisonPdfId + ".pdf"; String cmpFileName = sourceFolder + "cmp_multipleFlexContainersWithPredefinedPointWidthsInsideFlexContainerTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); Div innerFlex1 = new FlexContainer(); innerFlex1.Add(CreateNewDiv()).Add(CreateNewDiv()).Add(CreateNewDiv()); @@ -541,16 +544,18 @@ public virtual void MultipleFlexContainersWithPredefinedPointWidthsInsideFlexCon , "diff")); } - [NUnit.Framework.Test] - public virtual void MultipleFlexContainersWithPredefinedPercentWidthsInsideFlexContainerTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void MultipleFlexContainersWithPredefinedPercentWidthsInsideFlexContainerTest(AlignmentPropertyValue + alignItemsValue, JustifyContent justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue + directionValue, int? comparisonPdfId) { String outFileName = destinationFolder + "multipleFlexContainersWithPredefinedPercentWidthsInsideFlexContainerTest" + comparisonPdfId + ".pdf"; String cmpFileName = sourceFolder + "cmp_multipleFlexContainersWithPredefinedPercentWidthsInsideFlexContainerTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); Div innerFlex1 = new FlexContainer(); innerFlex1.Add(CreateNewDiv()).Add(CreateNewDiv()).Add(CreateNewDiv()); @@ -575,8 +580,10 @@ public virtual void MultipleFlexContainersWithPredefinedPercentWidthsInsideFlexC , "diff")); } - [NUnit.Framework.Test] - public virtual void MultipleFlexContainersWithPredefinedMinWidthsInsideFlexContainerTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void MultipleFlexContainersWithPredefinedMinWidthsInsideFlexContainerTest(AlignmentPropertyValue + alignItemsValue, JustifyContent justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue + directionValue, int? comparisonPdfId) { // TODO DEVSIX-5087 Content should not overflow container by default String outFileName = destinationFolder + "multipleFlexContainersWithPredefinedMinWidthsInsideFlexContainerTest" + comparisonPdfId + ".pdf"; @@ -584,8 +591,8 @@ public virtual void MultipleFlexContainersWithPredefinedMinWidthsInsideFlexConta + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); Div innerFlex1 = new FlexContainer(); innerFlex1.Add(CreateNewDiv()).Add(CreateNewDiv()).Add(CreateNewDiv()); @@ -610,16 +617,18 @@ public virtual void MultipleFlexContainersWithPredefinedMinWidthsInsideFlexConta , "diff")); } - [NUnit.Framework.Test] - public virtual void MultipleFlexContainersWithPredefinedMaxWidthsInsideFlexContainerTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void MultipleFlexContainersWithPredefinedMaxWidthsInsideFlexContainerTest(AlignmentPropertyValue + alignItemsValue, JustifyContent justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue + directionValue, int? comparisonPdfId) { String outFileName = destinationFolder + "multipleFlexContainersWithPredefinedMaxWidthsInsideFlexContainerTest" + comparisonPdfId + ".pdf"; String cmpFileName = sourceFolder + "cmp_multipleFlexContainersWithPredefinedMaxWidthsInsideFlexContainerTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); Div innerFlex1 = new FlexContainer(); innerFlex1.Add(CreateNewDiv()).Add(CreateNewDiv()).Add(CreateNewDiv()); @@ -644,14 +653,16 @@ public virtual void MultipleFlexContainersWithPredefinedMaxWidthsInsideFlexConta , "diff")); } - [NUnit.Framework.Test] - public virtual void FlexContainerFillAvailableAreaTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void FlexContainerFillAvailableAreaTest(AlignmentPropertyValue alignItemsValue, JustifyContent + justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue, int? + comparisonPdfId) { String outFileName = destinationFolder + "flexContainerFillAvailableAreaTest" + comparisonPdfId + ".pdf"; String cmpFileName = sourceFolder + "cmp_flexContainerFillAvailableAreaTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); flexContainer.SetProperty(Property.FILL_AVAILABLE_AREA, true); Div innerDiv = new Div(); @@ -672,14 +683,16 @@ public virtual void FlexContainerFillAvailableAreaTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void FlexContainerRotationAngleTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void FlexContainerRotationAngleTest(AlignmentPropertyValue alignItemsValue, JustifyContent + justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue, int? + comparisonPdfId) { String outFileName = destinationFolder + "flexContainerRotationAngleTest" + comparisonPdfId + ".pdf"; String cmpFileName = sourceFolder + "cmp_flexContainerRotationAngleTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); flexContainer.SetProperty(Property.ROTATION_ANGLE, 20f); Table table = new Table(UnitValue.CreatePercentArray(new float[] { 10, 10, 10 })); @@ -697,15 +710,18 @@ public virtual void FlexContainerRotationAngleTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void RespectFlexContainersHeightTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void RespectFlexContainersHeightTest(AlignmentPropertyValue alignItemsValue, JustifyContent + justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue, int? + comparisonPdfId) { // TODO DEVSIX-5174 content should overflow bottom String outFileName = destinationFolder + "respectFlexContainersHeightTest" + comparisonPdfId + ".pdf"; String cmpFileName = sourceFolder + "cmp_respectFlexContainersHeightTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); Style containerStyle = new Style().SetWidth(60).SetHeight(50); - Div flexContainer = GetFlexContainer(null, containerStyle); + Div flexContainer = GetFlexContainer(null, containerStyle, alignItemsValue, justifyContentValue, wrapValue + , directionValue); Div flexItem = new Div().SetBackgroundColor(ColorConstants.BLUE).Add(new Paragraph("h")).Add(new Paragraph ("e")).Add(new Paragraph("l")).Add(new Paragraph("l")).Add(new Paragraph("o")).Add(new Paragraph("w")) .Add(new Paragraph("o")).Add(new Paragraph("r")).Add(new Paragraph("l")).Add(new Paragraph("d")); @@ -717,8 +733,10 @@ public virtual void RespectFlexContainersHeightTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void RespectFlexContainersWidthTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void RespectFlexContainersWidthTest(AlignmentPropertyValue alignItemsValue, JustifyContent + justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue, int? + comparisonPdfId) { String outFileName = destinationFolder + "respectFlexContainersWidthTest" + comparisonPdfId + ".pdf"; String cmpFileName = sourceFolder + "cmp_respectFlexContainersWidthTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); @@ -727,13 +745,15 @@ public virtual void RespectFlexContainersWidthTest() { OverflowPropertyValue? overflowX = null; Style containerStyle = new Style().SetWidth(60).SetHeight(200); Style itemStyle = new Style().SetWidth(60f).SetHeight(100f); - Div flexContainer = GetFlexContainer(overflowX, containerStyle); + Div flexContainer = GetFlexContainer(overflowX, containerStyle, alignItemsValue, justifyContentValue, wrapValue + , directionValue); flexContainer.Add(GetFlexItem(overflowX, itemStyle)).Add(GetFlexItem(overflowX, itemStyle)); document.Add(flexContainer); document.Add(new AreaBreak()); // default (overflow visible) overflowX = OverflowPropertyValue.VISIBLE; - flexContainer = GetFlexContainer(overflowX, containerStyle); + flexContainer = GetFlexContainer(overflowX, containerStyle, alignItemsValue, justifyContentValue, wrapValue + , directionValue); flexContainer.Add(GetFlexItem(overflowX, itemStyle)).Add(GetFlexItem(overflowX, itemStyle)); document.Add(flexContainer); document.Close(); @@ -741,13 +761,15 @@ public virtual void RespectFlexContainersWidthTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void FlexItemsMinHeightShouldBeOverriddenTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void FlexItemsMinHeightShouldBeOverriddenTest(AlignmentPropertyValue alignItemsValue, JustifyContent + justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue, int? + comparisonPdfId) { String outFileName = destinationFolder + "flexItemsMinHeightShouldBeOverriddenTest" + comparisonPdfId + ".pdf"; String cmpFileName = sourceFolder + "cmp_flexItemsMinHeightShouldBeOverriddenTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); flexContainer.Add(new Div().SetWidth(110).SetBackgroundColor(ColorConstants.BLUE).SetHeight(100)); flexContainer.Add(new Div().SetWidth(110).SetBackgroundColor(ColorConstants.YELLOW).SetMinHeight(20)); document.Add(flexContainer); @@ -756,13 +778,15 @@ public virtual void FlexItemsMinHeightShouldBeOverriddenTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void LinesMinHeightShouldBeRespectedTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void LinesMinHeightShouldBeRespectedTest(AlignmentPropertyValue alignItemsValue, JustifyContent + justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue, int? + comparisonPdfId) { String outFileName = destinationFolder + "linesMinHeightShouldBeRespectedTest" + comparisonPdfId + ".pdf"; String cmpFileName = sourceFolder + "cmp_linesMinHeightShouldBeRespectedTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); flexContainer.SetMinHeight(100); Div child = new Div().SetWidth(110).SetBackgroundColor(ColorConstants.BLUE); child.Add(new Paragraph().SetWidth(110).SetBackgroundColor(ColorConstants.YELLOW)); @@ -773,13 +797,15 @@ public virtual void LinesMinHeightShouldBeRespectedTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void LinesMaxHeightShouldBeRespectedTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void LinesMaxHeightShouldBeRespectedTest(AlignmentPropertyValue alignItemsValue, JustifyContent + justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue, int? + comparisonPdfId) { String outFileName = destinationFolder + "linesMaxHeightShouldBeRespectedTest" + comparisonPdfId + ".pdf"; String cmpFileName = sourceFolder + "cmp_linesMaxHeightShouldBeRespectedTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); flexContainer.SetMaxHeight(100); Div child = new Div().SetWidth(100).SetBackgroundColor(ColorConstants.BLUE).SetHeight(150); child.Add(new Paragraph().SetWidth(100).SetBackgroundColor(ColorConstants.YELLOW)); @@ -790,16 +816,18 @@ public virtual void LinesMaxHeightShouldBeRespectedTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void CollapsingMarginsFlexContainerTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void CollapsingMarginsFlexContainerTest(AlignmentPropertyValue alignItemsValue, JustifyContent + justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue, int? + comparisonPdfId) { String outFileName = destinationFolder + "collapsingMarginsFlexContainerTest" + comparisonPdfId + ".pdf"; String cmpFileName = sourceFolder + "cmp_collapsingMarginsFlexContainerTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); document.SetProperty(Property.COLLAPSING_MARGINS, true); - Div flexContainer = CreateFlexContainer(); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); flexContainer.SetProperty(Property.MARGIN_TOP, UnitValue.CreatePointValue(50)); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(2)); + flexContainer.SetBorder(new SolidBorder(2)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); Div child1 = CreateNewDiv(); child1.SetBackgroundColor(ColorConstants.CYAN); @@ -816,14 +844,15 @@ public virtual void CollapsingMarginsFlexContainerTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void FlexItemBoxSizingTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void FlexItemBoxSizingTest(AlignmentPropertyValue alignItemsValue, JustifyContent justifyContentValue + , FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue, int? comparisonPdfId) { String outFileName = destinationFolder + "flexItemBoxSizingTest" + comparisonPdfId + ".pdf"; String cmpFileName = sourceFolder + "cmp_flexItemBoxSizingTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(ColorConstants.BLUE, 30)); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); + flexContainer.SetBorder(new SolidBorder(ColorConstants.BLUE, 30)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); flexContainer.SetWidth(450); flexContainer.SetHeight(200); @@ -859,14 +888,15 @@ public virtual void FlexItemBoxSizingTest() { , "diff")); } - [NUnit.Framework.Test] - public virtual void FlexContainerBoxSizingTest() { + [NUnit.Framework.TestCaseSource("AlignItemsAndJustifyContentProperties")] + public virtual void FlexContainerBoxSizingTest(AlignmentPropertyValue alignItemsValue, JustifyContent justifyContentValue + , FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue, int? comparisonPdfId) { String outFileName = destinationFolder + "flexContainerBoxSizingTest" + comparisonPdfId + ".pdf"; String cmpFileName = sourceFolder + "cmp_flexContainerBoxSizingTest" + comparisonPdfId + ".pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document document = new Document(pdfDocument); - Div flexContainer = CreateFlexContainer(); - flexContainer.SetProperty(Property.BORDER, new SolidBorder(ColorConstants.BLUE, 30)); + Div flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue); + flexContainer.SetBorder(new SolidBorder(ColorConstants.BLUE, 30)); flexContainer.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); flexContainer.SetWidth(450); flexContainer.SetProperty(Property.BOX_SIZING, BoxSizingPropertyValue.BORDER_BOX); @@ -886,8 +916,11 @@ public virtual void FlexContainerBoxSizingTest() { , "diff")); } - private Div GetFlexContainer(OverflowPropertyValue? overflowX, Style style) { - FlexContainer flexContainer = CreateFlexContainer(); + private Div GetFlexContainer(OverflowPropertyValue? overflowX, Style style, AlignmentPropertyValue alignItemsValue + , JustifyContent justifyContentValue, FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue + ) { + FlexContainer flexContainer = CreateFlexContainer(alignItemsValue, justifyContentValue, wrapValue, directionValue + ); flexContainer.SetBackgroundColor(ColorConstants.GREEN).SetBorderRight(new SolidBorder(60)); if (null != style) { flexContainer.AddStyle(style); @@ -912,7 +945,8 @@ private static Div GetFlexItem(OverflowPropertyValue? overflowX, Style style) { return flexItem; } - private FlexContainer CreateFlexContainer() { + private FlexContainer CreateFlexContainer(AlignmentPropertyValue alignItemsValue, JustifyContent justifyContentValue + , FlexWrapPropertyValue wrapValue, FlexDirectionPropertyValue directionValue) { FlexContainer flexContainer = new FlexContainer(); flexContainer.SetProperty(Property.ALIGN_ITEMS, alignItemsValue); flexContainer.SetProperty(Property.JUSTIFY_CONTENT, justifyContentValue); @@ -926,7 +960,7 @@ private FlexContainer CreateFlexContainer() { private static Div CreateNewDiv() { Div newDiv = new Div(); - newDiv.SetProperty(Property.BORDER, new SolidBorder(1)); + newDiv.SetBorder(new SolidBorder(1)); newDiv.SetProperty(Property.WIDTH, UnitValue.CreatePointValue(50)); newDiv.SetProperty(Property.HEIGHT, UnitValue.CreatePointValue(100)); return newDiv; diff --git a/itext.tests/itext.layout.tests/itext/layout/element/GridContainerTest.cs b/itext.tests/itext.layout.tests/itext/layout/element/GridContainerTest.cs index 1f8966cf77..fa8bc0f29d 100644 --- a/itext.tests/itext.layout.tests/itext/layout/element/GridContainerTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/element/GridContainerTest.cs @@ -67,10 +67,29 @@ public virtual void BasicThreeColumnsTest() { )); } + [NUnit.Framework.Test] + public virtual void BorderBoxWithNoBordersTest() { + String filename = DESTINATION_FOLDER + "borderBoxWithNoBordersTest.pdf"; + String cmpName = SOURCE_FOLDER + "cmp_borderBoxWithNoBordersTest.pdf"; + IList templateColumns = new List(); + templateColumns.Add(new PointValue(150.0f)); + templateColumns.Add(new PointValue(150.0f)); + using (Document document = new Document(new PdfDocument(new PdfWriter(filename)))) { + GridContainer grid = new GridContainer(); + grid.SetProperty(Property.GRID_TEMPLATE_COLUMNS, templateColumns); + Paragraph child = new Paragraph("First"); + child.SetProperty(Property.BOX_SIZING, BoxSizingPropertyValue.BORDER_BOX); + grid.Add(child); + document.Add(grid); + } + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpName, DESTINATION_FOLDER, "diff_" + )); + } + [NUnit.Framework.Test] public virtual void BasicTwoColumnsTest() { - String filename = DESTINATION_FOLDER + "basicTwoColumnsTest.pdf"; - String cmpName = SOURCE_FOLDER + "cmp_basicTwoColumnsTest.pdf"; + String filename = DESTINATION_FOLDER + "borderBoxChild.pdf"; + String cmpName = SOURCE_FOLDER + "cmp_borderBoxChild.pdf"; IList templateColumns = new List(); templateColumns.Add(new PointValue(150.0f)); templateColumns.Add(new PointValue(150.0f)); diff --git a/itext.tests/itext.layout.tests/itext/layout/element/MulticolContainerTest.cs b/itext.tests/itext.layout.tests/itext/layout/element/MulticolContainerTest.cs index 6ba452fe4f..d4944951bc 100644 --- a/itext.tests/itext.layout.tests/itext/layout/element/MulticolContainerTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/element/MulticolContainerTest.cs @@ -78,7 +78,7 @@ public virtual void DivColumnContainerTest() { ctx.SetProperty(Property.COLUMN_COUNT, 2); Div div = new Div(); div.SetProperty(Property.MARGIN_TOP, UnitValue.CreatePointValue(50)); - div.SetProperty(Property.BORDER, new SolidBorder(2)); + div.SetBorder(new SolidBorder(2)); div.SetProperty(Property.PADDING_LEFT, UnitValue.CreatePointValue(40)); div.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); div.SetProperty(Property.WIDTH, UnitValue.CreatePointValue(450)); @@ -646,7 +646,7 @@ public virtual void OverflowingDivWithParagraphMultipageTest() { ); paragraph.SetBorder(new SolidBorder(2)); Div columnDiv = new Div(); - columnDiv.SetProperty(Property.BORDER, new SolidBorder(1)); + columnDiv.SetBorder(new SolidBorder(1)); columnDiv.SetProperty(Property.BACKGROUND, new Background(ColorConstants.BLUE)); columnDiv.SetProperty(Property.KEEP_TOGETHER, true); columnDiv.SetProperty(Property.WIDTH, UnitValue.CreatePointValue(50)); @@ -674,7 +674,7 @@ public virtual void MarginCantFitCurrentPageTest() { ); paragraph.SetBorder(new SolidBorder(2)); Div columnDiv = new Div(); - columnDiv.SetProperty(Property.BORDER, new SolidBorder(1)); + columnDiv.SetBorder(new SolidBorder(1)); columnDiv.SetProperty(Property.BACKGROUND, new Background(ColorConstants.BLUE)); columnDiv.SetProperty(Property.KEEP_TOGETHER, true); columnDiv.SetProperty(Property.MARGIN_BOTTOM, UnitValue.CreatePointValue(40)); @@ -703,7 +703,7 @@ public virtual void PaddingCantFitCurrentPageTest() { ); paragraph.SetBorder(new SolidBorder(2)); Div columnDiv = new Div(); - columnDiv.SetProperty(Property.BORDER, new SolidBorder(1)); + columnDiv.SetBorder(new SolidBorder(1)); columnDiv.SetProperty(Property.BACKGROUND, new Background(ColorConstants.BLUE)); columnDiv.SetProperty(Property.KEEP_TOGETHER, true); columnDiv.SetProperty(Property.PADDING_BOTTOM, UnitValue.CreatePointValue(40)); @@ -1216,7 +1216,7 @@ private static Paragraph CreateDummyParagraph() { private static Div CreateFirstPageFiller() { Div firstPageFiller = new Div(); firstPageFiller.SetProperty(Property.MARGIN_TOP, UnitValue.CreatePointValue(50)); - firstPageFiller.SetProperty(Property.BORDER, new SolidBorder(1)); + firstPageFiller.SetBorder(new SolidBorder(1)); firstPageFiller.SetProperty(Property.PADDING_LEFT, UnitValue.CreatePointValue(20)); firstPageFiller.SetProperty(Property.BACKGROUND, new Background(ColorConstants.LIGHT_GRAY)); firstPageFiller.SetProperty(Property.WIDTH, UnitValue.CreatePointValue(450)); diff --git a/itext.tests/itext.layout.tests/itext/layout/hyphenation/HyphenationTreeTest.cs b/itext.tests/itext.layout.tests/itext/layout/hyphenation/HyphenationTreeTest.cs new file mode 100644 index 0000000000..04fbd373ca --- /dev/null +++ b/itext.tests/itext.layout.tests/itext/layout/hyphenation/HyphenationTreeTest.cs @@ -0,0 +1,52 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using iText.Test; + +namespace iText.Layout.Hyphenation { + [NUnit.Framework.Category("UnitTest")] + public class HyphenationTreeTest : ExtendedITextTest { + private static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + .CurrentContext.TestDirectory) + "/resources/itext/layout/HyphenationTreeTest/"; + + [NUnit.Framework.Test] + public virtual void LoadPatternXmlTest() { + String sourceFilePath = SOURCE_FOLDER + "hyphen_pattern.xml"; + HyphenationTree hyphenationTree = new HyphenationTree(); + hyphenationTree.LoadPatterns(sourceFilePath); + NUnit.Framework.Assert.AreEqual(3, hyphenationTree.length); + } + + [NUnit.Framework.Test] + public virtual void DirectlyParsePatternClassesTest() { + String sourceFilePath = SOURCE_FOLDER + "only_classes.xml"; + String classPatterns = "\u0000a\u0000Ab\u0000B\u0000c\u0000C\u0000d\u0000D"; + HyphenationTree hyphenationTree = new HyphenationTree(); + PatternParser patternParser = new PatternParser(hyphenationTree); + patternParser.Parse(sourceFilePath); + char[] sc = hyphenationTree.classmap.sc; + String resultClassmapSc = new String(sc); + NUnit.Framework.Assert.IsTrue(resultClassmapSc.Contains(classPatterns)); + } + } +} diff --git a/itext.tests/itext.layout.tests/itext/layout/renderer/AbstractRendererUnitTest.cs b/itext.tests/itext.layout.tests/itext/layout/renderer/AbstractRendererUnitTest.cs index 260de90f24..a5afeba49a 100644 --- a/itext.tests/itext.layout.tests/itext/layout/renderer/AbstractRendererUnitTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/renderer/AbstractRendererUnitTest.cs @@ -74,22 +74,22 @@ public virtual void CreateXObjectWithInvalidColorTest() { [NUnit.Framework.Test] public virtual void DrawBackgroundImageTest() { - AbstractRenderer renderer = new _DivRenderer_104(new Div()); + AbstractRenderer renderer = new _DivRenderer_103(new Div()); byte[] bytes = new byte[] { 54, 25, 47, 15, 2, 2, 2, 44, 55, 77, 86, 24 }; int[] counter = new int[] { 0 }; PdfDocument document = new PdfDocument(new PdfWriter(new MemoryStream())); document.AddNewPage(); - DrawContext context = new DrawContext(document, new _PdfCanvas_114(counter, bytes, document, 1)); + DrawContext context = new DrawContext(document, new _PdfCanvas_113(counter, bytes, document, 1)); IList images = new List(); - images.Add(new BackgroundImage.Builder().SetImage(new _PdfImageXObject_132(ImageDataFactory.CreateRawImage + images.Add(new BackgroundImage.Builder().SetImage(new _PdfImageXObject_131(ImageDataFactory.CreateRawImage (bytes))).Build()); renderer.SetProperty(Property.BACKGROUND_IMAGE, images); renderer.DrawBackground(context); NUnit.Framework.Assert.AreEqual(50, counter[0]); } - private sealed class _DivRenderer_104 : DivRenderer { - public _DivRenderer_104(Div baseArg1) + private sealed class _DivRenderer_103 : DivRenderer { + public _DivRenderer_103(Div baseArg1) : base(baseArg1) { } @@ -98,8 +98,8 @@ public override Rectangle GetOccupiedAreaBBox() { } } - private sealed class _PdfCanvas_114 : PdfCanvas { - public _PdfCanvas_114(int[] counter, byte[] bytes, PdfDocument baseArg1, int baseArg2) + private sealed class _PdfCanvas_113 : PdfCanvas { + public _PdfCanvas_113(int[] counter, byte[] bytes, PdfDocument baseArg1, int baseArg2) : base(baseArg1, baseArg2) { this.counter = counter; this.bytes = bytes; @@ -127,8 +127,8 @@ public override PdfCanvas AddXObjectFittedIntoRectangle(PdfXObject xObject, Rect private readonly byte[] bytes; } - private sealed class _PdfImageXObject_132 : PdfImageXObject { - public _PdfImageXObject_132(ImageData baseArg1) + private sealed class _PdfImageXObject_131 : PdfImageXObject { + public _PdfImageXObject_131(ImageData baseArg1) : base(baseArg1) { } @@ -143,14 +143,14 @@ public override float GetHeight() { [NUnit.Framework.Test] public virtual void DrawBackgroundImageWithNoRepeatXTest() { - AbstractRenderer renderer = new _DivRenderer_150(new Div()); + AbstractRenderer renderer = new _DivRenderer_149(new Div()); byte[] bytes = new byte[] { 54, 25, 47, 15, 2, 2, 2, 44, 55, 77, 86, 24 }; int[] counter = new int[] { 0 }; PdfDocument document = new PdfDocument(new PdfWriter(new MemoryStream())); document.AddNewPage(); - DrawContext context = new DrawContext(document, new _PdfCanvas_160(counter, bytes, document, 1)); + DrawContext context = new DrawContext(document, new _PdfCanvas_159(counter, bytes, document, 1)); IList images = new List(); - images.Add(new BackgroundImage.Builder().SetImage(new _PdfImageXObject_178(ImageDataFactory.CreateRawImage + images.Add(new BackgroundImage.Builder().SetImage(new _PdfImageXObject_177(ImageDataFactory.CreateRawImage (bytes))).SetBackgroundRepeat(new BackgroundRepeat(BackgroundRepeat.BackgroundRepeatValue.NO_REPEAT, BackgroundRepeat.BackgroundRepeatValue .REPEAT)).Build()); renderer.SetProperty(Property.BACKGROUND_IMAGE, images); @@ -158,8 +158,8 @@ public virtual void DrawBackgroundImageWithNoRepeatXTest() { NUnit.Framework.Assert.AreEqual(5, counter[0]); } - private sealed class _DivRenderer_150 : DivRenderer { - public _DivRenderer_150(Div baseArg1) + private sealed class _DivRenderer_149 : DivRenderer { + public _DivRenderer_149(Div baseArg1) : base(baseArg1) { } @@ -168,8 +168,8 @@ public override Rectangle GetOccupiedAreaBBox() { } } - private sealed class _PdfCanvas_160 : PdfCanvas { - public _PdfCanvas_160(int[] counter, byte[] bytes, PdfDocument baseArg1, int baseArg2) + private sealed class _PdfCanvas_159 : PdfCanvas { + public _PdfCanvas_159(int[] counter, byte[] bytes, PdfDocument baseArg1, int baseArg2) : base(baseArg1, baseArg2) { this.counter = counter; this.bytes = bytes; @@ -197,8 +197,8 @@ public override PdfCanvas AddXObjectFittedIntoRectangle(PdfXObject xObject, Rect private readonly byte[] bytes; } - private sealed class _PdfImageXObject_178 : PdfImageXObject { - public _PdfImageXObject_178(ImageData baseArg1) + private sealed class _PdfImageXObject_177 : PdfImageXObject { + public _PdfImageXObject_177(ImageData baseArg1) : base(baseArg1) { } @@ -213,14 +213,14 @@ public override float GetHeight() { [NUnit.Framework.Test] public virtual void DrawBackgroundImageWithNoRepeatYTest() { - AbstractRenderer renderer = new _DivRenderer_197(new Div()); + AbstractRenderer renderer = new _DivRenderer_196(new Div()); byte[] bytes = new byte[] { 54, 25, 47, 15, 2, 2, 2, 44, 55, 77, 86, 24 }; int[] counter = new int[] { 0 }; PdfDocument document = new PdfDocument(new PdfWriter(new MemoryStream())); document.AddNewPage(); - DrawContext context = new DrawContext(document, new _PdfCanvas_207(counter, bytes, document, 1)); + DrawContext context = new DrawContext(document, new _PdfCanvas_206(counter, bytes, document, 1)); IList images = new List(); - images.Add(new BackgroundImage.Builder().SetImage(new _PdfImageXObject_225(ImageDataFactory.CreateRawImage + images.Add(new BackgroundImage.Builder().SetImage(new _PdfImageXObject_224(ImageDataFactory.CreateRawImage (bytes))).SetBackgroundRepeat(new BackgroundRepeat(BackgroundRepeat.BackgroundRepeatValue.REPEAT, BackgroundRepeat.BackgroundRepeatValue .NO_REPEAT)).Build()); renderer.SetProperty(Property.BACKGROUND_IMAGE, images); @@ -228,8 +228,8 @@ public virtual void DrawBackgroundImageWithNoRepeatYTest() { NUnit.Framework.Assert.AreEqual(10, counter[0]); } - private sealed class _DivRenderer_197 : DivRenderer { - public _DivRenderer_197(Div baseArg1) + private sealed class _DivRenderer_196 : DivRenderer { + public _DivRenderer_196(Div baseArg1) : base(baseArg1) { } @@ -238,8 +238,8 @@ public override Rectangle GetOccupiedAreaBBox() { } } - private sealed class _PdfCanvas_207 : PdfCanvas { - public _PdfCanvas_207(int[] counter, byte[] bytes, PdfDocument baseArg1, int baseArg2) + private sealed class _PdfCanvas_206 : PdfCanvas { + public _PdfCanvas_206(int[] counter, byte[] bytes, PdfDocument baseArg1, int baseArg2) : base(baseArg1, baseArg2) { this.counter = counter; this.bytes = bytes; @@ -267,8 +267,8 @@ public override PdfCanvas AddXObjectFittedIntoRectangle(PdfXObject xObject, Rect private readonly byte[] bytes; } - private sealed class _PdfImageXObject_225 : PdfImageXObject { - public _PdfImageXObject_225(ImageData baseArg1) + private sealed class _PdfImageXObject_224 : PdfImageXObject { + public _PdfImageXObject_224(ImageData baseArg1) : base(baseArg1) { } @@ -283,14 +283,14 @@ public override float GetHeight() { [NUnit.Framework.Test] public virtual void DrawBackgroundImageWithNoRepeatTest() { - AbstractRenderer renderer = new _DivRenderer_244(new Div()); + AbstractRenderer renderer = new _DivRenderer_243(new Div()); byte[] bytes = new byte[] { 54, 25, 47, 15, 2, 2, 2, 44, 55, 77, 86, 24 }; int[] counter = new int[] { 0 }; PdfDocument document = new PdfDocument(new PdfWriter(new MemoryStream())); document.AddNewPage(); - DrawContext context = new DrawContext(document, new _PdfCanvas_254(counter, bytes, document, 1)); + DrawContext context = new DrawContext(document, new _PdfCanvas_253(counter, bytes, document, 1)); IList images = new List(); - images.Add(new BackgroundImage.Builder().SetImage(new _PdfImageXObject_272(ImageDataFactory.CreateRawImage + images.Add(new BackgroundImage.Builder().SetImage(new _PdfImageXObject_271(ImageDataFactory.CreateRawImage (bytes))).SetBackgroundRepeat(new BackgroundRepeat(BackgroundRepeat.BackgroundRepeatValue.NO_REPEAT)). Build()); renderer.SetProperty(Property.BACKGROUND_IMAGE, images); @@ -298,8 +298,8 @@ public virtual void DrawBackgroundImageWithNoRepeatTest() { NUnit.Framework.Assert.AreEqual(1, counter[0]); } - private sealed class _DivRenderer_244 : DivRenderer { - public _DivRenderer_244(Div baseArg1) + private sealed class _DivRenderer_243 : DivRenderer { + public _DivRenderer_243(Div baseArg1) : base(baseArg1) { } @@ -308,8 +308,8 @@ public override Rectangle GetOccupiedAreaBBox() { } } - private sealed class _PdfCanvas_254 : PdfCanvas { - public _PdfCanvas_254(int[] counter, byte[] bytes, PdfDocument baseArg1, int baseArg2) + private sealed class _PdfCanvas_253 : PdfCanvas { + public _PdfCanvas_253(int[] counter, byte[] bytes, PdfDocument baseArg1, int baseArg2) : base(baseArg1, baseArg2) { this.counter = counter; this.bytes = bytes; @@ -337,8 +337,8 @@ public override PdfCanvas AddXObjectFittedIntoRectangle(PdfXObject xObject, Rect private readonly byte[] bytes; } - private sealed class _PdfImageXObject_272 : PdfImageXObject { - public _PdfImageXObject_272(ImageData baseArg1) + private sealed class _PdfImageXObject_271 : PdfImageXObject { + public _PdfImageXObject_271(ImageData baseArg1) : base(baseArg1) { } @@ -353,21 +353,21 @@ public override float GetHeight() { [NUnit.Framework.Test] public virtual void DrawBackgroundImageWithPositionTest() { - AbstractRenderer renderer = new _DivRenderer_292(new Div()); + AbstractRenderer renderer = new _DivRenderer_291(new Div()); byte[] bytes = new byte[] { 54, 25, 47, 15, 2, 2, 2, 44, 55, 77, 86, 24 }; PdfDocument document = new PdfDocument(new PdfWriter(new MemoryStream())); document.AddNewPage(); - DrawContext context = new DrawContext(document, new _PdfCanvas_301(bytes, document, 1)); + DrawContext context = new DrawContext(document, new _PdfCanvas_300(bytes, document, 1)); IList images = new List(); - images.Add(new BackgroundImage.Builder().SetImage(new _PdfImageXObject_320(ImageDataFactory.CreateRawImage + images.Add(new BackgroundImage.Builder().SetImage(new _PdfImageXObject_319(ImageDataFactory.CreateRawImage (bytes))).SetBackgroundPosition(new BackgroundPosition().SetXShift(new UnitValue(UnitValue.PERCENT, 30 ))).Build()); renderer.SetProperty(Property.BACKGROUND_IMAGE, images); renderer.DrawBackground(context); } - private sealed class _DivRenderer_292 : DivRenderer { - public _DivRenderer_292(Div baseArg1) + private sealed class _DivRenderer_291 : DivRenderer { + public _DivRenderer_291(Div baseArg1) : base(baseArg1) { } @@ -376,8 +376,8 @@ public override Rectangle GetOccupiedAreaBBox() { } } - private sealed class _PdfCanvas_301 : PdfCanvas { - public _PdfCanvas_301(byte[] bytes, PdfDocument baseArg1, int baseArg2) + private sealed class _PdfCanvas_300 : PdfCanvas { + public _PdfCanvas_300(byte[] bytes, PdfDocument baseArg1, int baseArg2) : base(baseArg1, baseArg2) { this.bytes = bytes; this.@object = null; @@ -403,8 +403,8 @@ public override PdfCanvas AddXObjectFittedIntoRectangle(PdfXObject xObject, Rect private readonly byte[] bytes; } - private sealed class _PdfImageXObject_320 : PdfImageXObject { - public _PdfImageXObject_320(ImageData baseArg1) + private sealed class _PdfImageXObject_319 : PdfImageXObject { + public _PdfImageXObject_319(ImageData baseArg1) : base(baseArg1) { } @@ -419,10 +419,10 @@ public override float GetHeight() { [NUnit.Framework.Test] public virtual void DrawGradientWithPositionTest() { - AbstractRenderer renderer = new _DivRenderer_338(new Div()); + AbstractRenderer renderer = new _DivRenderer_337(new Div()); PdfDocument document = new PdfDocument(new PdfWriter(new MemoryStream())); document.AddNewPage(); - DrawContext context = new DrawContext(document, new _PdfCanvas_346(document, 1)); + DrawContext context = new DrawContext(document, new _PdfCanvas_345(document, 1)); IList images = new List(); images.Add(new BackgroundImage.Builder().SetLinearGradientBuilder(new StrategyBasedLinearGradientBuilder() .AddColorStop(new GradientColorStop(ColorConstants.RED.GetColorValue())).AddColorStop(new GradientColorStop @@ -433,8 +433,8 @@ public virtual void DrawGradientWithPositionTest() { renderer.DrawBackground(context); } - private sealed class _DivRenderer_338 : DivRenderer { - public _DivRenderer_338(Div baseArg1) + private sealed class _DivRenderer_337 : DivRenderer { + public _DivRenderer_337(Div baseArg1) : base(baseArg1) { } @@ -443,8 +443,8 @@ public override Rectangle GetOccupiedAreaBBox() { } } - private sealed class _PdfCanvas_346 : PdfCanvas { - public _PdfCanvas_346(PdfDocument baseArg1, int baseArg2) + private sealed class _PdfCanvas_345 : PdfCanvas { + public _PdfCanvas_345(PdfDocument baseArg1, int baseArg2) : base(baseArg1, baseArg2) { this.@object = null; } @@ -467,10 +467,10 @@ public override PdfCanvas AddXObjectFittedIntoRectangle(PdfXObject xObject, Rect [NUnit.Framework.Test] public virtual void DrawGradientWithPercentagePositionTest() { - AbstractRenderer renderer = new _DivRenderer_375(new Div()); + AbstractRenderer renderer = new _DivRenderer_374(new Div()); PdfDocument document = new PdfDocument(new PdfWriter(new MemoryStream())); document.AddNewPage(); - DrawContext context = new DrawContext(document, new _PdfCanvas_383(document, 1)); + DrawContext context = new DrawContext(document, new _PdfCanvas_382(document, 1)); IList images = new List(); images.Add(new BackgroundImage.Builder().SetLinearGradientBuilder(new StrategyBasedLinearGradientBuilder() .AddColorStop(new GradientColorStop(ColorConstants.RED.GetColorValue())).AddColorStop(new GradientColorStop @@ -481,8 +481,8 @@ public virtual void DrawGradientWithPercentagePositionTest() { renderer.DrawBackground(context); } - private sealed class _DivRenderer_375 : DivRenderer { - public _DivRenderer_375(Div baseArg1) + private sealed class _DivRenderer_374 : DivRenderer { + public _DivRenderer_374(Div baseArg1) : base(baseArg1) { } @@ -491,8 +491,8 @@ public override Rectangle GetOccupiedAreaBBox() { } } - private sealed class _PdfCanvas_383 : PdfCanvas { - public _PdfCanvas_383(PdfDocument baseArg1, int baseArg2) + private sealed class _PdfCanvas_382 : PdfCanvas { + public _PdfCanvas_382(PdfDocument baseArg1, int baseArg2) : base(baseArg1, baseArg2) { this.@object = null; } @@ -515,23 +515,23 @@ public override PdfCanvas AddXObjectFittedIntoRectangle(PdfXObject xObject, Rect [NUnit.Framework.Test] public virtual void DrawBackgroundImagesTest() { - AbstractRenderer renderer = new _DivRenderer_412(new Div()); + AbstractRenderer renderer = new _DivRenderer_411(new Div()); IList listBytes = JavaUtil.ArraysAsList(new byte[] { 54, 25, 47, 15, 2, 2, 2, 44, 55, 77, 86, 24 } , new byte[] { 4, 15, 41, 23, 3, 2, 7, 14, 55, 27, 46, 12, 14, 14, 7, 7, 24, 25 }); int[] counter = new int[] { 0 }; PdfDocument document = new PdfDocument(new PdfWriter(new MemoryStream())); document.AddNewPage(); - DrawContext context = new DrawContext(document, new _PdfCanvas_424(listBytes, counter, document, 1)); + DrawContext context = new DrawContext(document, new _PdfCanvas_423(listBytes, counter, document, 1)); renderer.SetProperty(Property.BACKGROUND_IMAGE, JavaUtil.ArraysAsList((BackgroundImage)new BackgroundImage.Builder - ().SetImage(new _PdfImageXObject_440(ImageDataFactory.CreateRawImage(listBytes[1]))).Build(), (BackgroundImage - )new BackgroundImage.Builder().SetImage(new _PdfImageXObject_451(ImageDataFactory.CreateRawImage(listBytes + ().SetImage(new _PdfImageXObject_439(ImageDataFactory.CreateRawImage(listBytes[1]))).Build(), (BackgroundImage + )new BackgroundImage.Builder().SetImage(new _PdfImageXObject_450(ImageDataFactory.CreateRawImage(listBytes [0]))).Build())); renderer.DrawBackground(context); NUnit.Framework.Assert.AreEqual(listBytes.Count, counter[0]); } - private sealed class _DivRenderer_412 : DivRenderer { - public _DivRenderer_412(Div baseArg1) + private sealed class _DivRenderer_411 : DivRenderer { + public _DivRenderer_411(Div baseArg1) : base(baseArg1) { } @@ -540,8 +540,8 @@ public override Rectangle GetOccupiedAreaBBox() { } } - private sealed class _PdfCanvas_424 : PdfCanvas { - public _PdfCanvas_424(IList listBytes, int[] counter, PdfDocument baseArg1, int baseArg2) + private sealed class _PdfCanvas_423 : PdfCanvas { + public _PdfCanvas_423(IList listBytes, int[] counter, PdfDocument baseArg1, int baseArg2) : base(baseArg1, baseArg2) { this.listBytes = listBytes; this.counter = counter; @@ -568,8 +568,8 @@ public override PdfCanvas AddXObjectFittedIntoRectangle(PdfXObject xObject, Rect private readonly int[] counter; } - private sealed class _PdfImageXObject_440 : PdfImageXObject { - public _PdfImageXObject_440(ImageData baseArg1) + private sealed class _PdfImageXObject_439 : PdfImageXObject { + public _PdfImageXObject_439(ImageData baseArg1) : base(baseArg1) { } @@ -582,8 +582,8 @@ public override float GetHeight() { } } - private sealed class _PdfImageXObject_451 : PdfImageXObject { - public _PdfImageXObject_451(ImageData baseArg1) + private sealed class _PdfImageXObject_450 : PdfImageXObject { + public _PdfImageXObject_450(ImageData baseArg1) : base(baseArg1) { } @@ -598,7 +598,7 @@ public override float GetHeight() { [NUnit.Framework.Test] public virtual void DrawBackgroundImagesWithPositionsTest() { - AbstractRenderer renderer = new _DivRenderer_468(new Div()); + AbstractRenderer renderer = new _DivRenderer_467(new Div()); IList listBytes = JavaUtil.ArraysAsList(new byte[] { 54, 25, 47, 15, 2, 2, 2, 44, 55, 77, 86, 24 } , new byte[] { 4, 15, 41, 23, 3, 2, 7, 14, 55, 27, 46, 12, 14, 14, 7, 7, 24, 25 }); float widthHeight = 10.0f; @@ -607,11 +607,11 @@ public virtual void DrawBackgroundImagesWithPositionsTest() { int[] counter = new int[] { 0 }; PdfDocument document = new PdfDocument(new PdfWriter(new MemoryStream())); document.AddNewPage(); - DrawContext context = new DrawContext(document, new _PdfCanvas_485(listBytes, counter, listRectangles, document + DrawContext context = new DrawContext(document, new _PdfCanvas_484(listBytes, counter, listRectangles, document , 1)); renderer.SetProperty(Property.BACKGROUND_IMAGE, JavaUtil.ArraysAsList((BackgroundImage)new BackgroundImage.Builder - ().SetImage(new _PdfImageXObject_503(widthHeight, ImageDataFactory.CreateRawImage(listBytes[1]))).Build - (), (BackgroundImage)new BackgroundImage.Builder().SetImage(new _PdfImageXObject_514(widthHeight, ImageDataFactory + ().SetImage(new _PdfImageXObject_502(widthHeight, ImageDataFactory.CreateRawImage(listBytes[1]))).Build + (), (BackgroundImage)new BackgroundImage.Builder().SetImage(new _PdfImageXObject_513(widthHeight, ImageDataFactory .CreateRawImage(listBytes[0]))).SetBackgroundPosition(new BackgroundPosition().SetPositionX(BackgroundPosition.PositionX .RIGHT).SetPositionY(BackgroundPosition.PositionY.CENTER).SetXShift(new UnitValue(UnitValue.PERCENT, 10 ))).Build())); @@ -619,8 +619,8 @@ public virtual void DrawBackgroundImagesWithPositionsTest() { NUnit.Framework.Assert.AreEqual(listBytes.Count, counter[0]); } - private sealed class _DivRenderer_468 : DivRenderer { - public _DivRenderer_468(Div baseArg1) + private sealed class _DivRenderer_467 : DivRenderer { + public _DivRenderer_467(Div baseArg1) : base(baseArg1) { } @@ -629,8 +629,8 @@ public override Rectangle GetOccupiedAreaBBox() { } } - private sealed class _PdfCanvas_485 : PdfCanvas { - public _PdfCanvas_485(IList listBytes, int[] counter, IList listRectangles, PdfDocument + private sealed class _PdfCanvas_484 : PdfCanvas { + public _PdfCanvas_484(IList listBytes, int[] counter, IList listRectangles, PdfDocument baseArg1, int baseArg2) : base(baseArg1, baseArg2) { this.listBytes = listBytes; @@ -663,8 +663,8 @@ public override PdfCanvas AddXObjectFittedIntoRectangle(PdfXObject xObject, Rect private readonly IList listRectangles; } - private sealed class _PdfImageXObject_503 : PdfImageXObject { - public _PdfImageXObject_503(float widthHeight, ImageData baseArg1) + private sealed class _PdfImageXObject_502 : PdfImageXObject { + public _PdfImageXObject_502(float widthHeight, ImageData baseArg1) : base(baseArg1) { this.widthHeight = widthHeight; } @@ -680,8 +680,8 @@ public override float GetHeight() { private readonly float widthHeight; } - private sealed class _PdfImageXObject_514 : PdfImageXObject { - public _PdfImageXObject_514(float widthHeight, ImageData baseArg1) + private sealed class _PdfImageXObject_513 : PdfImageXObject { + public _PdfImageXObject_513(float widthHeight, ImageData baseArg1) : base(baseArg1) { this.widthHeight = widthHeight; } @@ -700,7 +700,7 @@ public override float GetHeight() { [NUnit.Framework.Test] public virtual void BackgroundColorClipTest() { PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new ByteArrayOutputStream())); - PdfCanvas pdfCanvas = new _PdfCanvas_533(pdfDocument.AddNewPage()); + PdfCanvas pdfCanvas = new _PdfCanvas_532(pdfDocument.AddNewPage()); DrawContext drawContext = new DrawContext(pdfDocument, pdfCanvas); AbstractRenderer renderer = new DivRenderer(new Div().SetPadding(20).SetBorder(new DashedBorder(10))); renderer.occupiedArea = new LayoutArea(1, new Rectangle(100f, 200f, 300f, 400f)); @@ -708,8 +708,8 @@ public virtual void BackgroundColorClipTest() { renderer.DrawBackground(drawContext); } - private sealed class _PdfCanvas_533 : PdfCanvas { - public _PdfCanvas_533(PdfPage baseArg1) + private sealed class _PdfCanvas_532 : PdfCanvas { + public _PdfCanvas_532(PdfPage baseArg1) : base(baseArg1) { } @@ -726,8 +726,8 @@ public override PdfCanvas Rectangle(double x, double y, double width, double hei public virtual void BackgroundImageClipOriginNoRepeatTest() { PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new ByteArrayOutputStream())); byte[] bytes = new byte[] { 54, 25, 47, 15, 2, 2, 2, 44, 55, 77, 86, 24 }; - PdfXObject rawImage = new _PdfImageXObject_554(ImageDataFactory.CreateRawImage(bytes)); - PdfCanvas pdfCanvas = new _PdfCanvas_565(rawImage, pdfDocument.AddNewPage()); + PdfXObject rawImage = new _PdfImageXObject_553(ImageDataFactory.CreateRawImage(bytes)); + PdfCanvas pdfCanvas = new _PdfCanvas_564(rawImage, pdfDocument.AddNewPage()); DrawContext drawContext = new DrawContext(pdfDocument, pdfCanvas); AbstractRenderer renderer = new DivRenderer(new Div().SetPadding(20).SetBorder(new DashedBorder(10))); renderer.occupiedArea = new LayoutArea(1, new Rectangle(100f, 200f, 300f, 400f)); @@ -740,8 +740,8 @@ public virtual void BackgroundImageClipOriginNoRepeatTest() { renderer.DrawBackground(drawContext); } - private sealed class _PdfImageXObject_554 : PdfImageXObject { - public _PdfImageXObject_554(ImageData baseArg1) + private sealed class _PdfImageXObject_553 : PdfImageXObject { + public _PdfImageXObject_553(ImageData baseArg1) : base(baseArg1) { } @@ -754,8 +754,8 @@ public override float GetHeight() { } } - private sealed class _PdfCanvas_565 : PdfCanvas { - public _PdfCanvas_565(PdfXObject rawImage, PdfPage baseArg1) + private sealed class _PdfCanvas_564 : PdfCanvas { + public _PdfCanvas_564(PdfXObject rawImage, PdfPage baseArg1) : base(baseArg1) { this.rawImage = rawImage; } @@ -784,7 +784,7 @@ public override PdfCanvas AddXObjectFittedIntoRectangle(PdfXObject xObject, Rect public virtual void BackgroundLinearGradientClipOriginNoRepeatTest() { PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new ByteArrayOutputStream())); byte[] bytes = new byte[] { 54, 25, 47, 15, 2, 2, 2, 44, 55, 77, 86, 24 }; - PdfCanvas pdfCanvas = new _PdfCanvas_602(pdfDocument.AddNewPage()); + PdfCanvas pdfCanvas = new _PdfCanvas_601(pdfDocument.AddNewPage()); DrawContext drawContext = new DrawContext(pdfDocument, pdfCanvas); AbstractRenderer renderer = new DivRenderer(new Div().SetPadding(20).SetBorder(new DashedBorder(10))); renderer.occupiedArea = new LayoutArea(1, new Rectangle(100f, 200f, 300f, 400f)); @@ -803,8 +803,8 @@ public virtual void BackgroundLinearGradientClipOriginNoRepeatTest() { renderer.DrawBackground(drawContext); } - private sealed class _PdfCanvas_602 : PdfCanvas { - public _PdfCanvas_602(PdfPage baseArg1) + private sealed class _PdfCanvas_601 : PdfCanvas { + public _PdfCanvas_601(PdfPage baseArg1) : base(baseArg1) { } diff --git a/itext.tests/itext.layout.tests/itext/layout/renderer/AreaBreakRendererUnitTest.cs b/itext.tests/itext.layout.tests/itext/layout/renderer/AreaBreakRendererUnitTest.cs index 427e8cddeb..87b591352c 100644 --- a/itext.tests/itext.layout.tests/itext/layout/renderer/AreaBreakRendererUnitTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/renderer/AreaBreakRendererUnitTest.cs @@ -55,65 +55,65 @@ public virtual void GetOccupiedAreaTestUnsupported() { [NUnit.Framework.Test] public virtual void HasPropertyTest() { //Properties are not supported for AbstractRenderer, and it's expected that the result is false for all the properties. - //The BORDER property is chosen without any specific intention. It could be replaced with any other property. + //The AREA_BREAK_TYPE property is chosen without any specific intention. It could be replaced with any other property. AreaBreakRenderer areaBreakRenderer = new AreaBreakRenderer(new AreaBreak()); - NUnit.Framework.Assert.IsFalse(areaBreakRenderer.HasProperty(Property.BORDER)); + NUnit.Framework.Assert.IsFalse(areaBreakRenderer.HasProperty(Property.AREA_BREAK_TYPE)); } [NUnit.Framework.Test] public virtual void HasOwnPropertyTest() { //Properties are not supported for AbstractRenderer, and it's expected that the result is false for all the properties. - //The BORDER property is chosen without any specific intention. It could be replaced with any other property. + //The AREA_BREAK_TYPE property is chosen without any specific intention. It could be replaced with any other property. AreaBreakRenderer areaBreakRenderer = new AreaBreakRenderer(new AreaBreak()); - NUnit.Framework.Assert.IsFalse(areaBreakRenderer.HasProperty(Property.BORDER)); + NUnit.Framework.Assert.IsFalse(areaBreakRenderer.HasOwnProperty(Property.AREA_BREAK_TYPE)); } [NUnit.Framework.Test] public virtual void GetPropertyTest() { //Properties are not supported for AbstractRenderer, and it's expected that the result is null for all the properties. - //The BORDER property is chosen without any specific intention. It could be replaced with any other property. + //The AREA_BREAK_TYPE property is chosen without any specific intention. It could be replaced with any other property. AreaBreakRenderer areaBreakRenderer = new AreaBreakRenderer(new AreaBreak()); - NUnit.Framework.Assert.IsNull(areaBreakRenderer.GetProperty(Property.BORDER)); + NUnit.Framework.Assert.IsNull(areaBreakRenderer.GetProperty(Property.AREA_BREAK_TYPE)); } [NUnit.Framework.Test] public virtual void GetOwnPropertyTest() { //Properties are not supported for AbstractRenderer, and it's expected that the result is null for all the properties. - //The BORDER property is chosen without any specific intention. It could be replaced with any other property. + //The AREA_BREAK_TYPE property is chosen without any specific intention. It could be replaced with any other property. AreaBreakRenderer areaBreakRenderer = new AreaBreakRenderer(new AreaBreak()); - NUnit.Framework.Assert.IsNull(areaBreakRenderer.GetOwnProperty(Property.BORDER)); + NUnit.Framework.Assert.IsNull(areaBreakRenderer.GetOwnProperty(Property.AREA_BREAK_TYPE)); } [NUnit.Framework.Test] public virtual void GetDefaultPropertyTest() { //Properties are not supported for AbstractRenderer, and it's expected that the result is null for all the properties. - //The BORDER property is chosen without any specific intention. It could be replaced with any other property. + //The AREA_BREAK_TYPE property is chosen without any specific intention. It could be replaced with any other property. AreaBreakRenderer areaBreakRenderer = new AreaBreakRenderer(new AreaBreak()); - NUnit.Framework.Assert.IsNull(areaBreakRenderer.GetDefaultProperty(Property.BORDER)); + NUnit.Framework.Assert.IsNull(areaBreakRenderer.GetDefaultProperty(Property.AREA_BREAK_TYPE)); } [NUnit.Framework.Test] public virtual void GetPropertyWithDefaultValueTestUnsupported() { - //The BORDER_RADIUS property is chosen without any specific intention. It could be replaced with any other property. + //The BORDER_BOTTOM_LEFT_RADIUS property is chosen without any specific intention. It could be replaced with any other property. AreaBreakRenderer areaBreakRenderer = new AreaBreakRenderer(new AreaBreak()); - NUnit.Framework.Assert.Catch(typeof(NotSupportedException), () => areaBreakRenderer.GetProperty(Property.BORDER_RADIUS + NUnit.Framework.Assert.Catch(typeof(NotSupportedException), () => areaBreakRenderer.GetProperty(Property.BORDER_BOTTOM_LEFT_RADIUS , 3)); } [NUnit.Framework.Test] public virtual void SetPropertyTestUnsupported() { - //The BORDER_RADIUS property is chosen without any specific intention. It could be replaced with any other property. + //The BORDER_BOTTOM_LEFT_RADIUS property is chosen without any specific intention. It could be replaced with any other property. AreaBreakRenderer areaBreakRenderer = new AreaBreakRenderer(new AreaBreak()); - NUnit.Framework.Assert.Catch(typeof(NotSupportedException), () => areaBreakRenderer.SetProperty(Property.BORDER_RADIUS + NUnit.Framework.Assert.Catch(typeof(NotSupportedException), () => areaBreakRenderer.SetProperty(Property.BORDER_BOTTOM_LEFT_RADIUS , 5)); } [NUnit.Framework.Test] public virtual void DeleteOwnProperty() { - //The BORDER property is chosen without any specific intention. It could be replaced with any other property. + //The AREA_BREAK_TYPE property is chosen without any specific intention. It could be replaced with any other property. //Here we just check that no exception has been thrown. AreaBreakRenderer areaBreakRenderer = new AreaBreakRenderer(new AreaBreak()); - NUnit.Framework.Assert.DoesNotThrow(() => areaBreakRenderer.DeleteOwnProperty(Property.BORDER)); + NUnit.Framework.Assert.DoesNotThrow(() => areaBreakRenderer.DeleteOwnProperty(Property.AREA_BREAK_TYPE)); } [NUnit.Framework.Test] diff --git a/itext.tests/itext.layout.tests/itext/layout/renderer/CellRendererUnitTest.cs b/itext.tests/itext.layout.tests/itext/layout/renderer/CellRendererUnitTest.cs index fe58fa855a..fc9f3b37fa 100644 --- a/itext.tests/itext.layout.tests/itext/layout/renderer/CellRendererUnitTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/renderer/CellRendererUnitTest.cs @@ -30,13 +30,13 @@ public class CellRendererUnitTest : ExtendedITextTest { [NUnit.Framework.Test] [LogMessage(iText.IO.Logs.IoLogMessageConstant.GET_NEXT_RENDERER_SHOULD_BE_OVERRIDDEN)] public virtual void GetNextRendererShouldBeOverriddenTest() { - CellRenderer cellRenderer = new _CellRenderer_44(new Cell()); + CellRenderer cellRenderer = new _CellRenderer_43(new Cell()); // Nothing is overridden NUnit.Framework.Assert.AreEqual(typeof(CellRenderer), cellRenderer.GetNextRenderer().GetType()); } - private sealed class _CellRenderer_44 : CellRenderer { - public _CellRenderer_44(Cell baseArg1) + private sealed class _CellRenderer_43 : CellRenderer { + public _CellRenderer_43(Cell baseArg1) : base(baseArg1) { } } diff --git a/itext.tests/itext.layout.tests/itext/layout/renderer/DivRendererUnitTest.cs b/itext.tests/itext.layout.tests/itext/layout/renderer/DivRendererUnitTest.cs index 310af19b22..8299013cf0 100644 --- a/itext.tests/itext.layout.tests/itext/layout/renderer/DivRendererUnitTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/renderer/DivRendererUnitTest.cs @@ -30,13 +30,13 @@ public class DivRendererUnitTest : ExtendedITextTest { [NUnit.Framework.Test] [LogMessage(iText.IO.Logs.IoLogMessageConstant.GET_NEXT_RENDERER_SHOULD_BE_OVERRIDDEN)] public virtual void GetNextRendererShouldBeOverriddenTest() { - DivRenderer divRenderer = new _DivRenderer_44(new Div()); + DivRenderer divRenderer = new _DivRenderer_43(new Div()); // Nothing is overridden NUnit.Framework.Assert.AreEqual(typeof(DivRenderer), divRenderer.GetNextRenderer().GetType()); } - private sealed class _DivRenderer_44 : DivRenderer { - public _DivRenderer_44(Div baseArg1) + private sealed class _DivRenderer_43 : DivRenderer { + public _DivRenderer_43(Div baseArg1) : base(baseArg1) { } } diff --git a/itext.tests/itext.layout.tests/itext/layout/renderer/FlexContainerRendererTest.cs b/itext.tests/itext.layout.tests/itext/layout/renderer/FlexContainerRendererTest.cs index d5d83f95d9..b405be24f4 100644 --- a/itext.tests/itext.layout.tests/itext/layout/renderer/FlexContainerRendererTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/renderer/FlexContainerRendererTest.cs @@ -32,7 +32,7 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Layout.Renderer { [NUnit.Framework.Category("UnitTest")] public class FlexContainerRendererTest : ExtendedITextTest { - private static float EPS = 0.0001F; + private const float EPS = 0.0001F; [NUnit.Framework.Test] public virtual void WidthNotSetTest() { @@ -77,7 +77,11 @@ public virtual void WidthSetToChildManyChildrenWithBordersMarginsPaddingsTest() FlexContainerRenderer flexRenderer = new FlexContainerRenderer(new Div()); DivRenderer divRenderer1 = new DivRenderer(new Div()); divRenderer1.SetProperty(Property.WIDTH, UnitValue.CreatePointValue(50)); - divRenderer1.SetProperty(Property.BORDER, new SolidBorder(5)); + SolidBorder border = new SolidBorder(5); + divRenderer1.SetProperty(Property.BORDER_TOP, border); + divRenderer1.SetProperty(Property.BORDER_RIGHT, border); + divRenderer1.SetProperty(Property.BORDER_BOTTOM, border); + divRenderer1.SetProperty(Property.BORDER_LEFT, border); DivRenderer divRenderer2 = new DivRenderer(new Div()); divRenderer2.SetProperty(Property.WIDTH, UnitValue.CreatePointValue(40)); divRenderer2.SetProperty(Property.MARGIN_LEFT, UnitValue.CreatePointValue(10)); @@ -100,7 +104,11 @@ public virtual void WidthSetToFlexRendererAndToChildManyChildrenWithBordersMargi flexRenderer.SetProperty(Property.WIDTH, UnitValue.CreatePointValue(50)); DivRenderer divRenderer1 = new DivRenderer(new Div()); divRenderer1.SetProperty(Property.WIDTH, UnitValue.CreatePointValue(50)); - divRenderer1.SetProperty(Property.BORDER, new SolidBorder(5)); + SolidBorder border = new SolidBorder(5); + divRenderer1.SetProperty(Property.BORDER_TOP, border); + divRenderer1.SetProperty(Property.BORDER_RIGHT, border); + divRenderer1.SetProperty(Property.BORDER_BOTTOM, border); + divRenderer1.SetProperty(Property.BORDER_LEFT, border); DivRenderer divRenderer2 = new DivRenderer(new Div()); divRenderer2.SetProperty(Property.WIDTH, UnitValue.CreatePointValue(40)); divRenderer2.SetProperty(Property.MARGIN_LEFT, UnitValue.CreatePointValue(10)); @@ -229,14 +237,14 @@ public virtual void WidthSetToChildManyChildrenFlexRendererWithMaxWidthLowerThan [NUnit.Framework.Test] [LogMessage(iText.IO.Logs.IoLogMessageConstant.GET_NEXT_RENDERER_SHOULD_BE_OVERRIDDEN)] public virtual void GetNextRendererShouldBeOverriddenTest() { - FlexContainerRenderer flexContainerRenderer = new _FlexContainerRenderer_274(new Div()); + FlexContainerRenderer flexContainerRenderer = new _FlexContainerRenderer_281(new Div()); // Nothing is overridden NUnit.Framework.Assert.AreEqual(typeof(FlexContainerRenderer), flexContainerRenderer.GetNextRenderer().GetType ()); } - private sealed class _FlexContainerRenderer_274 : FlexContainerRenderer { - public _FlexContainerRenderer_274(Div baseArg1) + private sealed class _FlexContainerRenderer_281 : FlexContainerRenderer { + public _FlexContainerRenderer_281(Div baseArg1) : base(baseArg1) { } } @@ -265,7 +273,11 @@ public virtual void MinMaxWidthForFlexRendererWithWrapTest() { FlexContainerRenderer flexRenderer = new FlexContainerRenderer(new Div()); flexRenderer.SetProperty(Property.FLEX_WRAP, FlexWrapPropertyValue.WRAP); flexRenderer.SetProperty(Property.MAX_WIDTH, UnitValue.CreatePointValue(100)); - flexRenderer.SetProperty(Property.BORDER, new SolidBorder(5)); + SolidBorder border = new SolidBorder(5); + flexRenderer.SetProperty(Property.BORDER_TOP, border); + flexRenderer.SetProperty(Property.BORDER_RIGHT, border); + flexRenderer.SetProperty(Property.BORDER_BOTTOM, border); + flexRenderer.SetProperty(Property.BORDER_LEFT, border); // line 1 DivRenderer divRenderer1 = new DivRenderer(new Div()); divRenderer1.SetProperty(Property.MIN_WIDTH, UnitValue.CreatePointValue(30)); diff --git a/itext.tests/itext.layout.tests/itext/layout/renderer/FloatExampleTest.cs b/itext.tests/itext.layout.tests/itext/layout/renderer/FloatExampleTest.cs index 28634be034..b3f0f7bf97 100644 --- a/itext.tests/itext.layout.tests/itext/layout/renderer/FloatExampleTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/renderer/FloatExampleTest.cs @@ -198,7 +198,7 @@ private void AddContent(Document document, bool wrapImages, int imageWidthProper } div.Add(image); div.Add(new Paragraph("Figure for Div" + i + ": This is longer text that wraps This is longer text that wraps" - ).SetTextAlignment(TextAlignment.CENTER)).SetBold(); + ).SetTextAlignment(TextAlignment.CENTER)).SimulateBold(); document.Add(div); } else { diff --git a/itext.tests/itext.layout.tests/itext/layout/renderer/LineRendererUnitTest.cs b/itext.tests/itext.layout.tests/itext/layout/renderer/LineRendererUnitTest.cs index 3df96ee8fc..6f1465957b 100644 --- a/itext.tests/itext.layout.tests/itext/layout/renderer/LineRendererUnitTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/renderer/LineRendererUnitTest.cs @@ -20,6 +20,7 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ +using System; using System.Collections.Generic; using iText.Commons.Utils; using iText.IO.Font.Constants; @@ -369,5 +370,54 @@ public virtual void ReorderSimpleTest() { NUnit.Framework.Assert.AreSame(dummyImage4, childRenderers[6]); NUnit.Framework.Assert.AreSame(dummyImage5, childRenderers[7]); } + + [NUnit.Framework.Test] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.PROPERTY_IN_PERCENTS_NOT_SUPPORTED, Count = 2)] + public virtual void PercentFontSizeNotSupportedTest() { + LineRenderer lineRenderer = new LineRenderer(); + Leading leading = new Leading(Leading.MULTIPLIED, 1); + lineRenderer.SetProperty(Property.FONT_SIZE, UnitValue.CreatePercentValue(35)); + float topLeadingIndent = lineRenderer.GetTopLeadingIndent(leading); + float bottomLeadingIndent = lineRenderer.GetBottomLeadingIndent(leading); + NUnit.Framework.Assert.AreEqual(0.0, topLeadingIndent); + NUnit.Framework.Assert.AreEqual(7.0, bottomLeadingIndent); + } + + [NUnit.Framework.Test] + public virtual void LeadingTypeUnsupportedTest() { + LineRenderer lineRenderer = new LineRenderer(); + Leading leading = new Leading(new Leading(3, 3).GetLeadingType(), 1); + NUnit.Framework.Assert.Catch(typeof(InvalidOperationException), () => lineRenderer.GetTopLeadingIndent(leading + )); + NUnit.Framework.Assert.Catch(typeof(InvalidOperationException), () => lineRenderer.GetBottomLeadingIndent( + leading)); + } + + [NUnit.Framework.Test] + public virtual void GetGlyphTest() { + Document dummyDocument = CreateDummyDocument(); + TextRenderer textRenderer = CreateLayoutedTextRenderer("hello", dummyDocument); + LineRenderer.RendererGlyph rendererGlyph = new LineRenderer.RendererGlyph(null, textRenderer); + rendererGlyph.SetGlyph(new Glyph('\n', 0, '\n')); + Glyph glyph = rendererGlyph.GetGlyph(); + NUnit.Framework.Assert.AreEqual(1, glyph.GetChars().Length); + NUnit.Framework.Assert.AreEqual(0, glyph.GetWidth()); + NUnit.Framework.Assert.AreEqual(10, glyph.GetUnicode()); + NUnit.Framework.Assert.AreEqual(10, glyph.GetCode()); + NUnit.Framework.Assert.IsFalse(glyph.IsMark()); + } + + [NUnit.Framework.Test] + public virtual void GetRendererTest() { + Document dummyDocument = CreateDummyDocument(); + LineRenderer.RendererGlyph rendererGlyph = new LineRenderer.RendererGlyph(new Glyph('\n', 0, '\n'), null); + TextRenderer textRenderer = CreateLayoutedTextRenderer("hello", dummyDocument); + rendererGlyph.SetRenderer(textRenderer); + TextRenderer renderer = rendererGlyph.GetRenderer(); + NUnit.Framework.Assert.AreEqual("hello", renderer.GetText().ToString()); + NUnit.Framework.Assert.AreEqual(0, renderer.GetText().GetStart()); + NUnit.Framework.Assert.AreEqual(5, renderer.GetText().GetEnd()); + NUnit.Framework.Assert.AreEqual(0, renderer.GetText().GetIdx()); + } } } diff --git a/itext.tests/itext.layout.tests/itext/layout/renderer/LinkRendererUnitTest.cs b/itext.tests/itext.layout.tests/itext/layout/renderer/LinkRendererUnitTest.cs index 0e317262ba..d998d33b77 100644 --- a/itext.tests/itext.layout.tests/itext/layout/renderer/LinkRendererUnitTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/renderer/LinkRendererUnitTest.cs @@ -32,14 +32,14 @@ public class LinkRendererUnitTest : ExtendedITextTest { [NUnit.Framework.Test] [LogMessage(iText.IO.Logs.IoLogMessageConstant.GET_NEXT_RENDERER_SHOULD_BE_OVERRIDDEN)] public virtual void GetNextRendererShouldBeOverriddenTest() { - LinkRenderer linkRenderer = new _LinkRenderer_47(new Link("test", new PdfLinkAnnotation(new Rectangle(0, 0 + LinkRenderer linkRenderer = new _LinkRenderer_46(new Link("test", new PdfLinkAnnotation(new Rectangle(0, 0 )))); // Nothing is overridden NUnit.Framework.Assert.AreEqual(typeof(LinkRenderer), linkRenderer.GetNextRenderer().GetType()); } - private sealed class _LinkRenderer_47 : LinkRenderer { - public _LinkRenderer_47(Link baseArg1) + private sealed class _LinkRenderer_46 : LinkRenderer { + public _LinkRenderer_46(Link baseArg1) : base(baseArg1) { } } diff --git a/itext.tests/itext.layout.tests/itext/layout/renderer/ListRendererUnitTest.cs b/itext.tests/itext.layout.tests/itext/layout/renderer/ListRendererUnitTest.cs index 34f2e39323..21e92f243f 100644 --- a/itext.tests/itext.layout.tests/itext/layout/renderer/ListRendererUnitTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/renderer/ListRendererUnitTest.cs @@ -38,13 +38,13 @@ public class ListRendererUnitTest : RendererUnitTest { [NUnit.Framework.Test] [LogMessage(iText.IO.Logs.IoLogMessageConstant.GET_NEXT_RENDERER_SHOULD_BE_OVERRIDDEN)] public virtual void GetNextRendererShouldBeOverriddenTest() { - ListRenderer listRenderer = new _ListRenderer_57(new List()); + ListRenderer listRenderer = new _ListRenderer_56(new List()); // Nothing is overridden NUnit.Framework.Assert.AreEqual(typeof(ListRenderer), listRenderer.GetNextRenderer().GetType()); } - private sealed class _ListRenderer_57 : ListRenderer { - public _ListRenderer_57(List baseArg1) + private sealed class _ListRenderer_56 : ListRenderer { + public _ListRenderer_56(List baseArg1) : base(baseArg1) { } } diff --git a/itext.tests/itext.layout.tests/itext/layout/renderer/ParagraphRendererUnitTest.cs b/itext.tests/itext.layout.tests/itext/layout/renderer/ParagraphRendererUnitTest.cs index a65827829a..594b3858de 100644 --- a/itext.tests/itext.layout.tests/itext/layout/renderer/ParagraphRendererUnitTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/renderer/ParagraphRendererUnitTest.cs @@ -30,13 +30,13 @@ public class ParagraphRendererUnitTest : ExtendedITextTest { [NUnit.Framework.Test] [LogMessage(iText.IO.Logs.IoLogMessageConstant.GET_NEXT_RENDERER_SHOULD_BE_OVERRIDDEN)] public virtual void GetNextRendererShouldBeOverriddenTest() { - ParagraphRenderer paragraphRenderer = new _ParagraphRenderer_44(new Paragraph()); + ParagraphRenderer paragraphRenderer = new _ParagraphRenderer_43(new Paragraph()); // Nothing is overridden NUnit.Framework.Assert.AreEqual(typeof(ParagraphRenderer), paragraphRenderer.GetNextRenderer().GetType()); } - private sealed class _ParagraphRenderer_44 : ParagraphRenderer { - public _ParagraphRenderer_44(Paragraph baseArg1) + private sealed class _ParagraphRenderer_43 : ParagraphRenderer { + public _ParagraphRenderer_43(Paragraph baseArg1) : base(baseArg1) { } } diff --git a/itext.tests/itext.layout.tests/itext/layout/renderer/TabRendererUnitTest.cs b/itext.tests/itext.layout.tests/itext/layout/renderer/TabRendererUnitTest.cs index e481ff28d5..8ff4294798 100644 --- a/itext.tests/itext.layout.tests/itext/layout/renderer/TabRendererUnitTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/renderer/TabRendererUnitTest.cs @@ -30,13 +30,13 @@ public class TabRendererUnitTest : ExtendedITextTest { [NUnit.Framework.Test] [LogMessage(iText.IO.Logs.IoLogMessageConstant.GET_NEXT_RENDERER_SHOULD_BE_OVERRIDDEN)] public virtual void GetNextRendererShouldBeOverriddenTest() { - TabRenderer tabRenderer = new _TabRenderer_44(new Tab()); + TabRenderer tabRenderer = new _TabRenderer_43(new Tab()); // Nothing is overridden NUnit.Framework.Assert.AreEqual(typeof(TabRenderer), tabRenderer.GetNextRenderer().GetType()); } - private sealed class _TabRenderer_44 : TabRenderer { - public _TabRenderer_44(Tab baseArg1) + private sealed class _TabRenderer_43 : TabRenderer { + public _TabRenderer_43(Tab baseArg1) : base(baseArg1) { } } diff --git a/itext.tests/itext.layout.tests/itext/layout/renderer/TableRendererUnitTest.cs b/itext.tests/itext.layout.tests/itext/layout/renderer/TableRendererUnitTest.cs index 0222893bf6..042197c952 100644 --- a/itext.tests/itext.layout.tests/itext/layout/renderer/TableRendererUnitTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/renderer/TableRendererUnitTest.cs @@ -30,13 +30,13 @@ public class TableRendererUnitTest : ExtendedITextTest { [NUnit.Framework.Test] [LogMessage(iText.IO.Logs.IoLogMessageConstant.GET_NEXT_RENDERER_SHOULD_BE_OVERRIDDEN)] public virtual void GetNextRendererShouldBeOverriddenTest() { - TableRenderer tableRenderer = new _TableRenderer_44(new Table(1)); + TableRenderer tableRenderer = new _TableRenderer_43(new Table(1)); // Nothing is overridden NUnit.Framework.Assert.AreEqual(typeof(TableRenderer), tableRenderer.GetNextRenderer().GetType()); } - private sealed class _TableRenderer_44 : TableRenderer { - public _TableRenderer_44(Table baseArg1) + private sealed class _TableRenderer_43 : TableRenderer { + public _TableRenderer_43(Table baseArg1) : base(baseArg1) { } } diff --git a/itext.tests/itext.layout.tests/itext/layout/renderer/TargetCounterHandlerUnitTest.cs b/itext.tests/itext.layout.tests/itext/layout/renderer/TargetCounterHandlerUnitTest.cs index e2948b31c3..3b8f6841d4 100644 --- a/itext.tests/itext.layout.tests/itext/layout/renderer/TargetCounterHandlerUnitTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/renderer/TargetCounterHandlerUnitTest.cs @@ -32,10 +32,10 @@ namespace iText.Layout.Renderer { public class TargetCounterHandlerUnitTest : ExtendedITextTest { [NUnit.Framework.Test] public virtual void AddAndGetPageByDestinationNotDocumentRendererTest() { - RootRenderer documentRenderer = new _RootRenderer_41(); + RootRenderer documentRenderer = new _RootRenderer_40(); String id = "id"; int expectedPage = 5; - IRenderer renderer = new _TextRenderer_60(expectedPage, new Text("renderer")); + IRenderer renderer = new _TextRenderer_59(expectedPage, new Text("renderer")); renderer.SetParent(documentRenderer); renderer.SetProperty(Property.ID, id); TargetCounterHandler.AddPageByID(renderer); @@ -43,8 +43,8 @@ public virtual void AddAndGetPageByDestinationNotDocumentRendererTest() { NUnit.Framework.Assert.IsNull(page); } - private sealed class _RootRenderer_41 : RootRenderer { - public _RootRenderer_41() { + private sealed class _RootRenderer_40 : RootRenderer { + public _RootRenderer_40() { } public override IRenderer GetNextRenderer() { @@ -59,8 +59,8 @@ protected internal override LayoutArea UpdateCurrentArea(LayoutResult overflowRe } } - private sealed class _TextRenderer_60 : TextRenderer { - public _TextRenderer_60(int expectedPage, Text baseArg1) + private sealed class _TextRenderer_59 : TextRenderer { + public _TextRenderer_59(int expectedPage, Text baseArg1) : base(baseArg1) { this.expectedPage = expectedPage; } @@ -74,16 +74,16 @@ public override LayoutArea GetOccupiedArea() { [NUnit.Framework.Test] public virtual void IsValueDefinedForThisIdNotDocumentRendererTest() { - RootRenderer documentRenderer = new _RootRenderer_76(); + RootRenderer documentRenderer = new _RootRenderer_75(); String id = "id"; - IRenderer renderer = new _TextRenderer_94(new Text("renderer")); + IRenderer renderer = new _TextRenderer_93(new Text("renderer")); renderer.SetParent(documentRenderer); renderer.SetProperty(Property.ID, id); NUnit.Framework.Assert.IsFalse(TargetCounterHandler.IsValueDefinedForThisId(renderer, id)); } - private sealed class _RootRenderer_76 : RootRenderer { - public _RootRenderer_76() { + private sealed class _RootRenderer_75 : RootRenderer { + public _RootRenderer_75() { } public override IRenderer GetNextRenderer() { @@ -98,8 +98,8 @@ protected internal override LayoutArea UpdateCurrentArea(LayoutResult overflowRe } } - private sealed class _TextRenderer_94 : TextRenderer { - public _TextRenderer_94(Text baseArg1) + private sealed class _TextRenderer_93 : TextRenderer { + public _TextRenderer_93(Text baseArg1) : base(baseArg1) { } @@ -112,7 +112,7 @@ public override LayoutArea GetOccupiedArea() { public virtual void AddAndGetPageByDestinationNullOccupiedAreaTest() { DocumentRenderer documentRenderer = new DocumentRenderer(null); String id = "id"; - IRenderer renderer = new _TextRenderer_111(new Text("renderer")); + IRenderer renderer = new _TextRenderer_110(new Text("renderer")); renderer.SetParent(documentRenderer); renderer.SetProperty(Property.ID, id); TargetCounterHandler.AddPageByID(renderer); @@ -120,8 +120,8 @@ public virtual void AddAndGetPageByDestinationNullOccupiedAreaTest() { NUnit.Framework.Assert.IsNull(page); } - private sealed class _TextRenderer_111 : TextRenderer { - public _TextRenderer_111(Text baseArg1) + private sealed class _TextRenderer_110 : TextRenderer { + public _TextRenderer_110(Text baseArg1) : base(baseArg1) { } @@ -134,7 +134,7 @@ public override LayoutArea GetOccupiedArea() { public virtual void AddAndGetPageByDestinationDoubleAddIncreasedTest() { DocumentRenderer documentRenderer = new DocumentRenderer(null); String id = "id"; - IRenderer renderer = new _TextRenderer_130(new Text("renderer")); + IRenderer renderer = new _TextRenderer_129(new Text("renderer")); renderer.SetParent(documentRenderer); renderer.SetProperty(Property.ID, id); TargetCounterHandler.AddPageByID(renderer); @@ -144,8 +144,8 @@ public virtual void AddAndGetPageByDestinationDoubleAddIncreasedTest() { NUnit.Framework.Assert.AreEqual((int?)8, page); } - private sealed class _TextRenderer_130 : TextRenderer { - public _TextRenderer_130(Text baseArg1) + private sealed class _TextRenderer_129 : TextRenderer { + public _TextRenderer_129(Text baseArg1) : base(baseArg1) { this.expectedPage = 5; } @@ -163,7 +163,7 @@ public override LayoutArea GetOccupiedArea() { public virtual void AddAndGetPageByDestinationDoubleAddDecreasedTest() { DocumentRenderer documentRenderer = new DocumentRenderer(null); String id = "id"; - IRenderer renderer = new _TextRenderer_152(new Text("renderer")); + IRenderer renderer = new _TextRenderer_151(new Text("renderer")); renderer.SetParent(documentRenderer); renderer.SetProperty(Property.ID, id); TargetCounterHandler.AddPageByID(renderer); @@ -173,8 +173,8 @@ public virtual void AddAndGetPageByDestinationDoubleAddDecreasedTest() { NUnit.Framework.Assert.AreEqual((int?)2, page); } - private sealed class _TextRenderer_152 : TextRenderer { - public _TextRenderer_152(Text baseArg1) + private sealed class _TextRenderer_151 : TextRenderer { + public _TextRenderer_151(Text baseArg1) : base(baseArg1) { this.expectedPage = 5; } @@ -193,7 +193,7 @@ public virtual void AddAndGetPageByDestinationTest() { DocumentRenderer documentRenderer = new DocumentRenderer(null); String id = "id"; int expectedPage = 5; - IRenderer renderer = new _TextRenderer_175(expectedPage, new Text("renderer")); + IRenderer renderer = new _TextRenderer_174(expectedPage, new Text("renderer")); renderer.SetParent(documentRenderer); renderer.SetProperty(Property.ID, id); TargetCounterHandler.AddPageByID(renderer); @@ -206,8 +206,8 @@ public virtual void AddAndGetPageByDestinationTest() { NUnit.Framework.Assert.AreEqual((int?)expectedPage, page); } - private sealed class _TextRenderer_175 : TextRenderer { - public _TextRenderer_175(int expectedPage, Text baseArg1) + private sealed class _TextRenderer_174 : TextRenderer { + public _TextRenderer_174(int expectedPage, Text baseArg1) : base(baseArg1) { this.expectedPage = expectedPage; } @@ -223,7 +223,7 @@ public override LayoutArea GetOccupiedArea() { public virtual void IsRelayoutRequiredTest() { DocumentRenderer documentRenderer = new DocumentRenderer(null); String id = "id"; - IRenderer renderer = new _TextRenderer_200(new Text("renderer")); + IRenderer renderer = new _TextRenderer_199(new Text("renderer")); renderer.SetParent(documentRenderer); renderer.SetProperty(Property.ID, id); NUnit.Framework.Assert.IsFalse(documentRenderer.IsRelayoutRequired()); @@ -233,8 +233,8 @@ public virtual void IsRelayoutRequiredTest() { NUnit.Framework.Assert.IsFalse(documentRenderer.IsRelayoutRequired()); } - private sealed class _TextRenderer_200 : TextRenderer { - public _TextRenderer_200(Text baseArg1) + private sealed class _TextRenderer_199 : TextRenderer { + public _TextRenderer_199(Text baseArg1) : base(baseArg1) { } @@ -248,7 +248,7 @@ public override LayoutArea GetOccupiedArea() { public virtual void CopyConstructorTest() { DocumentRenderer documentRenderer = new DocumentRenderer(null); String id = "id"; - IRenderer renderer = new _TextRenderer_222(new Text("renderer")); + IRenderer renderer = new _TextRenderer_221(new Text("renderer")); renderer.SetParent(documentRenderer); renderer.SetProperty(Property.ID, id); TargetCounterHandler.AddPageByID(renderer); @@ -256,8 +256,8 @@ public virtual void CopyConstructorTest() { NUnit.Framework.Assert.IsTrue(copy.IsRelayoutRequired()); } - private sealed class _TextRenderer_222 : TextRenderer { - public _TextRenderer_222(Text baseArg1) + private sealed class _TextRenderer_221 : TextRenderer { + public _TextRenderer_221(Text baseArg1) : base(baseArg1) { } @@ -272,7 +272,7 @@ public virtual void IsValueDefinedForThisId() { DocumentRenderer documentRenderer = new DocumentRenderer(null); String id = "id"; String notAddedId = "not added id"; - IRenderer renderer = new _TextRenderer_243(new Text("renderer")); + IRenderer renderer = new _TextRenderer_242(new Text("renderer")); renderer.SetParent(documentRenderer); renderer.SetProperty(Property.ID, id); TargetCounterHandler.AddPageByID(renderer); @@ -280,8 +280,8 @@ public virtual void IsValueDefinedForThisId() { NUnit.Framework.Assert.IsFalse(TargetCounterHandler.IsValueDefinedForThisId(renderer, notAddedId)); } - private sealed class _TextRenderer_243 : TextRenderer { - public _TextRenderer_243(Text baseArg1) + private sealed class _TextRenderer_242 : TextRenderer { + public _TextRenderer_242(Text baseArg1) : base(baseArg1) { } diff --git a/itext.tests/itext.layout.tests/itext/layout/renderer/TextRendererIntegrationTest.cs b/itext.tests/itext.layout.tests/itext/layout/renderer/TextRendererIntegrationTest.cs index 3c18179532..a1a2a5c212 100644 --- a/itext.tests/itext.layout.tests/itext/layout/renderer/TextRendererIntegrationTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/renderer/TextRendererIntegrationTest.cs @@ -21,6 +21,7 @@ You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ using System; +using System.IO; using System.Text; using iText.IO.Font; using iText.IO.Font.Otf; @@ -29,6 +30,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Kernel.Font; using iText.Kernel.Geom; using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Canvas; using iText.Kernel.Utils; using iText.Layout; using iText.Layout.Borders; @@ -467,19 +469,19 @@ public virtual void CustomTextRendererShouldOverrideGetNextRendererTest() { Document doc = new Document(pdfDoc); Text text = new Text("If getNextRenderer() is not overridden and text overflows to the next line," + " then customizations are not applied. " ); - text.SetNextRenderer(new _TextRenderer_739(text)); + text.SetNextRenderer(new _TextRenderer_742(text)); doc.Add(new Paragraph(text)); text = new Text("If getNextRenderer() is overridden and text overflows to the next line, " + "then customizations are applied. " ); - text.SetNextRenderer(new _TextRenderer_755(text)); + text.SetNextRenderer(new _TextRenderer_758(text)); doc.Add(new Paragraph(text)); doc.Close(); NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder )); } - private sealed class _TextRenderer_739 : TextRenderer { - public _TextRenderer_739(Text baseArg1) + private sealed class _TextRenderer_742 : TextRenderer { + public _TextRenderer_742(Text baseArg1) : base(baseArg1) { } @@ -490,8 +492,8 @@ public override void Draw(DrawContext drawContext) { } } - private sealed class _TextRenderer_755 : TextRenderer { - public _TextRenderer_755(Text baseArg1) + private sealed class _TextRenderer_758 : TextRenderer { + public _TextRenderer_758(Text baseArg1) : base(baseArg1) { } @@ -585,7 +587,7 @@ public virtual void CustomTextRendererShouldOverrideCreateCopyTest() { longTextBuilder.Append("Дзень добры, свет! Hallo Welt! "); } iText.Layout.Element.Text text = new iText.Layout.Element.Text(longTextBuilder.ToString()); - text.SetNextRenderer(new _TextRenderer_890(text)); + text.SetNextRenderer(new _TextRenderer_893(text)); doc.Add(new Paragraph(text)); text.SetNextRenderer(new TextRendererIntegrationTest.TextRendererWithOverriddenGetNextRenderer(text)); doc.Add(new Paragraph(text)); @@ -594,8 +596,8 @@ public virtual void CustomTextRendererShouldOverrideCreateCopyTest() { )); } - private sealed class _TextRenderer_890 : TextRenderer { - public _TextRenderer_890(iText.Layout.Element.Text baseArg1) + private sealed class _TextRenderer_893 : TextRenderer { + public _TextRenderer_893(iText.Layout.Element.Text baseArg1) : base(baseArg1) { } @@ -611,6 +613,104 @@ public override IRenderer GetNextRenderer() { } } + [NUnit.Framework.Test] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.OCCUPIED_AREA_HAS_NOT_BEEN_INITIALIZED, Count = 1)] + public virtual void DrawWithSkewAndHorizontalScalingTest() { + using (PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new MemoryStream()))) { + Document doc = new Document(pdfDocument); + iText.Layout.Element.Text text = new iText.Layout.Element.Text("test string").SetTextRise(0).SetWordSpacing + (0).SetSkew(10, 10).SetHorizontalScaling(2); + Paragraph paragraph = new Paragraph().Add(text); + paragraph.SetNextRenderer(new _TextRenderer_932(text)); + doc.Add(paragraph); + String contentstream = iText.Commons.Utils.JavaUtil.GetStringForBytes(doc.GetPdfDocument().GetPage(1).GetContentBytes + (), System.Text.Encoding.UTF8); + NUnit.Framework.Assert.IsTrue(contentstream.Contains("test string")); + } + } + + private sealed class _TextRenderer_932 : TextRenderer { + public _TextRenderer_932(iText.Layout.Element.Text baseArg1) + : base(baseArg1) { + } + + public override void Draw(DrawContext drawContext) { + drawContext.GetCanvas().SaveState().Rectangle(this.occupiedArea.GetBBox()).Fill().RestoreState(); + base.Draw(drawContext); + } + + public override IRenderer GetNextRenderer() { + return new TextRendererIntegrationTest.TextRendererWithOverriddenGetNextRenderer((iText.Layout.Element.Text + )this.modelElement); + } + } + + [NUnit.Framework.Test] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.OCCUPIED_AREA_HAS_NOT_BEEN_INITIALIZED, Count = 1)] + public virtual void DrawTextRenderingModeFillStrokeTest() { + using (PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new MemoryStream()))) { + Document doc = new Document(pdfDocument); + iText.Layout.Element.Text text = new iText.Layout.Element.Text("test string").SetTextRenderingMode(PdfCanvasConstants.TextRenderingMode + .FILL_STROKE); + Paragraph paragraph = new Paragraph().Add(text).SetBackgroundColor(ColorConstants.YELLOW).SetWidth(10).SetStrokeWidth + (1f).SetStrokeColor(null).SetBorder(new SolidBorder(1)); + paragraph.SetNextRenderer(new _TextRenderer_970(text)); + doc.Add(paragraph); + String contentstream = iText.Commons.Utils.JavaUtil.GetStringForBytes(doc.GetPdfDocument().GetPage(1).GetContentBytes + (), System.Text.Encoding.UTF8); + NUnit.Framework.Assert.IsTrue(contentstream.Contains("test string")); + } + } + + private sealed class _TextRenderer_970 : TextRenderer { + public _TextRenderer_970(iText.Layout.Element.Text baseArg1) + : base(baseArg1) { + } + + public override void Draw(DrawContext drawContext) { + drawContext.GetCanvas().SaveState().Rectangle(this.occupiedArea.GetBBox()).Fill().RestoreState(); + base.Draw(drawContext); + } + + public override IRenderer GetNextRenderer() { + return new TextRendererIntegrationTest.TextRendererWithOverriddenGetNextRenderer((iText.Layout.Element.Text + )this.modelElement); + } + } + + [NUnit.Framework.Test] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.OCCUPIED_AREA_HAS_NOT_BEEN_INITIALIZED, Count = 1)] + public virtual void FontColorNullTest() { + using (PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new MemoryStream()))) { + Document doc = new Document(pdfDocument); + iText.Layout.Element.Text text = new iText.Layout.Element.Text("test string").SetTextRenderingMode(PdfCanvasConstants.TextRenderingMode + .FILL_STROKE); + Paragraph paragraph = new Paragraph().Add(text); + paragraph.SetNextRenderer(new _TextRenderer_1003(text)); + doc.Add(paragraph); + String contentstream = iText.Commons.Utils.JavaUtil.GetStringForBytes(doc.GetPdfDocument().GetPage(1).GetContentBytes + (), System.Text.Encoding.UTF8); + NUnit.Framework.Assert.IsTrue(contentstream.Contains("test string")); + } + } + + private sealed class _TextRenderer_1003 : TextRenderer { + public _TextRenderer_1003(iText.Layout.Element.Text baseArg1) + : base(baseArg1) { + } + + public override void Draw(DrawContext drawContext) { + drawContext.GetCanvas().SaveState().Rectangle(this.occupiedArea.GetBBox()).Fill().RestoreState(); + this.SetProperty(Property.FONT_COLOR, new TransparentColor(ColorConstants.RED)); + base.Draw(drawContext); + } + + public override IRenderer GetNextRenderer() { + return new TextRendererIntegrationTest.TextRendererWithOverriddenGetNextRenderer((iText.Layout.Element.Text + )this.modelElement); + } + } + private class TextRendererWithOverriddenGetNextRenderer : TextRenderer { public TextRendererWithOverriddenGetNextRenderer(iText.Layout.Element.Text textElement) : base(textElement) { diff --git a/itext.tests/itext.layout.tests/itext/layout/renderer/TextRendererTest.cs b/itext.tests/itext.layout.tests/itext/layout/renderer/TextRendererTest.cs index ed27308ffd..c1a67ffd78 100644 --- a/itext.tests/itext.layout.tests/itext/layout/renderer/TextRendererTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/renderer/TextRendererTest.cs @@ -110,8 +110,8 @@ public virtual void SetTextGlyphLineAndPositionsParamTest() { glyphLine.Add(glyph); } renderer.SetText(new GlyphLine(), pdfFont); - glyphLine.start = 1; - glyphLine.end = 2; + glyphLine.SetStart(1); + glyphLine.SetEnd(2); renderer.SetText(glyphLine, pdfFont); GlyphLine actualLine = renderer.GetText(); NUnit.Framework.Assert.IsFalse(actualLine == glyphLine); @@ -120,8 +120,8 @@ public virtual void SetTextGlyphLineAndPositionsParamTest() { // Check that the glyph line has been processed using the replaceSpecialWhitespaceGlyphs method NUnit.Framework.Assert.AreEqual(space.GetCode(), glyph_1.GetCode()); NUnit.Framework.Assert.AreEqual(space.GetWidth(), glyph_1.GetWidth()); - NUnit.Framework.Assert.AreEqual(1, actualLine.start); - NUnit.Framework.Assert.AreEqual(2, actualLine.end); + NUnit.Framework.Assert.AreEqual(1, actualLine.GetStart()); + NUnit.Framework.Assert.AreEqual(2, actualLine.GetEnd()); } ///
    @@ -263,7 +263,6 @@ public virtual void OverflowWrapBreakWordProperty() { [NUnit.Framework.Test] public virtual void OverflowWrapAnywhereBoldSimulationMaxWidth() { Text text = new Text("wow"); - text.SetBold(); TextRenderer textRenderer = (TextRenderer)text.GetRenderer(); textRenderer.SetParent(CreateDummyDocument().GetRenderer()); float maxWidthNoOverflowWrap = textRenderer.GetMinMaxWidth().GetMaxWidth(); @@ -275,7 +274,7 @@ public virtual void OverflowWrapAnywhereBoldSimulationMaxWidth() { [NUnit.Framework.Test] public virtual void OverflowWrapAnywhereItalicSimulationMaxWidth() { Text text = new Text("wow"); - text.SetItalic(); + text.SimulateItalic(); TextRenderer textRenderer = (TextRenderer)text.GetRenderer(); textRenderer.SetParent(CreateDummyDocument().GetRenderer()); float maxWidthNoOverflowWrap = textRenderer.GetMinMaxWidth().GetMaxWidth(); @@ -291,7 +290,7 @@ public virtual void OverflowWrapAnywhereBoldSimulationMinWidth() { TextRenderer textRenderer = (TextRenderer)text.GetRenderer(); textRenderer.SetParent(CreateDummyDocument().GetRenderer()); float minWidthNoBoldSimulation = textRenderer.GetMinMaxWidth().GetMinWidth(); - text.SetBold(); + text.SimulateBold(); float minWidthAndBoldSimulation = textRenderer.GetMinMaxWidth().GetMinWidth(); NUnit.Framework.Assert.IsTrue(minWidthAndBoldSimulation > minWidthNoBoldSimulation); } @@ -303,7 +302,7 @@ public virtual void OverflowWrapAnywhereItalicSimulationMinWidth() { TextRenderer textRenderer = (TextRenderer)text.GetRenderer(); textRenderer.SetParent(CreateDummyDocument().GetRenderer()); float minWidthNoItalicSimulation = textRenderer.GetMinMaxWidth().GetMinWidth(); - text.SetItalic(); + text.SimulateItalic(); float minWidthAndItalicSimulation = textRenderer.GetMinMaxWidth().GetMinWidth(); NUnit.Framework.Assert.IsTrue(minWidthAndItalicSimulation > minWidthNoItalicSimulation); } diff --git a/itext.tests/itext.layout.tests/itext/layout/renderer/TextRendererUnitTest.cs b/itext.tests/itext.layout.tests/itext/layout/renderer/TextRendererUnitTest.cs index 111e2045ee..8dc8a5ef06 100644 --- a/itext.tests/itext.layout.tests/itext/layout/renderer/TextRendererUnitTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/renderer/TextRendererUnitTest.cs @@ -30,13 +30,13 @@ public class TextRendererUnitTest : ExtendedITextTest { [NUnit.Framework.Test] [LogMessage(iText.IO.Logs.IoLogMessageConstant.GET_NEXT_RENDERER_SHOULD_BE_OVERRIDDEN)] public virtual void GetNextRendererShouldBeOverriddenTest() { - TextRenderer textRenderer = new _TextRenderer_44(new Text("tet")); + TextRenderer textRenderer = new _TextRenderer_43(new Text("tet")); // Nothing is overridden NUnit.Framework.Assert.AreEqual(typeof(TextRenderer), textRenderer.GetNextRenderer().GetType()); } - private sealed class _TextRenderer_44 : TextRenderer { - public _TextRenderer_44(Text baseArg1) + private sealed class _TextRenderer_43 : TextRenderer { + public _TextRenderer_43(Text baseArg1) : base(baseArg1) { } } diff --git a/itext.tests/itext.layout.tests/itext/layout/renderer/WordWrapUnitTest.cs b/itext.tests/itext.layout.tests/itext/layout/renderer/WordWrapUnitTest.cs index 7f50e4bd97..e0ec78ea56 100644 --- a/itext.tests/itext.layout.tests/itext/layout/renderer/WordWrapUnitTest.cs +++ b/itext.tests/itext.layout.tests/itext/layout/renderer/WordWrapUnitTest.cs @@ -118,7 +118,7 @@ public virtual void NoNeedToSplitTextRendererOnLineSplit() { TextRenderer textRendererFirst = new TextRenderer(new Text("")); textRendererFirst.SetProperty(Property.FONT, pdfFont); textRendererFirst.SetText(thai.JSubstring(0, 8)); - textRendererFirst.text.start = 3; + textRendererFirst.text.SetStart(3); textRendererFirst.SetSpecialScriptsWordBreakPoints(new List(JavaUtil.ArraysAsList(3, 8))); textRendererFirst.SetParent(document.GetRenderer()); float longestWordLength = textRendererFirst.GetMinMaxWidth().GetMaxWidth(); diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FloatAndAlignmentTest/cmp_blockWithLimitedHeightAndFixedPositionTest.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FixedHeightTest/cmp_blockWithLimitedHeightAndFixedPositionTest.pdf similarity index 100% rename from itext.tests/itext.layout.tests/resources/itext/layout/FloatAndAlignmentTest/cmp_blockWithLimitedHeightAndFixedPositionTest.pdf rename to itext.tests/itext.layout.tests/resources/itext/layout/FixedHeightTest/cmp_blockWithLimitedHeightAndFixedPositionTest.pdf diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FloatAndAlignmentTest/cmp_listWithFixedPositionTest.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FixedHeightTest/cmp_listWithFixedPositionTest.pdf similarity index 100% rename from itext.tests/itext.layout.tests/resources/itext/layout/FloatAndAlignmentTest/cmp_listWithFixedPositionTest.pdf rename to itext.tests/itext.layout.tests/resources/itext/layout/FixedHeightTest/cmp_listWithFixedPositionTest.pdf diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_heightPropertyTest.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_heightPropertyTest.pdf index 0354980428..7392614d16 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_heightPropertyTest.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_heightPropertyTest.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_reverseRowWrapRtlStartTest.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_reverseRowWrapRtlStartTest.pdf index e3d8056155..9c406db2a6 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_reverseRowWrapRtlStartTest.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_reverseRowWrapRtlStartTest.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_reverseWrapEndHeightTest.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_reverseWrapEndHeightTest.pdf index 211d59f452..321f59abf9 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_reverseWrapEndHeightTest.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_reverseWrapEndHeightTest.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_reverseWrapEndTest.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_reverseWrapEndTest.pdf index cd2445f4a9..10caaa24b3 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_reverseWrapEndTest.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_reverseWrapEndTest.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_reverseWrapStartHeightTest.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_reverseWrapStartHeightTest.pdf index 9fea427496..43021b4eab 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_reverseWrapStartHeightTest.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_reverseWrapStartHeightTest.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_reverseWrapStartTest.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_reverseWrapStartTest.pdf index 42834eb28f..1d73f8432c 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_reverseWrapStartTest.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_reverseWrapStartTest.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_rowWrapRtlStartTest.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_rowWrapRtlStartTest.pdf index 3ce4a23e5a..3aa2d15472 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_rowWrapRtlStartTest.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_rowWrapRtlStartTest.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_simpleTest.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_simpleTest.pdf index a86b7db40d..b607e5fafc 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_simpleTest.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_simpleTest.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_simpleWrapCenterTest.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_simpleWrapCenterTest.pdf index 7794fafb5e..d45eb4b84c 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_simpleWrapCenterTest.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_simpleWrapCenterTest.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_simpleWrapEndTest.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_simpleWrapEndTest.pdf index 93545e96dc..1ab7400b18 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_simpleWrapEndTest.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_simpleWrapEndTest.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_simpleWrapStartTest.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_simpleWrapStartTest.pdf index 818bec3412..7b26a65b6f 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_simpleWrapStartTest.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_simpleWrapStartTest.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_simpleWrapTest.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_simpleWrapTest.pdf index d2c6611bd5..db56524e72 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_simpleWrapTest.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_simpleWrapTest.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_smallTrailingElementTest.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_smallTrailingElementTest.pdf index 87e98e31b2..f0f21d1941 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_smallTrailingElementTest.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_smallTrailingElementTest.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_splitOverSeveralPagesTest.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_splitOverSeveralPagesTest.pdf index 5a8c264b27..29d88be436 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_splitOverSeveralPagesTest.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/cmp_splitOverSeveralPagesTest.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/tableInFlexOnSplitTest.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/tableInFlexOnSplitTest.pdf new file mode 100644 index 0000000000..fc7da22c68 Binary files /dev/null and b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerSplitTest/tableInFlexOnSplitTest.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest1.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest1.pdf index a4ef980d1a..fa84d5c4b5 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest1.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest1.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest10.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest10.pdf index a575194b9f..95a9a81897 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest10.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest10.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest11.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest11.pdf index f93d8c9c3a..da35aba9d5 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest11.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest11.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest3.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest3.pdf index 62c0d5dc01..3edff93e99 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest3.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest3.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest5.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest5.pdf index b7add60e54..68c498b71f 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest5.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest5.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest6.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest6.pdf index 9e8ccdea33..7775459559 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest6.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest6.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest7.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest7.pdf index 630704d336..3dadeb443e 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest7.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest7.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest8.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest8.pdf index 694d972ce5..4bcbcd9197 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest8.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenDontFitVerticallyTest8.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenFitContainerDoesNotFitVerticallyTest10.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenFitContainerDoesNotFitVerticallyTest10.pdf index b4b702e4db..a2c16c3562 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenFitContainerDoesNotFitVerticallyTest10.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenFitContainerDoesNotFitVerticallyTest10.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenFitContainerDoesNotFitVerticallyTest11.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenFitContainerDoesNotFitVerticallyTest11.pdf index 31635a88da..49bdb4f34b 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenFitContainerDoesNotFitVerticallyTest11.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenFitContainerDoesNotFitVerticallyTest11.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenFitContainerDoesNotFitVerticallyTest3.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenFitContainerDoesNotFitVerticallyTest3.pdf index 25d8e935be..5ad45bcda8 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenFitContainerDoesNotFitVerticallyTest3.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenFitContainerDoesNotFitVerticallyTest3.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenFitContainerDoesNotFitVerticallyTest6.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenFitContainerDoesNotFitVerticallyTest6.pdf index f39a46bd71..ce379965db 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenFitContainerDoesNotFitVerticallyTest6.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenFitContainerDoesNotFitVerticallyTest6.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenFitContainerDoesNotFitVerticallyTest8.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenFitContainerDoesNotFitVerticallyTest8.pdf index 0fd5301058..61c547d237 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenFitContainerDoesNotFitVerticallyTest8.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FlexContainerTest/cmp_flexContainerDifferentChildrenFitContainerDoesNotFitVerticallyTest8.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FontSelectorTest/cmp_cyrillicAndLatinGroup.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FontSelectorTest/cmp_cyrillicAndLatinGroup.pdf index 3e6f446fc3..4ed5f7f8cf 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FontSelectorTest/cmp_cyrillicAndLatinGroup.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FontSelectorTest/cmp_cyrillicAndLatinGroup.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FontSelectorTest/cmp_cyrillicAndLatinGroup2.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FontSelectorTest/cmp_cyrillicAndLatinGroup2.pdf index 44bac01210..3606e69da7 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FontSelectorTest/cmp_cyrillicAndLatinGroup2.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FontSelectorTest/cmp_cyrillicAndLatinGroup2.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FontSelectorTest/cmp_cyrillicAndLatinGroup3.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FontSelectorTest/cmp_cyrillicAndLatinGroup3.pdf index da66bbfdab..fbe7d8afa0 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FontSelectorTest/cmp_cyrillicAndLatinGroup3.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FontSelectorTest/cmp_cyrillicAndLatinGroup3.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FontSelectorTest/cmp_cyrillicAndLatinWithUnicodeRange.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FontSelectorTest/cmp_cyrillicAndLatinWithUnicodeRange.pdf index f69a8b18e1..b4ccf49431 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FontSelectorTest/cmp_cyrillicAndLatinWithUnicodeRange.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FontSelectorTest/cmp_cyrillicAndLatinWithUnicodeRange.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/FontSelectorTest/cmp_duplicateFontWithUnicodeRange.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/FontSelectorTest/cmp_duplicateFontWithUnicodeRange.pdf index 59e617c30b..d28b1a7a4b 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/FontSelectorTest/cmp_duplicateFontWithUnicodeRange.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/FontSelectorTest/cmp_duplicateFontWithUnicodeRange.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/GridContainerTest/cmp_basicThreeColumnsTest.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/GridContainerTest/cmp_basicThreeColumnsTest.pdf index 89371e7953..0aa4e37347 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/GridContainerTest/cmp_basicThreeColumnsTest.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/GridContainerTest/cmp_basicThreeColumnsTest.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/GridContainerTest/cmp_borderBoxChild.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/GridContainerTest/cmp_borderBoxChild.pdf new file mode 100644 index 0000000000..b8387843b9 Binary files /dev/null and b/itext.tests/itext.layout.tests/resources/itext/layout/GridContainerTest/cmp_borderBoxChild.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/GridContainerTest/cmp_borderBoxWithNoBordersTest.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/GridContainerTest/cmp_borderBoxWithNoBordersTest.pdf new file mode 100644 index 0000000000..db964dcf55 Binary files /dev/null and b/itext.tests/itext.layout.tests/resources/itext/layout/GridContainerTest/cmp_borderBoxWithNoBordersTest.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/HyphenationTreeTest/hyphen_pattern.xml b/itext.tests/itext.layout.tests/resources/itext/layout/HyphenationTreeTest/hyphen_pattern.xml new file mode 100644 index 0000000000..fd7ac3b907 --- /dev/null +++ b/itext.tests/itext.layout.tests/resources/itext/layout/HyphenationTreeTest/hyphen_pattern.xml @@ -0,0 +1,10 @@ + + + + + +.ab4i +.ac4i +.ad4i + + diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/HyphenationTreeTest/only_classes.xml b/itext.tests/itext.layout.tests/resources/itext/layout/HyphenationTreeTest/only_classes.xml new file mode 100644 index 0000000000..070523640b --- /dev/null +++ b/itext.tests/itext.layout.tests/resources/itext/layout/HyphenationTreeTest/only_classes.xml @@ -0,0 +1,35 @@ + + + + + + + +aA +bB +cC +dD +eE +fF +gG +hH +iI +jJ +kK +lL +mM +nN +oO +pP +qQ +rR +sS +tT +uU +vV +wW +xX +yY +zZ + + diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/LayoutTaggingTest/cmp_notAsciiCharTest.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/LayoutTaggingTest/cmp_notAsciiCharTest.pdf index 5ae6c5ea5d..b743463bab 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/LayoutTaggingTest/cmp_notAsciiCharTest.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/LayoutTaggingTest/cmp_notAsciiCharTest.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/RotationTest/cmp_ignorePageRotationForContent.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/RotationTest/cmp_ignorePageRotationForContent.pdf new file mode 100644 index 0000000000..04824ffaa3 Binary files /dev/null and b/itext.tests/itext.layout.tests/resources/itext/layout/RotationTest/cmp_ignorePageRotationForContent.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/RotationTest/rotated.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/RotationTest/rotated.pdf new file mode 100644 index 0000000000..54fd51c3d0 Binary files /dev/null and b/itext.tests/itext.layout.tests/resources/itext/layout/RotationTest/rotated.pdf differ diff --git a/itext.tests/itext.layout.tests/resources/itext/layout/XMPWriterTest/cmp_addUAXMPMetaDataNotTaggedTest.pdf b/itext.tests/itext.layout.tests/resources/itext/layout/XMPWriterTest/cmp_addUAXMPMetaDataNotTaggedTest.pdf index d7ea61b08e..53e7e0f0cc 100644 Binary files a/itext.tests/itext.layout.tests/resources/itext/layout/XMPWriterTest/cmp_addUAXMPMetaDataNotTaggedTest.pdf and b/itext.tests/itext.layout.tests/resources/itext/layout/XMPWriterTest/cmp_addUAXMPMetaDataNotTaggedTest.pdf differ diff --git a/itext.tests/itext.pdfa.tests/Properties/AssemblyInfo.cs b/itext.tests/itext.pdfa.tests/Properties/AssemblyInfo.cs index 411a4949ce..9171132b3c 100644 --- a/itext.tests/itext.pdfa.tests/Properties/AssemblyInfo.cs +++ b/itext.tests/itext.pdfa.tests/Properties/AssemblyInfo.cs @@ -15,9 +15,9 @@ [assembly: Guid("b7c0e021-71ac-4c97-9a51-8356f1bd53c7")] -[assembly: AssemblyVersion("8.0.5.0")] -[assembly: AssemblyFileVersion("8.0.5.0")] -[assembly: AssemblyInformationalVersion("8.0.5")] +[assembly: AssemblyVersion("9.0.0.0")] +[assembly: AssemblyFileVersion("9.0.0.0")] +[assembly: AssemblyInformationalVersion("9.0.0")] #if !NETSTANDARD2_0 [assembly: NUnit.Framework.Timeout(300000)] diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1AcroFormCheckTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1AcroFormCheckTest.cs index defcc479c2..ee4d8522b9 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1AcroFormCheckTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1AcroFormCheckTest.cs @@ -49,8 +49,8 @@ public static void BeforeClass() { public virtual void AcroFormCheck01() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary acroForm = new PdfDictionary(); acroForm.Put(PdfName.NeedAppearances, new PdfBoolean(true)); @@ -66,8 +66,8 @@ public virtual void AcroFormCheck02() { String cmpPdf = cmpFolder + "cmp_pdfA1b_acroFormCheck02.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary acroForm = new PdfDictionary(); acroForm.Put(PdfName.NeedAppearances, new PdfBoolean(false)); @@ -82,8 +82,8 @@ public virtual void AcroFormCheck03() { String cmpPdf = cmpFolder + "cmp_pdfA1b_acroFormCheck03.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary acroForm = new PdfDictionary(); doc.GetCatalog().Put(PdfName.AcroForm, acroForm); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1ActionCheckTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1ActionCheckTest.cs index 841ff80464..f3557354f3 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1ActionCheckTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1ActionCheckTest.cs @@ -39,8 +39,8 @@ public class PdfA1ActionCheckTest : ExtendedITextTest { public virtual void ActionCheck01() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary openActions = new PdfDictionary(); openActions.Put(PdfName.S, PdfName.Launch); @@ -54,8 +54,8 @@ public virtual void ActionCheck01() { public virtual void ActionCheck02() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary openActions = new PdfDictionary(); openActions.Put(PdfName.S, PdfName.Hide); @@ -69,8 +69,8 @@ public virtual void ActionCheck02() { public virtual void ActionCheck03() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary openActions = new PdfDictionary(); openActions.Put(PdfName.S, PdfName.Sound); @@ -84,8 +84,8 @@ public virtual void ActionCheck03() { public virtual void ActionCheck04() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary openActions = new PdfDictionary(); openActions.Put(PdfName.S, PdfName.Movie); @@ -99,8 +99,8 @@ public virtual void ActionCheck04() { public virtual void ActionCheck05() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary openActions = new PdfDictionary(); openActions.Put(PdfName.S, PdfName.ResetForm); @@ -114,8 +114,8 @@ public virtual void ActionCheck05() { public virtual void ActionCheck06() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary openActions = new PdfDictionary(); openActions.Put(PdfName.S, PdfName.ImportData); @@ -129,8 +129,8 @@ public virtual void ActionCheck06() { public virtual void ActionCheck07() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary openActions = new PdfDictionary(); openActions.Put(PdfName.S, PdfName.JavaScript); @@ -144,8 +144,8 @@ public virtual void ActionCheck07() { public virtual void ActionCheck08() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary openActions = new PdfDictionary(); openActions.Put(PdfName.S, PdfName.Named); @@ -160,8 +160,8 @@ public virtual void ActionCheck08() { public virtual void ActionCheck09() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); page.SetAdditionalAction(PdfName.C, PdfAction.CreateJavaScript("js")); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => doc.Close()); @@ -173,8 +173,8 @@ public virtual void ActionCheck09() { public virtual void ActionCheck10() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); PdfDictionary action = new PdfDictionary(); action.Put(PdfName.S, PdfName.SetState); @@ -188,8 +188,8 @@ public virtual void ActionCheck10() { public virtual void ActionCheck11() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); doc.GetCatalog().SetAdditionalAction(PdfName.C, PdfAction.CreateJavaScript("js")); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => doc.Close()); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1AnnotationCheckTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1AnnotationCheckTest.cs index 787f4b324b..83669ab351 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1AnnotationCheckTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1AnnotationCheckTest.cs @@ -55,8 +55,8 @@ public static void BeforeClass() { public virtual void AnnotationCheckTest01() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); Rectangle rect = new Rectangle(100, 100, 100, 100); PdfAnnotation annot = new PdfFileAttachmentAnnotation(rect); @@ -70,8 +70,8 @@ public virtual void AnnotationCheckTest01() { public virtual void AnnotationCheckTest02() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); Rectangle rect = new Rectangle(100, 100, 100, 100); PdfMarkupAnnotation annot = new PdfTextAnnotation(rect); @@ -87,8 +87,8 @@ public virtual void AnnotationCheckTest02() { public virtual void AnnotationCheckTest03() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); Rectangle rect = new Rectangle(100, 100, 100, 100); PdfMarkupAnnotation annot = new PdfTextAnnotation(rect); @@ -103,8 +103,8 @@ public virtual void AnnotationCheckTest03() { public virtual void AnnotationCheckTest04() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); Rectangle rect = new Rectangle(100, 100, 100, 100); PdfMarkupAnnotation annot = new PdfTextAnnotation(rect); @@ -120,8 +120,8 @@ public virtual void AnnotationCheckTest04() { public virtual void AnnotationCheckTest05() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); Rectangle rect = new Rectangle(100, 100, 100, 100); PdfAnnotation annot = new PdfWidgetAnnotation(rect); @@ -139,8 +139,8 @@ public virtual void AnnotationCheckTest05() { public virtual void AnnotationCheckTest06() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); Rectangle rect = new Rectangle(100, 100, 100, 100); PdfAnnotation annot = new PdfWidgetAnnotation(rect); @@ -158,8 +158,8 @@ public virtual void AnnotationCheckTest07() { String cmpPdf = cmpFolder + "cmp_pdfA1b_annotationCheckTest07.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); Rectangle rect = new Rectangle(100, 100, 100, 100); PdfMarkupAnnotation annot = new PdfTextAnnotation(rect); @@ -177,8 +177,8 @@ public virtual void AnnotationCheckTest08() { String cmpPdf = cmpFolder + "cmp_pdfA1a_annotationCheckTest08.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_1_4)); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1A, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1A, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.SetTagged(); doc.GetCatalog().SetLang(new PdfString("en-US")); PdfPage page = doc.AddNewPage(); @@ -198,8 +198,8 @@ public virtual void AnnotationCheckTest09() { String cmpPdf = cmpFolder + "cmp_pdfA1a_annotationCheckTest09.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1A, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1A, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.SetTagged(); doc.GetCatalog().SetLang(new PdfString("en-US")); PdfPage page = doc.AddNewPage(); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1CanvasCheckTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1CanvasCheckTest.cs index 8475a5beac..f07507d501 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1CanvasCheckTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1CanvasCheckTest.cs @@ -51,7 +51,7 @@ public virtual void CanvasCheckTest1() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - using (PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, outputIntent)) { + using (PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformance.PDF_A_1B, outputIntent)) { pdfDocument.AddNewPage(); PdfCanvas canvas = new PdfCanvas(pdfDocument.GetLastPage()); for (int i = 0; i < 28; i++) { @@ -71,7 +71,7 @@ public virtual void CanvasCheckTest2() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, outputIntent); + PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformance.PDF_A_1B, outputIntent); pdfDocument.AddNewPage(); PdfCanvas canvas = new PdfCanvas(pdfDocument.GetLastPage()); for (int i = 0; i < 28; i++) { @@ -93,7 +93,7 @@ public virtual void CanvasCheckTest3() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - using (PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, outputIntent)) { + using (PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformance.PDF_A_1B, outputIntent)) { pdfDocument.AddNewPage(); PdfCanvas canvas = new PdfCanvas(pdfDocument.GetLastPage()); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => canvas.SetRenderingIntent diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1EmbeddedFilesCheckTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1EmbeddedFilesCheckTest.cs index 30295e1abf..4aa69c01f2 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1EmbeddedFilesCheckTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1EmbeddedFilesCheckTest.cs @@ -40,7 +40,7 @@ public virtual void FileSpecCheckTest01() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, outputIntent); + PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformance.PDF_A_1B, outputIntent); PdfDictionary fileNames = new PdfDictionary(); pdfDocument.GetCatalog().Put(PdfName.Names, fileNames); PdfDictionary embeddedFiles = new PdfDictionary(); @@ -63,7 +63,7 @@ public virtual void FileSpecCheckTest02() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, outputIntent); + PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformance.PDF_A_1B, outputIntent); PdfStream stream = new PdfStream(); pdfDocument.GetCatalog().Put(new PdfName("testStream"), stream); PdfFileSpec spec = PdfFileSpec.CreateEmbeddedFileSpec(pdfDocument, sourceFolder + "sample.wav", "sample.wav" @@ -81,7 +81,7 @@ public virtual void FileSpecCheckTest03() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, outputIntent); + PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformance.PDF_A_1B, outputIntent); PdfStream stream = new PdfStream(); pdfDocument.GetCatalog().Put(new PdfName("testStream"), stream); PdfFileSpec spec = PdfFileSpec.CreateEmbeddedFileSpec(pdfDocument, sourceFolder + "sample.wav", "sample.wav" diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1GraphicsTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1GraphicsTest.cs index d699d8b3f4..5d4899393a 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1GraphicsTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1GraphicsTest.cs @@ -55,7 +55,7 @@ public virtual void ColorCheckTest1() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, outputIntent); doc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(doc.GetLastPage()); canvas.SetFillColor(new DeviceCmyk(0.1f, 0.1f, 0.1f, 0.1f)); @@ -82,7 +82,7 @@ public virtual void ColorCheckTest2() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, outputIntent); doc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(doc.GetLastPage()); canvas.SetFillColor(new DeviceCmyk(0.1f, 0.1f, 0.1f, 0.1f)); @@ -98,7 +98,7 @@ public virtual void ColorCheckTest2() { [NUnit.Framework.Test] public virtual void ColorCheckTest3() { PdfWriter writer = new PdfWriter(new MemoryStream()); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, null); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, null); doc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(doc.GetLastPage()); canvas.SetFillColor(ColorConstants.GREEN); @@ -119,7 +119,7 @@ public virtual void ColorCheckTest4() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, outputIntent); doc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(doc.GetLastPage()); canvas.SetFillColor(ColorConstants.GREEN); @@ -137,7 +137,7 @@ public virtual void EgsCheckTest1() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - using (PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, outputIntent)) { + using (PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, outputIntent)) { doc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(doc.GetLastPage()); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => canvas.SetExtGState(new @@ -155,7 +155,7 @@ public virtual void EgsCheckTest2() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, outputIntent); doc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(doc.GetLastPage()); canvas.SetExtGState(new PdfExtGState().SetTransferFunction2(PdfName.Default)); @@ -170,7 +170,7 @@ public virtual void EgsCheckTest3() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - using (PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, outputIntent)) { + using (PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, outputIntent)) { doc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(doc.GetLastPage()); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => canvas.SetExtGState(new @@ -186,7 +186,7 @@ public virtual void EgsCheckTest4() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - using (PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, outputIntent)) { + using (PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, outputIntent)) { doc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(doc.GetLastPage()); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => canvas.SetExtGState(new @@ -202,7 +202,7 @@ public virtual void TransparencyCheckTest1() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, outputIntent); doc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(doc.GetLastPage()); PdfFormXObject xObject = new PdfFormXObject(new Rectangle(100, 100)); @@ -222,7 +222,7 @@ public virtual void TransparencyCheckTest2() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - using (PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, outputIntent)) { + using (PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, outputIntent)) { doc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(doc.GetLastPage()); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => canvas.SetExtGState(new @@ -240,7 +240,7 @@ public virtual void TransparencyCheckTest3() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, outputIntent); doc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(doc.GetLastPage()); canvas.SetExtGState(new PdfExtGState().SetSoftMask(PdfName.None)); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1LayoutListTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1LayoutListTest.cs index 06dc341c54..241cc495d2 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1LayoutListTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1LayoutListTest.cs @@ -54,8 +54,7 @@ public virtual void ListTest01() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument pdfDocument = new PdfADocument(new PdfWriter(outPdf), PdfAConformanceLevel.PDF_A_1B, outputIntent - ); + PdfADocument pdfDocument = new PdfADocument(new PdfWriter(outPdf), PdfAConformance.PDF_A_1B, outputIntent); Document doc = new Document(pdfDocument); pdfDocument.SetTagged(); PdfFont textfont = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", PdfEncodings.WINANSI, PdfFontFactory.EmbeddingStrategy diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1bCheckfieldAppearanceTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1bCheckfieldAppearanceTest.cs index fa5f4a5bad..a23786c046 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1bCheckfieldAppearanceTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA1bCheckfieldAppearanceTest.cs @@ -57,13 +57,13 @@ public virtual void PdfA1bCheckFieldOffAppearanceTest() { String diff = "diff_" + name + "_"; PdfWriter writer = new PdfWriter(outPath); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfAcroForm form = PdfFormCreator.GetAcroForm(doc, true); PdfFormField chk = new CheckBoxFormFieldBuilder(doc, "name").SetWidgetRectangle(new Rectangle(100, 500, 50 - , 50)).SetCheckType(CheckBoxType.CHECK).SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_1B).CreateCheckBox - ().SetValue("Off"); + , 50)).SetCheckType(CheckBoxType.CHECK).SetConformance(PdfConformance.PDF_A_1B).CreateCheckBox().SetValue + ("Off"); chk.GetFirstFormAnnotation().SetBorderColor(ColorConstants.BLACK); chk.GetFirstFormAnnotation().SetBorderWidth(1); form.AddField(chk); @@ -80,13 +80,13 @@ public virtual void PdfA1bCheckFieldOnAppearanceTest() { String diff = "diff_" + name + "_"; PdfWriter writer = new PdfWriter(outPath); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfAcroForm form = PdfFormCreator.GetAcroForm(doc, true); PdfFormField chk = new CheckBoxFormFieldBuilder(doc, "name").SetWidgetRectangle(new Rectangle(100, 500, 50 - , 50)).SetCheckType(CheckBoxType.CHECK).SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_1B).CreateCheckBox - ().SetValue("On"); + , 50)).SetCheckType(CheckBoxType.CHECK).SetConformance(PdfConformance.PDF_A_1B).CreateCheckBox().SetValue + ("On"); chk.GetFirstFormAnnotation().SetBorderColor(ColorConstants.BLACK); chk.GetFirstFormAnnotation().SetBorderWidth(1); form.AddField(chk); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2AcroFormCheckTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2AcroFormCheckTest.cs index a96e008205..c7d65c4289 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2AcroFormCheckTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2AcroFormCheckTest.cs @@ -49,8 +49,8 @@ public static void BeforeClass() { public virtual void AcroFormCheck01() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary acroForm = new PdfDictionary(); acroForm.Put(PdfName.NeedAppearances, new PdfBoolean(true)); @@ -69,8 +69,8 @@ public virtual void AcroFormCheck02() { String cmpPdf = cmpFolder + "cmp_pdfA2b_acroFormCheck02.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary acroForm = new PdfDictionary(); acroForm.Put(PdfName.NeedAppearances, new PdfBoolean(false)); @@ -85,8 +85,8 @@ public virtual void AcroFormCheck03() { String cmpPdf = cmpFolder + "cmp_pdfA2b_acroFormCheck03.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary acroForm = new PdfDictionary(); doc.GetCatalog().Put(PdfName.AcroForm, acroForm); @@ -98,8 +98,8 @@ public virtual void AcroFormCheck03() { public virtual void AcroFormCheck04() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary acroForm = new PdfDictionary(); acroForm.Put(PdfName.XFA, new PdfArray()); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2ActionCheckTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2ActionCheckTest.cs index ac9bf936b1..f311f5cb69 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2ActionCheckTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2ActionCheckTest.cs @@ -48,8 +48,8 @@ public static void BeforeClass() { public virtual void ActionCheck01() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary openActions = new PdfDictionary(); openActions.Put(PdfName.S, PdfName.Launch); @@ -63,8 +63,8 @@ public virtual void ActionCheck01() { public virtual void ActionCheck02() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary openActions = new PdfDictionary(); openActions.Put(PdfName.S, PdfName.Hide); @@ -78,8 +78,8 @@ public virtual void ActionCheck02() { public virtual void ActionCheck03() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary openActions = new PdfDictionary(); openActions.Put(PdfName.S, PdfName.Sound); @@ -93,8 +93,8 @@ public virtual void ActionCheck03() { public virtual void ActionCheck04() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary openActions = new PdfDictionary(); openActions.Put(PdfName.S, PdfName.Movie); @@ -108,8 +108,8 @@ public virtual void ActionCheck04() { public virtual void ActionCheck05() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary openActions = new PdfDictionary(); openActions.Put(PdfName.S, PdfName.ResetForm); @@ -123,8 +123,8 @@ public virtual void ActionCheck05() { public virtual void ActionCheck06() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary openActions = new PdfDictionary(); openActions.Put(PdfName.S, PdfName.ImportData); @@ -138,8 +138,8 @@ public virtual void ActionCheck06() { public virtual void ActionCheck07() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary openActions = new PdfDictionary(); openActions.Put(PdfName.S, PdfName.JavaScript); @@ -153,8 +153,8 @@ public virtual void ActionCheck07() { public virtual void ActionCheck08() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary openActions = new PdfDictionary(); openActions.Put(PdfName.S, PdfName.Named); @@ -169,8 +169,8 @@ public virtual void ActionCheck08() { public virtual void ActionCheck09() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary openActions = new PdfDictionary(); openActions.Put(PdfName.S, PdfName.SetOCGState); @@ -184,8 +184,8 @@ public virtual void ActionCheck09() { public virtual void ActionCheck10() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary openActions = new PdfDictionary(); openActions.Put(PdfName.S, PdfName.Rendition); @@ -199,8 +199,8 @@ public virtual void ActionCheck10() { public virtual void ActionCheck11() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary openActions = new PdfDictionary(); openActions.Put(PdfName.S, PdfName.Trans); @@ -214,8 +214,8 @@ public virtual void ActionCheck11() { public virtual void ActionCheck12() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary openActions = new PdfDictionary(); openActions.Put(PdfName.S, PdfName.GoTo3DView); @@ -229,8 +229,8 @@ public virtual void ActionCheck12() { public virtual void ActionCheck13() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); page.SetAdditionalAction(PdfName.C, PdfAction.CreateJavaScript("js")); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => doc.Close()); @@ -242,8 +242,8 @@ public virtual void ActionCheck13() { public virtual void ActionCheck14() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); doc.GetCatalog().SetAdditionalAction(PdfName.C, PdfAction.CreateJavaScript("js")); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => doc.Close()); @@ -257,8 +257,8 @@ public virtual void ActionCheck15() { String cmpPdf = sourceFolder + "cmp/PdfA2ActionCheckTest/cmp_pdfA2b_actionCheck15.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.GetOutlines(true); PdfOutline @out = doc.GetOutlines(false); @out.AddOutline("New").AddAction(PdfAction.CreateGoTo("TestDest")); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2AnnotationCheckTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2AnnotationCheckTest.cs index 606893f93b..8b0304046f 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2AnnotationCheckTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2AnnotationCheckTest.cs @@ -58,8 +58,8 @@ public static void BeforeClass() { public virtual void AnnotationCheckTest01() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); Rectangle rect = new Rectangle(100, 650, 400, 100); PdfAnnotation annot = new PdfFileAttachmentAnnotation(rect); @@ -75,8 +75,8 @@ public virtual void AnnotationCheckTest02() { String cmpPdf = cmpFolder + "cmp_pdfA2b_annotationCheckTest02.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); Rectangle rect = new Rectangle(100, 650, 400, 100); PdfAnnotation annot = new PdfPopupAnnotation(rect); @@ -91,8 +91,8 @@ public virtual void AnnotationCheckTest03() { String cmpPdf = cmpFolder + "cmp_pdfA2b_annotationCheckTest03.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); Rectangle rect = new Rectangle(100, 100, 0, 0); PdfAnnotation annot = new PdfWidgetAnnotation(rect); @@ -107,8 +107,8 @@ public virtual void AnnotationCheckTest03() { public virtual void AnnotationCheckTest04() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); Rectangle rect = new Rectangle(100, 650, 400, 100); PdfAnnotation annot = new PdfWidgetAnnotation(rect); @@ -124,8 +124,8 @@ public virtual void AnnotationCheckTest04() { public virtual void AnnotationCheckTest05() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); Rectangle rect = new Rectangle(100, 650, 400, 100); PdfAnnotation annot = new PdfTextAnnotation(rect); @@ -140,8 +140,8 @@ public virtual void AnnotationCheckTest05() { public virtual void AnnotationCheckTest06() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); Rectangle rect = new Rectangle(100, 650, 400, 100); PdfAnnotation annot = new PdfTextAnnotation(rect); @@ -156,8 +156,8 @@ public virtual void AnnotationCheckTest06() { public virtual void AnnotationCheckTest07() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); Rectangle rect = new Rectangle(100, 650, 400, 100); Rectangle formRect = new Rectangle(400, 100); @@ -176,8 +176,8 @@ public virtual void AnnotationCheckTest07() { public virtual void AnnotationCheckTest08() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); Rectangle rect = new Rectangle(100, 650, 400, 100); Rectangle formRect = new Rectangle(400, 100); @@ -196,8 +196,8 @@ public virtual void AnnotationCheckTest08() { public virtual void AnnotationCheckTest09() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); Rectangle rect = new Rectangle(100, 650, 400, 100); PdfAnnotation annot = new PdfWidgetAnnotation(rect); @@ -216,8 +216,8 @@ public virtual void AnnotationCheckTest10() { String cmpPdf = cmpFolder + "cmp_pdfA2b_annotationCheckTest10.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); Rectangle rect = new Rectangle(100, 650, 400, 100); Rectangle formRect = new Rectangle(400, 100); @@ -236,8 +236,8 @@ public virtual void AnnotationCheckTest11() { String cmpPdf = cmpFolder + "cmp_pdfA2b_annotationCheckTest11.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); Rectangle rect = new Rectangle(100, 650, 400, 100); Rectangle formRect = new Rectangle(400, 100); @@ -258,8 +258,8 @@ public virtual void AnnotationCheckTest12() { String cmpPdf = cmpFolder + "cmp_pdfA1a_annotationCheckTest12.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2A, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2A, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.SetTagged(); doc.GetCatalog().SetLang(new PdfString("en-US")); PdfPage page = doc.AddNewPage(); @@ -278,8 +278,8 @@ public virtual void AnnotationCheckTest12() { public virtual void AnnotationCheckTest13() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2A, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2A, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.SetTagged(); doc.GetCatalog().SetLang(new PdfString("en-US")); PdfPage page = doc.AddNewPage(); @@ -299,8 +299,8 @@ public virtual void AnnotationCheckTest14() { String cmpPdf = cmpFolder + "cmp_pdfA2a_annotationCheckTest14.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2A, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2A, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.SetTagged(); doc.GetCatalog().SetLang(new PdfString("en-US")); PdfPage page = doc.AddNewPage(); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2CanvasCheckTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2CanvasCheckTest.cs index 0302fe6b61..0bba715c5c 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2CanvasCheckTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2CanvasCheckTest.cs @@ -50,7 +50,7 @@ public virtual void CanvasCheckTest1() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - using (PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, outputIntent)) { + using (PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformance.PDF_A_2B, outputIntent)) { pdfDocument.AddNewPage(); PdfCanvas canvas = new PdfCanvas(pdfDocument.GetLastPage()); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { @@ -72,7 +72,7 @@ public virtual void CanvasCheckTest2() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - using (PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, outputIntent)) { + using (PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformance.PDF_A_2B, outputIntent)) { pdfDocument.AddNewPage(); PdfCanvas canvas = new PdfCanvas(pdfDocument.GetLastPage()); for (int i = 0; i < 28; i++) { @@ -94,7 +94,7 @@ public virtual void CanvasCheckTest3() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - using (PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, outputIntent)) { + using (PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformance.PDF_A_2B, outputIntent)) { pdfDocument.AddNewPage(); PdfCanvas canvas = new PdfCanvas(pdfDocument.GetLastPage()); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => canvas.SetRenderingIntent diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2CatalogCheckTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2CatalogCheckTest.cs index 9e617e09f7..647519e862 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2CatalogCheckTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2CatalogCheckTest.cs @@ -53,8 +53,8 @@ public virtual void CatalogCheck03() { String cmpPdf = cmpFolder + "cmp_pdfA2b_catalogCheck03.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary ocProperties = new PdfDictionary(); PdfDictionary d = new PdfDictionary(); @@ -79,8 +79,8 @@ public virtual void CatalogCheck03() { public virtual void CatalogCheck04() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary ocProperties = new PdfDictionary(); PdfDictionary d = new PdfDictionary(); @@ -105,8 +105,8 @@ public virtual void CatalogCheck05() { String cmpPdf = cmpFolder + "cmp_pdfA2b_catalogCheck05.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary ocProperties = new PdfDictionary(); PdfDictionary d = new PdfDictionary(); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2EmbeddedFilesCheckTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2EmbeddedFilesCheckTest.cs index 640b7699c3..8c8225f9ba 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2EmbeddedFilesCheckTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2EmbeddedFilesCheckTest.cs @@ -60,7 +60,7 @@ public virtual void FileSpecNonConformingTest01() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, outputIntent); + PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformance.PDF_A_2B, outputIntent); PdfPage page = pdfDocument.AddNewPage(); PdfFont font = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", "WinAnsi", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); @@ -83,7 +83,7 @@ public virtual void FileSpecCheckTest02() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, outputIntent); + PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformance.PDF_A_2B, outputIntent); PdfPage page = pdfDocument.AddNewPage(); PdfFont font = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", "WinAnsi", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); @@ -110,7 +110,7 @@ public virtual void FileSpecCheckTest03() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, outputIntent); + PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformance.PDF_A_2B, outputIntent); PdfPage page = pdfDocument.AddNewPage(); PdfFont font = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", "WinAnsi", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2GraphicsCheckTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2GraphicsCheckTest.cs index 96ed8b3eb5..d5f8a2912c 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2GraphicsCheckTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2GraphicsCheckTest.cs @@ -58,7 +58,7 @@ public virtual void ColorCheckTest1() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - using (PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, outputIntent)) { + using (PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, outputIntent)) { float[] whitePoint = new float[] { 0.9505f, 1f, 1.089f }; float[] gamma = new float[] { 2.2f, 2.2f, 2.2f }; float[] matrix = new float[] { 0.4124f, 0.2126f, 0.0193f, 0.3576f, 0.7152f, 0.1192f, 0.1805f, 0.0722f, 0.9505f @@ -78,7 +78,7 @@ public virtual void ColorCheckTest2() { String outPdf = destinationFolder + "pdfA2b_colorCheckTest2.pdf"; String cmpPdf = cmpFolder + "cmp_pdfA2b_colorCheckTest2.pdf"; PdfWriter writer = new PdfWriter(outPdf); - using (PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, null)) { + using (PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, null)) { float[] whitePoint = new float[] { 0.9505f, 1f, 1.089f }; float[] gamma = new float[] { 2.2f, 2.2f, 2.2f }; float[] matrix = new float[] { 0.4124f, 0.2126f, 0.0193f, 0.3576f, 0.7152f, 0.1192f, 0.1805f, 0.0722f, 0.9505f @@ -104,7 +104,7 @@ public virtual void ColorCheckTest3() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, outputIntent); PdfCanvas canvas = new PdfCanvas(doc.AddNewPage()); canvas.SetFillColor(new DeviceCmyk(0.1f, 0.1f, 0.1f, 0.1f)); canvas.MoveTo(doc.GetDefaultPageSize().GetLeft(), doc.GetDefaultPageSize().GetBottom()); @@ -124,7 +124,7 @@ public virtual void ColorCheckTest4() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, outputIntent); PdfCanvas canvas = new PdfCanvas(doc.AddNewPage()); canvas.SetFillColor(ColorConstants.BLUE); canvas.SetStrokeColor(new DeviceCmyk(0.1f, 0.1f, 0.1f, 0.1f)); @@ -148,7 +148,7 @@ public virtual void ColorCheckTest5() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, outputIntent); PdfCanvas canvas = new PdfCanvas(doc.AddNewPage()); String shortText = "text"; PdfFont font = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED @@ -173,7 +173,7 @@ public virtual void ColorCheckTest6() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, outputIntent); PdfCanvas canvas = new PdfCanvas(doc.AddNewPage()); String shortText = "text"; PdfFont font = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED @@ -196,7 +196,7 @@ public virtual void ColorCheckTest7() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, outputIntent); PdfCanvas canvas = new PdfCanvas(doc.AddNewPage()); String shortText = "text"; PdfFont font = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED @@ -216,7 +216,7 @@ public virtual void ColorCheckTest7() { [NUnit.Framework.Test] public virtual void DefaultTextColorCheckTest() { String outPdf = destinationFolder + "defaultColorCheck.pdf"; - PdfDocument pdfDocument = new PdfADocument(new PdfWriter(outPdf), PdfAConformanceLevel.PDF_A_2B, null); + PdfDocument pdfDocument = new PdfADocument(new PdfWriter(outPdf), PdfAConformance.PDF_A_2B, null); PdfFont font = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", "Identity-H", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); PdfPage page = pdfDocument.AddNewPage(); @@ -233,7 +233,7 @@ public virtual void DefaultTextColorCheckTest() { public virtual void DefaultTextColorCheckForInvisibleTextTest() { String outPdf = destinationFolder + "defaultColorCheckInvisibleText.pdf"; String cmpPdf = cmpFolder + "cmp_pdfA2b_defaultColorCheckInvisibleText.pdf"; - PdfDocument pdfDocument = new PdfADocument(new PdfWriter(outPdf), PdfAConformanceLevel.PDF_A_2B, null); + PdfDocument pdfDocument = new PdfADocument(new PdfWriter(outPdf), PdfAConformance.PDF_A_2B, null); PdfFont font = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", "Identity-H", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); PdfPage page = pdfDocument.AddNewPage(); @@ -248,7 +248,7 @@ public virtual void DefaultTextColorCheckForInvisibleTextTest() { [NUnit.Framework.Test] public virtual void DefaultStrokeColorCheckTest() { String outPdf = destinationFolder + "defaultColorCheck.pdf"; - PdfDocument pdfDocument = new PdfADocument(new PdfWriter(outPdf), PdfAConformanceLevel.PDF_A_2B, null); + PdfDocument pdfDocument = new PdfADocument(new PdfWriter(outPdf), PdfAConformance.PDF_A_2B, null); PdfPage page = pdfDocument.AddNewPage(); PdfCanvas canvas = new PdfCanvas(page); canvas.SaveState(); @@ -275,7 +275,7 @@ public virtual void EgsCheckTest1() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, outputIntent); doc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(doc.GetLastPage()); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => canvas.SetExtGState(new @@ -292,7 +292,7 @@ public virtual void EgsCheckTest2() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - using (PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, outputIntent)) { + using (PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, outputIntent)) { doc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(doc.GetLastPage()); PdfDictionary dict = new PdfDictionary(); @@ -311,7 +311,7 @@ public virtual void ImageCheckTest1() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, outputIntent); doc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(doc.GetLastPage()); canvas.AddImageAt(ImageDataFactory.Create(sourceFolder + "jpeg2000/p0_01.j2k"), 300, 300, false); @@ -326,7 +326,7 @@ public virtual void ImageCheckTest2() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, outputIntent); doc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(doc.GetLastPage()); canvas.AddImageAt(ImageDataFactory.Create(sourceFolder + "jpeg2000/file5.jp2"), 300, 300, false); @@ -341,7 +341,7 @@ public virtual void ImageCheckTest3() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, outputIntent); doc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(doc.GetLastPage()); canvas.AddImageAt(ImageDataFactory.Create(sourceFolder + "jpeg2000/file7.jp2"), 300, 300, false); @@ -369,7 +369,7 @@ public virtual void ImageCheckTest4() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, outputIntent); PdfCanvas canvas; for (int i = 1; i < 5; ++i) { canvas = new PdfCanvas(doc.AddNewPage()); @@ -390,7 +390,7 @@ public virtual void ImageCheckTest4() { [NUnit.Framework.Test] public virtual void TransparencyCheckTest1() { PdfWriter writer = new PdfWriter(new MemoryStream()); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, null); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, null); PdfCanvas canvas = new PdfCanvas(doc.AddNewPage()); canvas.SaveState(); canvas.SetExtGState(new PdfExtGState().SetBlendMode(PdfName.Darken)); @@ -415,7 +415,7 @@ public virtual void TransparencyCheckTest2() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, outputIntent); PdfCanvas canvas = new PdfCanvas(doc.AddNewPage()); canvas.SaveState(); canvas.SetExtGState(new PdfExtGState().SetBlendMode(PdfName.Darken)); @@ -437,7 +437,7 @@ public virtual void TransparencyCheckTest3() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - using (PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, outputIntent)) { + using (PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, outputIntent)) { PdfCanvas canvas = new PdfCanvas(doc.AddNewPage()); canvas.SaveState(); canvas.SetExtGState(new PdfExtGState().SetBlendMode(PdfName.Darken)); @@ -456,8 +456,8 @@ public virtual void TransparencyCheckTest3() { public virtual void ColourSpaceTest01() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); PdfColorSpace alternateSpace = new PdfDeviceCs.Rgb(); //Tint transformation function is a stream @@ -478,8 +478,8 @@ public virtual void ColourSpaceTest01() { public virtual void ColourSpaceTest02() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); PdfColorSpace alternateSpace = new PdfDeviceCs.Rgb(); //Tint transformation function is a dictionary @@ -500,8 +500,8 @@ public virtual void ColourSpaceTest02() { public virtual void ColourSpaceTest03() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); PdfColorSpace alternateSpace = new PdfDeviceCs.Rgb(); //Tint transformation function is a dictionary @@ -529,8 +529,8 @@ public virtual void ColourSpaceTest03() { public virtual void ColourSpaceWithoutColourantsTest() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); PdfColorSpace alternateSpace = new PdfDeviceCs.Rgb(); //Tint transformation function is a dictionary @@ -560,8 +560,8 @@ public virtual void ColourSpaceWithoutColourantsTest() { public virtual void ColourSpaceWithoutAttributesTest() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); PdfColorSpace alternateSpace = new PdfDeviceCs.Rgb(); //Tint transformation function is a dictionary diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2LayoutOcgTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2LayoutOcgTest.cs index 39cd27cbae..f7ccae7b05 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2LayoutOcgTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2LayoutOcgTest.cs @@ -54,7 +54,7 @@ public virtual void CheckIfOcgForPdfA2Works() { Stream colorStream = FileUtil.GetInputStreamForFile(sourceFolder + "color/sRGB_CS_profile.icm"); String outFileName = destinationFolder + fileName; String cmpFileName = sourceFolder + "cmp/PdfA2LayoutOcgTest/cmp_" + fileName; - PdfDocument pdfDoc = new PdfADocument(new PdfWriter(outFileName), PdfAConformanceLevel.PDF_A_2A, new PdfOutputIntent + PdfDocument pdfDoc = new PdfADocument(new PdfWriter(outFileName), PdfAConformance.PDF_A_2A, new PdfOutputIntent ("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", colorStream)); pdfDoc.SetTagged(); pdfDoc.GetCatalog().SetLang(new PdfString("en-US")); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2OCPropertiesTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2OCPropertiesTest.cs index 8699b9e6fa..75afad3ed6 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2OCPropertiesTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2OCPropertiesTest.cs @@ -49,8 +49,8 @@ public virtual void CheckNameEntryShouldBeUniqueBetweenDefaultAndAdditionalConfi String outPdf = DESTINATION_FOLDER + "pdfA2b_ocPropertiesCheck01.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary ocProperties = new PdfDictionary(); PdfDictionary d = new PdfDictionary(); @@ -72,8 +72,8 @@ public virtual void CheckAsKeyInContentConfigDictTest() { String outPdf = DESTINATION_FOLDER + "pdfA2b_ocPropertiesCheck02.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary ocProperties = new PdfDictionary(); PdfArray configs = new PdfArray(); @@ -93,8 +93,8 @@ public virtual void CheckNameEntryShouldBeUniqueBetweenAdditionalConfigsTest() { String outPdf = DESTINATION_FOLDER + "pdfA2b_ocPropertiesCheck03.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary ocProperties = new PdfDictionary(); PdfDictionary d = new PdfDictionary(); @@ -119,8 +119,8 @@ public virtual void CheckOCCDContainNameTest() { String outPdf = DESTINATION_FOLDER + "pdfA2b_ocPropertiesCheck04.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary ocProperties = new PdfDictionary(); PdfDictionary d = new PdfDictionary(); @@ -144,8 +144,8 @@ public virtual void CheckOrderArrayContainsReferencesToAllOCGsTest() { String outPdf = DESTINATION_FOLDER + "pdfA2b_ocPropertiesCheck05.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary ocProperties = new PdfDictionary(); PdfDictionary d = new PdfDictionary(); @@ -179,8 +179,8 @@ public virtual void CheckDocWithOCGsWithoutOptionalOrderEntryTest() { String cmpPdf = SOURCE_FOLDER + "cmp_pdfA2b_ocPropertiesCheck06.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary ocProperties = new PdfDictionary(); PdfDictionary d = new PdfDictionary(); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2PageCheckTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2PageCheckTest.cs index fddc1fa141..9a19549465 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2PageCheckTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA2PageCheckTest.cs @@ -38,8 +38,8 @@ public class PdfA2PageCheckTest : ExtendedITextTest { public virtual void CatalogCheck01() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream()); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); page.GetPdfObject().Put(PdfName.PresSteps, new PdfDictionary()); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => doc.Close()); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA3CatalogCheckTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA3CatalogCheckTest.cs index a197eca791..101ebc0e40 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA3CatalogCheckTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA3CatalogCheckTest.cs @@ -51,8 +51,8 @@ public virtual void CatalogCheck01() { String cmpPdf = cmpFolder + "cmp_pdfA3b_catalogCheck01.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_3B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_3B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary ocProperties = new PdfDictionary(); PdfDictionary d = new PdfDictionary(); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA3EmbeddedFilesCheckTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA3EmbeddedFilesCheckTest.cs index 60f2aa0e4a..42b7230f05 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA3EmbeddedFilesCheckTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA3EmbeddedFilesCheckTest.cs @@ -54,7 +54,7 @@ public virtual void FileSpecCheckTest01() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_3B, outputIntent); + PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformance.PDF_A_3B, outputIntent); PdfPage page = pdfDocument.AddNewPage(); PdfFont font = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", "WinAnsi", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); @@ -79,7 +79,7 @@ public virtual void FileSpecCheckTest02() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_3B, outputIntent); + PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformance.PDF_A_3B, outputIntent); PdfPage page = pdfDocument.AddNewPage(); PdfFont font = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", "WinAnsi", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); @@ -104,7 +104,7 @@ public virtual void FileSpecCheckTest03() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_3B, outputIntent); + PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformance.PDF_A_3B, outputIntent); PdfPage page = pdfDocument.AddNewPage(); PdfFont font = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", "WinAnsi", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); @@ -126,7 +126,7 @@ public virtual void FileSpecCheckTest04() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_3B, outputIntent); + PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformance.PDF_A_3B, outputIntent); PdfPage page = pdfDocument.AddNewPage(); PdfFont font = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", "WinAnsi", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA4ActionCheckTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA4ActionCheckTest.cs index 6a43f04794..fbd1ef4ca6 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA4ActionCheckTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA4ActionCheckTest.cs @@ -55,7 +55,7 @@ public static void BeforeClass() { [NUnit.Framework.Test] public virtual void PdfA4ForbiddenActions_LAUNCH_ActionToPage_Test() { - Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => GeneratePdfADocument(PdfAConformanceLevel + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => GeneratePdfADocument(PdfAConformance .PDF_A_4, null, (doc) => { doc.GetFirstPage().SetAdditionalAction(PdfName.O, PdfAction.CreateLaunch(new PdfStringFS("launch.sh"))); } @@ -67,7 +67,7 @@ public virtual void PdfA4ForbiddenActions_LAUNCH_ActionToPage_Test() { [NUnit.Framework.Test] public virtual void PdfA4ForbiddenActions_SOUND_ActionToPage_Test() { Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { - GeneratePdfADocument(PdfAConformanceLevel.PDF_A_4, null, (doc) => { + GeneratePdfADocument(PdfAConformance.PDF_A_4, null, (doc) => { Stream @is = null; try { @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sample.aif"); @@ -92,7 +92,7 @@ public virtual void PdfA4ForbiddenActions_SOUND_ActionToPage_Test() { [NUnit.Framework.Test] public virtual void PdfA4ForbiddenActions_MOVIE_ActionToPage_Test() { Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { - GeneratePdfADocument(PdfAConformanceLevel.PDF_A_4, null, (doc) => { + GeneratePdfADocument(PdfAConformance.PDF_A_4, null, (doc) => { doc.AddNewPage().SetAdditionalAction(PdfName.O, PdfAction.CreateMovie(null, "Some movie", PdfName.Play)); } ); @@ -105,7 +105,7 @@ public virtual void PdfA4ForbiddenActions_MOVIE_ActionToPage_Test() { [NUnit.Framework.Test] public virtual void PdfA4ForbiddenActions_RESETFORM_ActionToPage_Test() { Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { - GeneratePdfADocument(PdfAConformanceLevel.PDF_A_4, null, (doc) => { + GeneratePdfADocument(PdfAConformance.PDF_A_4, null, (doc) => { CheckBox checkBox = new CheckBox("test"); checkBox.SetChecked(true); Document document = new Document(doc); @@ -121,7 +121,7 @@ public virtual void PdfA4ForbiddenActions_RESETFORM_ActionToPage_Test() { [NUnit.Framework.Test] public virtual void PdfA4ForbiddenActions_IMPORTDATA_ActionToPage_Test() { - Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => GeneratePdfADocument(PdfAConformanceLevel + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => GeneratePdfADocument(PdfAConformance .PDF_A_4, null, (doc) => { doc.AddNewPage(); PdfDictionary openActions = new PdfDictionary(); @@ -136,7 +136,7 @@ public virtual void PdfA4ForbiddenActions_IMPORTDATA_ActionToPage_Test() { [NUnit.Framework.Test] public virtual void PdfA4ForbiddenActions_HIDE_ActionToPage_Test() { Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { - GeneratePdfADocument(PdfAConformanceLevel.PDF_A_4, null, (doc) => { + GeneratePdfADocument(PdfAConformance.PDF_A_4, null, (doc) => { PdfAnnotation[] annotations = new PdfAnnotation[] { new PdfLineAnnotation(new Rectangle(10, 10, 200, 200), new float[] { 50, 750, 50, 750 }), new PdfLineAnnotation(new Rectangle(200, 200, 200, 200), new float[ ] { 50, 750, 50, 750 }) }; @@ -152,7 +152,7 @@ public virtual void PdfA4ForbiddenActions_HIDE_ActionToPage_Test() { [NUnit.Framework.Test] public virtual void PdfA4ForbiddenActions_RENDITION_ActionToPage_Test() { Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { - GeneratePdfADocument(PdfAConformanceLevel.PDF_A_4, null, (doc) => { + GeneratePdfADocument(PdfAConformance.PDF_A_4, null, (doc) => { doc.AddNewPage().SetAdditionalAction(PdfName.O, PdfAction.CreateRendition("empty", PdfFileSpec.CreateEmbeddedFileSpec (doc, null, "bing", "bing", new PdfDictionary(), PdfName.AllOn), "something", new PdfCircleAnnotation( new Rectangle(10, 10, 200, 200)))); @@ -166,7 +166,7 @@ public virtual void PdfA4ForbiddenActions_RENDITION_ActionToPage_Test() { [NUnit.Framework.Test] public virtual void PdfA4ForbiddenActions_TRANS_ActionToPage_Test() { - Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => GeneratePdfADocument(PdfAConformanceLevel + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => GeneratePdfADocument(PdfAConformance .PDF_A_4, null, (doc) => { PdfDictionary openActions = new PdfDictionary(); openActions.Put(PdfName.S, PdfName.Trans); @@ -179,7 +179,7 @@ public virtual void PdfA4ForbiddenActions_TRANS_ActionToPage_Test() { [NUnit.Framework.Test] public virtual void PdfA4ForbiddenActions_SETSTATE_ActionToPage_Test() { - Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => GeneratePdfADocument(PdfAConformanceLevel + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => GeneratePdfADocument(PdfAConformance .PDF_A_4, null, (doc) => { PdfDictionary action = new PdfDictionary(); action.Put(PdfName.S, PdfName.SetState); @@ -192,7 +192,7 @@ public virtual void PdfA4ForbiddenActions_SETSTATE_ActionToPage_Test() { [NUnit.Framework.Test] public virtual void PdfA4ForbiddenActions_NOOP_ActionToPage_Test() { - Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => GeneratePdfADocument(PdfAConformanceLevel + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => GeneratePdfADocument(PdfAConformance .PDF_A_4, null, (doc) => { PdfDictionary action = new PdfDictionary(); action.Put(PdfName.S, PdfName.NoOp); @@ -205,7 +205,7 @@ public virtual void PdfA4ForbiddenActions_NOOP_ActionToPage_Test() { [NUnit.Framework.Test] public virtual void PdfA4ForbiddenActions_SETOCGSTATE_ActionToPage_Test() { - Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => GeneratePdfADocument(PdfAConformanceLevel + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => GeneratePdfADocument(PdfAConformance .PDF_A_4, null, (doc) => { doc.AddNewPage().SetAdditionalAction(PdfName.O, PdfAction.CreateSetOcgState(new List()) ); @@ -217,7 +217,7 @@ public virtual void PdfA4ForbiddenActions_SETOCGSTATE_ActionToPage_Test() { [NUnit.Framework.Test] public virtual void PdfA4ForbiddenActions_GOTO3DVIEW_ActionToPage_Test() { - Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => GeneratePdfADocument(PdfAConformanceLevel + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => GeneratePdfADocument(PdfAConformance .PDF_A_4, null, (doc) => { PdfDictionary action = new PdfDictionary(); action.Put(PdfName.S, PdfName.GoTo3DView); @@ -231,7 +231,7 @@ public virtual void PdfA4ForbiddenActions_GOTO3DVIEW_ActionToPage_Test() { [NUnit.Framework.Test] public virtual void PdfA4_SETOCGSTATE_InCatalog_Test() { Exception pdfa4Exception = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { - GeneratePdfADocument(PdfAConformanceLevel.PDF_A_4, null, (doc) => { + GeneratePdfADocument(PdfAConformance.PDF_A_4, null, (doc) => { doc.GetCatalog().SetAdditionalAction(PdfName.O, PdfAction.CreateSetOcgState(new List()) ); } @@ -246,13 +246,13 @@ public virtual void PdfA4_SETOCGSTATE_InCatalog_Test() { [NUnit.Framework.Test] public virtual void PdfA4_SETOCGSTATE_Annotation_Test() { Exception pdfa4Exception = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { - GeneratePdfADocument(PdfAConformanceLevel.PDF_A_4, null, (doc) => { + GeneratePdfADocument(PdfAConformance.PDF_A_4, null, (doc) => { doc.AddNewPage().AddAnnotation(ConstructAnnotationWithAction(PdfName.SetOCGState)); } ); } ); - String messageFormat = MessageFormatUtil.Format(PdfAConformanceException._0_ACTIONS_ARE_NOT_ALLOWED, PdfName + String messageFormat = MessageFormatUtil.Format(PdfaExceptionMessageConstant._0_ACTIONS_ARE_NOT_ALLOWED, PdfName .SetOCGState.GetValue()); NUnit.Framework.Assert.AreEqual(messageFormat, pdfa4Exception.Message); } @@ -261,7 +261,7 @@ public virtual void PdfA4_SETOCGSTATE_Annotation_Test() { public virtual void PdfA4E_SETOCGSTATE_Annotation_Test() { String outPdf = DESTINATION_FOLDER + "pdfA4ESetOCGStateAnnotation.pdf"; String cmpPdf = CMP_FOLDER + "cmp_pdfA4ESetOCGStateAnnotation.pdf"; - GeneratePdfADocument(PdfAConformanceLevel.PDF_A_4E, outPdf, (doc) => { + GeneratePdfADocument(PdfAConformance.PDF_A_4E, outPdf, (doc) => { doc.AddNewPage().AddAnnotation(ConstructAnnotationWithAction(PdfName.SetOCGState)); } ); @@ -271,13 +271,13 @@ public virtual void PdfA4E_SETOCGSTATE_Annotation_Test() { [NUnit.Framework.Test] public virtual void PdfA4_SETGOTO3DVIEW_Annotation_Test() { Exception pdfa4Exception = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { - GeneratePdfADocument(PdfAConformanceLevel.PDF_A_4, null, (doc) => { + GeneratePdfADocument(PdfAConformance.PDF_A_4, null, (doc) => { doc.AddNewPage().AddAnnotation(ConstructAnnotationWithAction(PdfName.GoTo3DView)); } ); } ); - String messageFormat = MessageFormatUtil.Format(PdfAConformanceException._0_ACTIONS_ARE_NOT_ALLOWED, PdfName + String messageFormat = MessageFormatUtil.Format(PdfaExceptionMessageConstant._0_ACTIONS_ARE_NOT_ALLOWED, PdfName .GoTo3DView.GetValue()); NUnit.Framework.Assert.AreEqual(messageFormat, pdfa4Exception.Message); } @@ -286,7 +286,7 @@ public virtual void PdfA4_SETGOTO3DVIEW_Annotation_Test() { public virtual void PdfA4E_GOTO3DVIEW_Annotation_Test() { String outPdf = DESTINATION_FOLDER + "pdfA4ESetGoto3DViewAnnotation.pdf"; String cmpPdf = CMP_FOLDER + "cmp_pdfA4EGoto3DViewAnnotation.pdf"; - GeneratePdfADocument(PdfAConformanceLevel.PDF_A_4E, outPdf, (doc) => { + GeneratePdfADocument(PdfAConformance.PDF_A_4E, outPdf, (doc) => { doc.AddNewPage().AddAnnotation(ConstructAnnotationWithAction(PdfName.GoTo3DView)); } ); @@ -299,7 +299,7 @@ public virtual void PdfA4_AllowedNamedActions_Test() { String cmpPdf = CMP_FOLDER + "cmp_pdfA4AllowedNamedActions.pdf"; IList annots = JavaUtil.ArraysAsList(PdfName.NextPage, PdfName.PrevPage, PdfName.FirstPage, PdfName .LastPage); - GeneratePdfADocument(PdfAConformanceLevel.PDF_A_4, outPdf, (doc) => { + GeneratePdfADocument(PdfAConformance.PDF_A_4, outPdf, (doc) => { PdfPage page = doc.GetFirstPage(); foreach (PdfName annot in annots) { PdfAnnotation annotation = ConstructAnnotationWithAction(new PdfName("")); @@ -317,7 +317,7 @@ public virtual void PdfA4_SpecialAllowedAction_Test() { String cmpPdf = CMP_FOLDER + "cmp_pdfA4SpecialAllowedAction.pdf"; IList annots = JavaUtil.ArraysAsList(PdfName.GoToR, PdfName.GoToE, PdfName.URI, PdfName.SubmitForm ); - GeneratePdfADocument(PdfAConformanceLevel.PDF_A_4, outPdf, (doc) => { + GeneratePdfADocument(PdfAConformance.PDF_A_4, outPdf, (doc) => { PdfPage page = doc.GetFirstPage(); foreach (PdfName annot in annots) { PdfAnnotation annotation = ConstructAnnotationWithAction(annot); @@ -331,7 +331,7 @@ public virtual void PdfA4_SpecialAllowedAction_Test() { [NUnit.Framework.Test] public virtual void PdfA4F_SETOCGSTATE_InCatalog_Test() { Exception pdfa4Exception = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { - GeneratePdfADocument(PdfAConformanceLevel.PDF_A_4F, null, (doc) => { + GeneratePdfADocument(PdfAConformance.PDF_A_4F, null, (doc) => { doc.GetCatalog().SetAdditionalAction(PdfName.O, PdfAction.CreateSetOcgState(new List()) ); } @@ -346,7 +346,7 @@ public virtual void PdfA4F_SETOCGSTATE_InCatalog_Test() { [NUnit.Framework.Test] public virtual void PdfA4E_SETOCGSTATE_InCatalog_Test() { Exception pdfa4Exception = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { - GeneratePdfADocument(PdfAConformanceLevel.PDF_A_4E, null, (doc) => { + GeneratePdfADocument(PdfAConformance.PDF_A_4E, null, (doc) => { doc.GetCatalog().SetAdditionalAction(PdfName.O, PdfAction.CreateSetOcgState(new List()) ); } @@ -361,7 +361,7 @@ public virtual void PdfA4E_SETOCGSTATE_InCatalog_Test() { [NUnit.Framework.Test] public virtual void PdfA4_GOTO3DVIEW_InCatalog_Test() { Exception pdfa4Exception = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { - GeneratePdfADocument(PdfAConformanceLevel.PDF_A_4, null, (doc) => { + GeneratePdfADocument(PdfAConformance.PDF_A_4, null, (doc) => { PdfDictionary action = new PdfDictionary(); action.Put(PdfName.S, PdfName.GoTo3DView); doc.GetCatalog().SetAdditionalAction(PdfName.O, new PdfAction(action)); @@ -377,7 +377,7 @@ public virtual void PdfA4_GOTO3DVIEW_InCatalog_Test() { [NUnit.Framework.Test] public virtual void PdfA4F_GOTO3DView_InCatalog_Test() { Exception pdfa4Exception = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { - GeneratePdfADocument(PdfAConformanceLevel.PDF_A_4F, null, (doc) => { + GeneratePdfADocument(PdfAConformance.PDF_A_4F, null, (doc) => { PdfDictionary action = new PdfDictionary(); action.Put(PdfName.S, PdfName.GoTo3DView); doc.GetCatalog().SetAdditionalAction(PdfName.O, new PdfAction(action)); @@ -391,7 +391,7 @@ public virtual void PdfA4F_GOTO3DView_InCatalog_Test() { [NUnit.Framework.Test] public virtual void PdfA4E_GOTO3DView_InCatalog_Test() { - Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => GeneratePdfADocument(PdfAConformanceLevel + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => GeneratePdfADocument(PdfAConformance .PDF_A_4E, null, (doc) => { PdfDictionary action = new PdfDictionary(); action.Put(PdfName.S, PdfName.GoTo3DView); @@ -406,7 +406,7 @@ public virtual void PdfA4E_GOTO3DView_InCatalog_Test() { public virtual void PdfA4AAEntriesAllowedInAADocumentCatalog_Test() { String outPdf = DESTINATION_FOLDER + "pdfA4AAEntriesAllowedInAADocumentCatalog.pdf"; String cmpPdf = CMP_FOLDER + "cmp_pdfA4AAEntriesAllowedInAADocumentCatalog.pdf"; - GeneratePdfADocument(PdfAConformanceLevel.PDF_A_4, outPdf, (doc) => { + GeneratePdfADocument(PdfAConformance.PDF_A_4, outPdf, (doc) => { PdfDictionary allowedAA = new PdfDictionary(); allowedAA.Put(PdfName.E, new PdfName("HELLO")); allowedAA.Put(PdfName.X, new PdfName("HELLO")); @@ -424,7 +424,7 @@ public virtual void PdfA4AAEntriesAllowedInAADocumentCatalog_Test() { public virtual void PdfA4AAEntriesAllowedInAAPage_Test() { String outPdf = DESTINATION_FOLDER + "pdfA4AAEntriesAllowedInAAPage.pdf"; String cmpPdf = CMP_FOLDER + "cmp_pdfA4AAEntriesAllowedInAAPage.pdf"; - GeneratePdfADocument(PdfAConformanceLevel.PDF_A_4, outPdf, (doc) => { + GeneratePdfADocument(PdfAConformance.PDF_A_4, outPdf, (doc) => { PdfDictionary allowedAA = new PdfDictionary(); allowedAA.Put(PdfName.E, new PdfName("HELLO")); allowedAA.Put(PdfName.X, new PdfName("HELLO")); @@ -460,14 +460,14 @@ private void CompareResult(String outPdf, String cmpPdf) { } } - private void GeneratePdfADocument(PdfAConformanceLevel conformanceLevel, String outPdf, System.Action consumer) { + private void GeneratePdfADocument(PdfAConformance conformance, String outPdf, System.Action consumer + ) { String filename = DESTINATION_FOLDER + Guid.NewGuid().ToString() + ".pdf"; if (outPdf != null) { filename = outPdf; } PdfWriter writer = new PdfWriter(filename, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - PdfADocument doc = new PdfADocument(writer, conformanceLevel, new PdfOutputIntent("Custom", "", "http://www.color.org" + PdfADocument doc = new PdfADocument(writer, conformance, new PdfOutputIntent("Custom", "", "http://www.color.org" , "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm")) ); doc.AddNewPage(); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA4AnnotationCheckTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA4AnnotationCheckTest.cs index c50a00c68e..f07d22ca2b 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA4AnnotationCheckTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA4AnnotationCheckTest.cs @@ -54,7 +54,7 @@ public static void BeforeClass() { public virtual void PdfA4ForbiddenAnnotations1Test() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream(), new WriterProperties().SetPdfVersion(PdfVersion .PDF_2_0)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, CreateOutputIntent()); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, CreateOutputIntent()); PdfPage page = doc.AddNewPage(); PdfAnnotation annot = new PdfFileAttachmentAnnotation(new Rectangle(100, 100, 100, 100)); page.AddAnnotation(annot); @@ -67,7 +67,7 @@ public virtual void PdfA4ForbiddenAnnotations1Test() { public virtual void PdfA4ForbiddenAnnotations2Test() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream(), new WriterProperties().SetPdfVersion(PdfVersion .PDF_2_0)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, CreateOutputIntent()); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, CreateOutputIntent()); PdfPage page = doc.AddNewPage(); PdfAnnotation annot = new PdfSoundAnnotation(new Rectangle(100, 100, 100, 100), new PdfStream()); page.AddAnnotation(annot); @@ -80,7 +80,7 @@ public virtual void PdfA4ForbiddenAnnotations2Test() { public virtual void PdfA4ForbiddenAnnotations3Test() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream(), new WriterProperties().SetPdfVersion(PdfVersion .PDF_2_0)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, CreateOutputIntent()); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, CreateOutputIntent()); PdfPage page = doc.AddNewPage(); PdfAnnotation annot = new Pdf3DAnnotation(new Rectangle(100, 100, 100, 100), new PdfArray()); page.AddAnnotation(annot); @@ -94,7 +94,7 @@ public virtual void PdfA4AllowedAnnotations1Test() { String outPdf = DESTINATION_FOLDER + "pdfA4AllowedAnnotations1Test.pdf"; String cmpPdf = CMP_FOLDER + "cmp_pdfA4AllowedAnnotations1Test.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - using (PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, CreateOutputIntent())) { + using (PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, CreateOutputIntent())) { PdfPage page = doc.AddNewPage(); PdfAnnotation annot = new PdfLinkAnnotation(new Rectangle(100, 100, 100, 100)); annot.SetFlag(PdfAnnotation.PRINT); @@ -108,7 +108,7 @@ public virtual void PdfA4AllowedAnnotations1Test() { public virtual void PdfA4eForbiddenAnnotations1Test() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream(), new WriterProperties().SetPdfVersion(PdfVersion .PDF_2_0)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4E, CreateOutputIntent()); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4E, CreateOutputIntent()); PdfPage page = doc.AddNewPage(); PdfAnnotation annot = new PdfFileAttachmentAnnotation(new Rectangle(100, 100, 100, 100)); page.AddAnnotation(annot); @@ -121,7 +121,7 @@ public virtual void PdfA4eForbiddenAnnotations1Test() { public virtual void PdfA4eForbiddenAnnotations2Test() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream(), new WriterProperties().SetPdfVersion(PdfVersion .PDF_2_0)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4E, CreateOutputIntent()); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4E, CreateOutputIntent()); PdfPage page = doc.AddNewPage(); PdfAnnotation annot = new PdfSoundAnnotation(new Rectangle(100, 100, 100, 100), new PdfStream()); page.AddAnnotation(annot); @@ -135,7 +135,7 @@ public virtual void PdfA4eAllowedAnnotations1Test() { String outPdf = DESTINATION_FOLDER + "pdfA4eAllowedAnnotations1Test.pdf"; String cmpPdf = CMP_FOLDER + "cmp_pdfA4eAllowedAnnotations1Test.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - using (PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4E, CreateOutputIntent())) { + using (PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4E, CreateOutputIntent())) { PdfPage page = doc.AddNewPage(); PdfAnnotation annot = new PdfLinkAnnotation(new Rectangle(100, 100, 100, 100)); annot.SetFlag(PdfAnnotation.PRINT); @@ -150,7 +150,7 @@ public virtual void PdfA4eAllowedAnnotations2Test() { String outPdf = DESTINATION_FOLDER + "pdfA4eAllowedAnnotations2Test.pdf"; String cmpPdf = CMP_FOLDER + "cmp_pdfA4eAllowedAnnotations2Test.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - using (PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4E, CreateOutputIntent())) { + using (PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4E, CreateOutputIntent())) { PdfPage page = doc.AddNewPage(); PdfStream stream3D = new PdfStream(doc, FileUtil.GetInputStreamForFile(CMP_FOLDER + "teapot.u3d")); stream3D.Put(PdfName.Type, PdfName._3D); @@ -177,7 +177,7 @@ public virtual void PdfA4eAllowedAnnotations2Test() { public virtual void PdfA4fForbiddenAnnotations1Test() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream(), new WriterProperties().SetPdfVersion(PdfVersion .PDF_2_0)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4F, CreateOutputIntent()); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4F, CreateOutputIntent()); PdfPage page = doc.AddNewPage(); AddSimpleEmbeddedFile(doc); PdfAnnotation annot = new PdfSoundAnnotation(new Rectangle(100, 100, 100, 100), new PdfStream()); @@ -191,7 +191,7 @@ public virtual void PdfA4fForbiddenAnnotations1Test() { public virtual void PdfA4fForbiddenAnnotations2Test() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream(), new WriterProperties().SetPdfVersion(PdfVersion .PDF_2_0)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4F, CreateOutputIntent()); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4F, CreateOutputIntent()); PdfPage page = doc.AddNewPage(); AddSimpleEmbeddedFile(doc); PdfAnnotation annot = new Pdf3DAnnotation(new Rectangle(100, 100, 100, 100), new PdfArray()); @@ -205,7 +205,7 @@ public virtual void PdfA4fForbiddenAnnotations2Test() { public virtual void PdfA4fForbiddenAnnotations3Test() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream(), new WriterProperties().SetPdfVersion(PdfVersion .PDF_2_0)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4F, CreateOutputIntent()); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4F, CreateOutputIntent()); PdfPage page = doc.AddNewPage(); AddSimpleEmbeddedFile(doc); PdfAnnotation annot = new PdfScreenAnnotation(new Rectangle(100, 100, 100, 100)); @@ -219,7 +219,7 @@ public virtual void PdfA4fForbiddenAnnotations3Test() { public virtual void PdfA4fForbiddenAnnotations4Test() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream(), new WriterProperties().SetPdfVersion(PdfVersion .PDF_2_0)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4F, CreateOutputIntent()); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4F, CreateOutputIntent()); PdfPage page = doc.AddNewPage(); AddSimpleEmbeddedFile(doc); PdfAnnotation annot = new PdfTextAnnotation(new Rectangle(100, 100, 100, 100)); @@ -235,7 +235,7 @@ public virtual void PdfA4fAllowedAnnotations1Test() { String outPdf = DESTINATION_FOLDER + "pdfA4fAllowedAnnotations1Test.pdf"; String cmpPdf = CMP_FOLDER + "cmp_pdfA4fAllowedAnnotations1Test.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - using (PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4F, CreateOutputIntent())) { + using (PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4F, CreateOutputIntent())) { PdfPage page = doc.AddNewPage(); AddSimpleEmbeddedFile(doc); PdfAnnotation annot = new PdfFileAttachmentAnnotation(new Rectangle(100, 100, 100, 100)); @@ -252,7 +252,7 @@ public virtual void PdfA4fAllowedAnnotations2Test() { String outPdf = DESTINATION_FOLDER + "pdfA4fAllowedAnnotations2Test.pdf"; String cmpPdf = CMP_FOLDER + "cmp_pdfA4fAllowedAnnotations2Test.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - using (PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4F, CreateOutputIntent())) { + using (PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4F, CreateOutputIntent())) { PdfPage page = doc.AddNewPage(); AddSimpleEmbeddedFile(doc); PdfAnnotation annot = new PdfLinkAnnotation(new Rectangle(100, 100, 100, 100)); @@ -268,7 +268,7 @@ public virtual void PdfA4AllowedAnnotWithoutApTest() { String outPdf = DESTINATION_FOLDER + "pdfA4AllowedAnnotWithoutApTest.pdf"; String cmpPdf = CMP_FOLDER + "cmp_pdfA4AllowedAnnotWithoutApTest.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - using (PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, CreateOutputIntent())) { + using (PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, CreateOutputIntent())) { PdfPage page = doc.AddNewPage(); PdfAnnotation annot = new PdfA4AnnotationCheckTest.PdfProjectionAnnotation(new Rectangle(100, 100, 100, 100 )); @@ -283,7 +283,7 @@ public virtual void PdfA4AllowedAnnotWithoutApTest() { public virtual void PdfA4ForbiddenAKeyWidgetAnnotationTest() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream(), new WriterProperties().SetPdfVersion(PdfVersion .PDF_2_0)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4F, CreateOutputIntent()); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4F, CreateOutputIntent()); PdfPage page = doc.AddNewPage(); AddSimpleEmbeddedFile(doc); PdfAnnotation annot = new PdfWidgetAnnotation(new Rectangle(100, 100, 100, 100)); @@ -300,7 +300,7 @@ public virtual void PdfA4AllowedAAKeyWidgetAnnotationTest() { String outPdf = DESTINATION_FOLDER + "pdfA4AllowedAAKeyWidgetAnnotationTest.pdf"; String cmpPdf = CMP_FOLDER + "cmp_pdfA4AllowedAAKeyWidgetAnnotationTest.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - using (PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, CreateOutputIntent())) { + using (PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, CreateOutputIntent())) { PdfPage page = doc.AddNewPage(); PdfAnnotation annot = new PdfWidgetAnnotation(new Rectangle(100, 100, 100, 100)); annot.GetPdfObject().Put(PdfName.AA, (new PdfAction()).GetPdfObject()); @@ -315,7 +315,7 @@ public virtual void PdfA4AllowedAAKeyWidgetAnnotationTest() { public virtual void PdfA4BtnAppearanceContainsNStreamWidgetAnnotationTest() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream(), new WriterProperties().SetPdfVersion(PdfVersion .PDF_2_0)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4F, CreateOutputIntent()); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4F, CreateOutputIntent()); PdfPage page = doc.AddNewPage(); AddSimpleEmbeddedFile(doc); PdfAnnotation annot = new PdfWidgetAnnotation(new Rectangle(100, 100, 100, 100)); @@ -332,7 +332,7 @@ public virtual void PdfA4BtnAppearanceContainsNStreamWidgetAnnotationTest() { public virtual void PdfA4AppearanceContainsNDictWidgetAnnotationTest() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream(), new WriterProperties().SetPdfVersion(PdfVersion .PDF_2_0)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4F, CreateOutputIntent()); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4F, CreateOutputIntent()); PdfPage page = doc.AddNewPage(); AddSimpleEmbeddedFile(doc); PdfAnnotation annot = new PdfWidgetAnnotation(new Rectangle(100, 100, 100, 100)); @@ -349,7 +349,7 @@ public virtual void PdfA4AppearanceContainsNDictWidgetAnnotationTest() { public virtual void PdfA4AppearanceContainsOtherKeyWidgetAnnotationTest() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream(), new WriterProperties().SetPdfVersion(PdfVersion .PDF_2_0)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4F, CreateOutputIntent()); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4F, CreateOutputIntent()); PdfPage page = doc.AddNewPage(); AddSimpleEmbeddedFile(doc); PdfAnnotation annot = new PdfWidgetAnnotation(new Rectangle(100, 100, 100, 100)); @@ -367,7 +367,7 @@ public virtual void PdfA4ForbiddenAAKeyAnnotationTest() { String outPdf = DESTINATION_FOLDER + "pdfA4ForbiddenAAKeyAnnotationTest.pdf"; String cmpPdf = CMP_FOLDER + "cmp_pdfA4ForbiddenAAKeyAnnotationTest.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, CreateOutputIntent()); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, CreateOutputIntent()); PdfPage page = doc.AddNewPage(); PdfAnnotation annot = new PdfLinkAnnotation(new Rectangle(100, 100, 100, 100)); PdfDictionary dict = new PdfDictionary(); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA4CatalogCheckTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA4CatalogCheckTest.cs index 3ac4cabcc5..3ad2fae606 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA4CatalogCheckTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA4CatalogCheckTest.cs @@ -57,8 +57,8 @@ public virtual void CreateSimpleDocTest() { String outPdf = destinationFolder + "pdfA4_catalogCheck01.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); doc.Close(); NUnit.Framework.Assert.IsNull(new VeraPdfValidator().Validate(outPdf)); @@ -71,8 +71,8 @@ public virtual void CreateSimpleTaggedDocTest() { String cmpPdf = sourceFolder + "cmp/PdfA4CatalogCheckTest/cmp_pdfA4_tagged.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument pdfDoc = (PdfADocument)new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent - ("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", @is)).SetTagged(); + PdfADocument pdfDoc = (PdfADocument)new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent( + "Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", @is)).SetTagged(); PdfFont font = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", "WinAnsi", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); Document document = new Document(pdfDoc); @@ -94,8 +94,8 @@ public virtual void InvalidCatalogVersionCheckTest() { String outPdf = destinationFolder + "pdfA4_catalogCheck02.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); doc.GetCatalog().Put(PdfName.Version, new PdfString("1.7")); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => doc.Close()); @@ -113,8 +113,8 @@ public virtual void EncryptInTrailerTest() { (userPassword, ownerPassword, permissions, EncryptionConstants.ENCRYPTION_AES_256).SetFullCompressionMode (false)); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => doc.Close()); NUnit.Framework.Assert.AreEqual(PdfaExceptionMessageConstant.KEYWORD_ENCRYPT_SHALL_NOT_BE_USED_IN_THE_TRAILER_DICTIONARY @@ -123,7 +123,7 @@ public virtual void EncryptInTrailerTest() { [NUnit.Framework.Test] public virtual void EncryptedDocumentTest() { - String outPdf = destinationFolder + "pdfA4_catalogCheck03.pdf"; + String outPdf = destinationFolder + "pdfA4_encryptedDocument.pdf"; byte[] userPassword = "user".GetBytes(iText.Commons.Utils.EncodingUtil.ISO_8859_1); byte[] ownerPassword = "owner".GetBytes(iText.Commons.Utils.EncodingUtil.ISO_8859_1); int permissions = EncryptionConstants.ALLOW_SCREENREADERS | EncryptionConstants.ALLOW_DEGRADED_PRINTING; @@ -131,8 +131,8 @@ public virtual void EncryptedDocumentTest() { (userPassword, ownerPassword, permissions, EncryptionConstants.ENCRYPTION_AES_256).SetFullCompressionMode (true)); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => doc.Close()); NUnit.Framework.Assert.AreEqual(PdfaExceptionMessageConstant.KEYWORD_ENCRYPT_SHALL_NOT_BE_USED_IN_THE_TRAILER_DICTIONARY @@ -144,8 +144,8 @@ public virtual void AbsentPieceInfoTest() { String outPdf = destinationFolder + "pdfA4_catalogCheck04.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfDictionary info = new PdfDictionary(); String timeValue = "D:19860426012347+04'00'"; @@ -162,8 +162,8 @@ public virtual void ValidCatalogCheckTest() { String cmpPdf = sourceFolder + "cmp/PdfA4CatalogCheckTest/cmp_pdfA4_catalogCheck05.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); doc.GetCatalog().Put(PdfName.PieceInfo, new PdfDictionary()); doc.Close(); @@ -179,8 +179,8 @@ public virtual void InvalidInfoTest() { String outPdf = destinationFolder + "pdfA4_catalogCheck05.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); doc.GetTrailer().Put(PdfName.Info, new PdfDictionary()); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => doc.Close()); @@ -188,6 +188,20 @@ public virtual void InvalidInfoTest() { , e.Message); } + [NUnit.Framework.Test] + public virtual void InvalidInfoWithFullCompression() { + String outPdf = destinationFolder + "invalidInfoWithFillCompression.pdf"; + PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0).SetFullCompressionMode + (true)); + Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); + using (PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", + "", "http://www.color.org", "sRGB IEC61966-2.1", @is))) { + doc.AddNewPage(); + } + NUnit.Framework.Assert.IsNull(new VeraPdfValidator().Validate(outPdf)); + } + + // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf\a validation on Android) [NUnit.Framework.Test] public virtual void ReadValidDocumentTest() { String outPdf = destinationFolder + "simplePdfA4_output01.pdf"; @@ -204,8 +218,8 @@ public virtual void InvalidVersionInCatalogTest() { String outPdf = destinationFolder + "pdfA4_catalogCheck06.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); doc.GetCatalog().Put(PdfName.Version, new PdfString("1.7")); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => doc.Close()); @@ -218,8 +232,8 @@ public virtual void CorruptedVersionInCatalogTest() { String outPdf = destinationFolder + "pdfA4_catalogCheck07.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); doc.GetCatalog().Put(PdfName.Version, new PdfString("2ae")); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => doc.Close()); @@ -244,7 +258,7 @@ public virtual void CheckReferenceXObject() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, outputIntent); doc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(doc.GetLastPage()); PdfFormXObject xObject = new PdfFormXObject(new Rectangle(100, 100)); @@ -264,7 +278,7 @@ public virtual void CheckOpiInXObject() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, outputIntent); doc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(doc.GetLastPage()); PdfFormXObject xObject = new PdfFormXObject(new Rectangle(100, 100)); @@ -285,7 +299,7 @@ public virtual void ValidFormXObjectTest() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, outputIntent); doc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(doc.GetLastPage()); PdfFormXObject xObject = new PdfFormXObject(new Rectangle(100, 100)); @@ -302,11 +316,11 @@ public virtual void ValidFormXObjectTest() { // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf\a validation on Android) [NUnit.Framework.Test] public virtual void CreateInvalidPdfAVersionNumberWithPDFA4() { - PdfWriter writer = new PdfWriter(new PdfWriter(new MemoryStream()), new WriterProperties().SetPdfVersion(PdfVersion - .PDF_1_7)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm" - ))); + PdfWriter writer = new PdfWriter(new PdfWriter(new MemoryStream()), new WriterProperties()); + PdfA4CatalogCheckTest.PdfDocumentCustomVersion doc = new PdfA4CatalogCheckTest.PdfDocumentCustomVersion(writer + , PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" + , FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"))); + doc.SetPdfVersion(PdfVersion.PDF_1_7); doc.AddNewPage(); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => doc.Close()); NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(PdfaExceptionMessageConstant.THE_FILE_HEADER_SHALL_CONTAIN_RIGHT_PDF_VERSION @@ -315,11 +329,11 @@ public virtual void CreateInvalidPdfAVersionNumberWithPDFA4() { [NUnit.Framework.Test] public virtual void CreateInvalidPdfAVersionNumberWithPDFA4F() { - PdfWriter writer = new PdfWriter(new PdfWriter(new MemoryStream()), new WriterProperties().SetPdfVersion(PdfVersion - .PDF_1_7)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4F, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm" - ))); + PdfWriter writer = new PdfWriter(new PdfWriter(new MemoryStream()), new WriterProperties()); + PdfA4CatalogCheckTest.PdfDocumentCustomVersion doc = new PdfA4CatalogCheckTest.PdfDocumentCustomVersion(writer + , PdfAConformance.PDF_A_4F, new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" + , FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"))); + doc.SetPdfVersion(PdfVersion.PDF_1_7); doc.AddNewPage(); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => doc.Close()); NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(PdfaExceptionMessageConstant.THE_FILE_HEADER_SHALL_CONTAIN_RIGHT_PDF_VERSION @@ -328,11 +342,11 @@ public virtual void CreateInvalidPdfAVersionNumberWithPDFA4F() { [NUnit.Framework.Test] public virtual void CreateInvalidPdfAVersionNumberWithPDFA4E() { - PdfWriter writer = new PdfWriter(new PdfWriter(new MemoryStream()), new WriterProperties().SetPdfVersion(PdfVersion - .PDF_1_7)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4E, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm" - ))); + PdfWriter writer = new PdfWriter(new PdfWriter(new MemoryStream()), new WriterProperties()); + PdfA4CatalogCheckTest.PdfDocumentCustomVersion doc = new PdfA4CatalogCheckTest.PdfDocumentCustomVersion(writer + , PdfAConformance.PDF_A_4E, new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" + , FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"))); + doc.SetPdfVersion(PdfVersion.PDF_1_7); doc.AddNewPage(); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => doc.Close()); NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(PdfaExceptionMessageConstant.THE_FILE_HEADER_SHALL_CONTAIN_RIGHT_PDF_VERSION @@ -341,11 +355,11 @@ public virtual void CreateInvalidPdfAVersionNumberWithPDFA4E() { [NUnit.Framework.Test] public virtual void CreateInvalidPdfAVersion16NumberWithPDFA4() { - PdfWriter writer = new PdfWriter(new PdfWriter(new MemoryStream()), new WriterProperties().SetPdfVersion(PdfVersion - .PDF_1_6)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm" - ))); + PdfWriter writer = new PdfWriter(new PdfWriter(new MemoryStream()), new WriterProperties()); + PdfA4CatalogCheckTest.PdfDocumentCustomVersion doc = new PdfA4CatalogCheckTest.PdfDocumentCustomVersion(writer + , PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" + , FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"))); + doc.SetPdfVersion(PdfVersion.PDF_1_6); doc.AddNewPage(); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => doc.Close()); NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(PdfaExceptionMessageConstant.THE_FILE_HEADER_SHALL_CONTAIN_RIGHT_PDF_VERSION @@ -354,11 +368,11 @@ public virtual void CreateInvalidPdfAVersion16NumberWithPDFA4() { [NUnit.Framework.Test] public virtual void CreateInvalidPdfAVersion13NumberWithPDFA4F() { - PdfWriter writer = new PdfWriter(new PdfWriter(new MemoryStream()), new WriterProperties().SetPdfVersion(PdfVersion - .PDF_1_3)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4F, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm" - ))); + PdfWriter writer = new PdfWriter(new PdfWriter(new MemoryStream()), new WriterProperties()); + PdfA4CatalogCheckTest.PdfDocumentCustomVersion doc = new PdfA4CatalogCheckTest.PdfDocumentCustomVersion(writer + , PdfAConformance.PDF_A_4F, new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" + , FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"))); + doc.SetPdfVersion(PdfVersion.PDF_1_3); doc.AddNewPage(); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => doc.Close()); NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(PdfaExceptionMessageConstant.THE_FILE_HEADER_SHALL_CONTAIN_RIGHT_PDF_VERSION @@ -367,15 +381,26 @@ public virtual void CreateInvalidPdfAVersion13NumberWithPDFA4F() { [NUnit.Framework.Test] public virtual void CreateInvalidPdfAVersionNumber17WithPDFA4E() { - PdfWriter writer = new PdfWriter(new PdfWriter(new MemoryStream()), new WriterProperties().SetPdfVersion(PdfVersion - .PDF_1_7)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4E, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm" - ))); + PdfWriter writer = new PdfWriter(new PdfWriter(new MemoryStream()), new WriterProperties()); + PdfA4CatalogCheckTest.PdfDocumentCustomVersion doc = new PdfA4CatalogCheckTest.PdfDocumentCustomVersion(writer + , PdfAConformance.PDF_A_4E, new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" + , FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"))); + doc.SetPdfVersion(PdfVersion.PDF_1_7); doc.AddNewPage(); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => doc.Close()); NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(PdfaExceptionMessageConstant.THE_FILE_HEADER_SHALL_CONTAIN_RIGHT_PDF_VERSION , "2"), e.Message); } + + private class PdfDocumentCustomVersion : PdfADocument { + public PdfDocumentCustomVersion(PdfWriter writer, PdfAConformance aConformance, PdfOutputIntent outputIntent + ) + : base(writer, aConformance, outputIntent) { + } + + public virtual void SetPdfVersion(PdfVersion pdfVersion) { + this.pdfVersion = pdfVersion; + } + } } } diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA4EmbeddedFilesCheckTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA4EmbeddedFilesCheckTest.cs index d4893cb919..5939173f61 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA4EmbeddedFilesCheckTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA4EmbeddedFilesCheckTest.cs @@ -47,7 +47,7 @@ public static void BeforeClass() { public virtual void PdfA4fWithoutEmbeddedFilesTest() { String outPdf = DESTINATION_FOLDER + "pdfA4fWithoutEmbeddedFilesTest.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4F, CreateOutputIntent()); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4F, CreateOutputIntent()); doc.AddNewPage(); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => doc.Close()); NUnit.Framework.Assert.AreEqual(PdfaExceptionMessageConstant.NAME_DICTIONARY_SHALL_CONTAIN_EMBEDDED_FILES_KEY @@ -58,7 +58,7 @@ public virtual void PdfA4fWithoutEmbeddedFilesTest() { public virtual void PdfA4fWithEmbeddedFilesWithoutFTest() { String outPdf = DESTINATION_FOLDER + "pdfA4fWithEmbeddedFilesWithoutFTest.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4F, CreateOutputIntent()); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4F, CreateOutputIntent()); doc.AddNewPage(); PdfFileSpec fs = PdfFileSpec.CreateEmbeddedFileSpec(doc, "file".GetBytes(), "description", "file.txt", null , null, null); @@ -66,7 +66,7 @@ public virtual void PdfA4fWithEmbeddedFilesWithoutFTest() { fsDict.Remove(PdfName.F); doc.AddFileAttachment("file.txt", fs); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => doc.Close()); - NUnit.Framework.Assert.AreEqual(PdfAConformanceException.FILE_SPECIFICATION_DICTIONARY_SHALL_CONTAIN_F_KEY_AND_UF_KEY + NUnit.Framework.Assert.AreEqual(PdfaExceptionMessageConstant.FILE_SPECIFICATION_DICTIONARY_SHALL_CONTAIN_F_KEY_AND_UF_KEY , e.Message); } @@ -74,7 +74,7 @@ public virtual void PdfA4fWithEmbeddedFilesWithoutFTest() { public virtual void PdfA4fWithEmbeddedFilesWithoutUFTest() { String outPdf = DESTINATION_FOLDER + "pdfA4fWithEmbeddedFilesWithoutUFTest.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4F, CreateOutputIntent()); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4F, CreateOutputIntent()); doc.AddNewPage(); PdfFileSpec fs = PdfFileSpec.CreateEmbeddedFileSpec(doc, "file".GetBytes(), "description", "file.txt", null , null, null); @@ -82,7 +82,7 @@ public virtual void PdfA4fWithEmbeddedFilesWithoutUFTest() { fsDict.Remove(PdfName.UF); doc.AddFileAttachment("file.txt", fs); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => doc.Close()); - NUnit.Framework.Assert.AreEqual(PdfAConformanceException.FILE_SPECIFICATION_DICTIONARY_SHALL_CONTAIN_F_KEY_AND_UF_KEY + NUnit.Framework.Assert.AreEqual(PdfaExceptionMessageConstant.FILE_SPECIFICATION_DICTIONARY_SHALL_CONTAIN_F_KEY_AND_UF_KEY , e.Message); } @@ -90,7 +90,7 @@ public virtual void PdfA4fWithEmbeddedFilesWithoutUFTest() { public virtual void PdfA4fWithEmbeddedFilesWithoutAFRTest() { String outPdf = DESTINATION_FOLDER + "pdfA4fWithEmbeddedFilesWithoutAFRTest.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4F, CreateOutputIntent()); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4F, CreateOutputIntent()); doc.AddNewPage(); PdfFileSpec fs = PdfFileSpec.CreateEmbeddedFileSpec(doc, "file".GetBytes(), "description", "file.txt", null , null, null); @@ -106,7 +106,7 @@ public virtual void PdfA4fWithEmbeddedFilesWithoutAFRTest() { public virtual void PdfA4eWithEmbeddedFilesWithoutFTest() { String outPdf = DESTINATION_FOLDER + "pdfA4eWithEmbeddedFilesWithoutFTest.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4E, CreateOutputIntent()); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4E, CreateOutputIntent()); doc.AddNewPage(); PdfFileSpec fs = PdfFileSpec.CreateEmbeddedFileSpec(doc, "file".GetBytes(), "description", "file.txt", null , null, null); @@ -114,7 +114,7 @@ public virtual void PdfA4eWithEmbeddedFilesWithoutFTest() { fsDict.Remove(PdfName.F); doc.AddFileAttachment("file.txt", fs); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => doc.Close()); - NUnit.Framework.Assert.AreEqual(PdfAConformanceException.FILE_SPECIFICATION_DICTIONARY_SHALL_CONTAIN_F_KEY_AND_UF_KEY + NUnit.Framework.Assert.AreEqual(PdfaExceptionMessageConstant.FILE_SPECIFICATION_DICTIONARY_SHALL_CONTAIN_F_KEY_AND_UF_KEY , e.Message); } @@ -122,7 +122,7 @@ public virtual void PdfA4eWithEmbeddedFilesWithoutFTest() { public virtual void PdfA4WithEmbeddedFilesWithoutAFRTest() { String outPdf = DESTINATION_FOLDER + "pdfA4WithEmbeddedFilesWithoutAFRTest.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, CreateOutputIntent()); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, CreateOutputIntent()); doc.AddNewPage(); PdfFileSpec fs = PdfFileSpec.CreateEmbeddedFileSpec(doc, "file".GetBytes(), "description", "file.txt", null , null, null); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA4GraphicsCheckTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA4GraphicsCheckTest.cs index 357bee7000..d60247b525 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA4GraphicsCheckTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA4GraphicsCheckTest.cs @@ -64,7 +64,7 @@ public virtual void ValidHalftoneTest() { Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - using (PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, outputIntent)) { + using (PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, outputIntent)) { doc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(doc.GetLastPage()); PdfDictionary colourantHalftone = new PdfDictionary(); @@ -89,7 +89,7 @@ public virtual void ValidHalftoneType1Test() { Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - using (PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, outputIntent)) { + using (PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, outputIntent)) { doc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(doc.GetLastPage()); PdfDictionary halftone = new PdfDictionary(); @@ -110,7 +110,7 @@ public virtual void ValidHalftoneTest2() { Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - using (PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, outputIntent)) { + using (PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, outputIntent)) { doc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(doc.GetLastPage()); PdfDictionary colourantHalftone = new PdfDictionary(); @@ -137,7 +137,7 @@ public virtual void ValidHalftoneTest3() { Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - using (PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, outputIntent)) { + using (PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, outputIntent)) { doc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(doc.GetLastPage()); PdfDictionary colourantHalftone = new PdfDictionary(); @@ -163,7 +163,7 @@ public virtual void InvalidHalftoneTest1() { Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - using (PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, outputIntent)) { + using (PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, outputIntent)) { doc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(doc.GetLastPage()); PdfDictionary halftone = new PdfDictionary(); @@ -183,7 +183,7 @@ public virtual void InvalidHalftoneTest2() { Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - using (PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, outputIntent)) { + using (PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, outputIntent)) { doc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(doc.GetLastPage()); PdfDictionary halftone = new PdfDictionary(); @@ -224,7 +224,7 @@ public virtual void ColorCheckTest1() { Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - using (PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, outputIntent)) { + using (PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, outputIntent)) { float[] whitePoint = new float[] { 0.9505f, 1f, 1.089f }; float[] gamma = new float[] { 2.2f, 2.2f, 2.2f }; float[] matrix = new float[] { 0.4124f, 0.2126f, 0.0193f, 0.3576f, 0.7152f, 0.1192f, 0.1805f, 0.0722f, 0.9505f @@ -234,7 +234,7 @@ public virtual void ColorCheckTest1() { canvas.GetResources().SetDefaultCmyk(calRgb); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => canvas.SetFillColor(new DeviceCmyk(0.1f, 0.1f, 0.1f, 0.1f))); - NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(PdfAConformanceException.COLOR_SPACE_0_SHALL_HAVE_1_COMPONENTS + NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(PdfaExceptionMessageConstant.COLOR_SPACE_0_SHALL_HAVE_1_COMPONENTS , PdfName.DefaultCMYK.GetValue(), 4), e.Message); } } @@ -244,7 +244,7 @@ public virtual void ColorCheckTest2() { String outPdf = DESTINATION_FOLDER + "pdfA4_colorCheckTest2.pdf"; String cmpPdf = CMP_FOLDER + "cmp_pdfA4_colorCheckTest2.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - using (PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, null)) { + using (PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, null)) { float[] whitePoint = new float[] { 0.9505f, 1f, 1.089f }; float[] gamma = new float[] { 2.2f, 2.2f, 2.2f }; float[] matrix = new float[] { 0.4124f, 0.2126f, 0.0193f, 0.3576f, 0.7152f, 0.1192f, 0.1805f, 0.0722f, 0.9505f @@ -271,7 +271,7 @@ public virtual void ColorCheckTest3() { Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, outputIntent); PdfCanvas canvas = new PdfCanvas(doc.AddNewPage()); canvas.SetFillColor(new DeviceCmyk(0.1f, 0.1f, 0.1f, 0.1f)); canvas.MoveTo(doc.GetDefaultPageSize().GetLeft(), doc.GetDefaultPageSize().GetBottom()); @@ -291,7 +291,7 @@ public virtual void ColorCheckTest4() { Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, outputIntent); PdfCanvas canvas = new PdfCanvas(doc.AddNewPage()); canvas.SetFillColor(ColorConstants.BLUE); canvas.SetStrokeColor(new DeviceCmyk(0.1f, 0.1f, 0.1f, 0.1f)); @@ -317,7 +317,7 @@ public virtual void ColorCheckTest5() { Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, outputIntent); PdfPage page = doc.AddNewPage(); page.AddOutputIntent(new PdfOutputIntent("Custom", "", "http://www.color.org", "cmyk", FileUtil.GetInputStreamForFile (SOURCE_FOLDER + "USWebUncoated.icc"))); @@ -347,7 +347,7 @@ public virtual void ColorCheckTest6() { Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, outputIntent); PdfCanvas canvas = new PdfCanvas(doc.AddNewPage()); String shortText = "text"; PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "FreeSans.ttf", PdfFontFactory.EmbeddingStrategy. @@ -372,7 +372,7 @@ public virtual void ColorCheckTest7() { Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, outputIntent); PdfPage page = doc.AddNewPage(); page.AddOutputIntent(new PdfOutputIntent("Custom", "", "http://www.color.org", "cmyk", FileUtil.GetInputStreamForFile (SOURCE_FOLDER + "USWebUncoated.icc"))); @@ -402,7 +402,7 @@ public virtual void ColorCheckTest8() { Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, outputIntent); PdfCanvas canvas = new PdfCanvas(doc.AddNewPage()); String shortText = "text"; PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "FreeSans.ttf", PdfFontFactory.EmbeddingStrategy. @@ -427,7 +427,7 @@ public virtual void ColorCheckTest9() { Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, outputIntent); PdfPage page = doc.AddNewPage(); page.AddOutputIntent(new PdfOutputIntent("Custom", "", "http://www.color.org", "cmyk", FileUtil.GetInputStreamForFile (SOURCE_FOLDER + "USWebUncoated.icc"))); @@ -451,7 +451,7 @@ public virtual void ColorCheckTest10() { String outPdf = DESTINATION_FOLDER + "pdfA4_colorCheckTest10.pdf"; String cmpPdf = CMP_FOLDER + "cmp_pdfA4_colorCheckTest10.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, null); + PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformance.PDF_A_4, null); PdfPage page = pdfDoc.AddNewPage(); // Add page blending colorspace PdfTransparencyGroup transparencyGroup = new PdfTransparencyGroup(); @@ -471,7 +471,7 @@ public virtual void ColorCheckTest11() { String outPdf = DESTINATION_FOLDER + "pdfA4_colorCheckTest11.pdf"; String cmpPdf = CMP_FOLDER + "cmp_pdfA4_colorCheckTest11.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, null); + PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformance.PDF_A_4, null); PdfPage page = pdfDoc.AddNewPage(); // Add page blending colorspace PdfTransparencyGroup transparencyGroup = new PdfTransparencyGroup(); @@ -504,7 +504,7 @@ public virtual void ColorCheckTest12() { String outPdf = DESTINATION_FOLDER + "pdfA4_colorCheckTest12.pdf"; String cmpPdf = CMP_FOLDER + "cmp_pdfA4_colorCheckTest12.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, null); + PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformance.PDF_A_4, null); PdfPage page = pdfDoc.AddNewPage(); // Add page blending colorspace PdfTransparencyGroup transparencyGroup = new PdfTransparencyGroup(); @@ -523,7 +523,7 @@ public virtual void ColorCheckTest12() { public virtual void DefaultTextColorCheckTest() { String outPdf = DESTINATION_FOLDER + "defaultColorCheck.pdf"; PdfDocument pdfDocument = new PdfADocument(new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion - .PDF_2_0)), PdfAConformanceLevel.PDF_A_4, null); + .PDF_2_0)), PdfAConformance.PDF_A_4, null); PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "FreeSans.ttf", "Identity-H", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); PdfPage page = pdfDocument.AddNewPage(); @@ -541,7 +541,7 @@ public virtual void DefaultTextColorCheckWithPageOutputIntentTest() { String outPdf = DESTINATION_FOLDER + "defaultTextColorCheckWithPageOutputIntent.pdf"; String cmpPdf = CMP_FOLDER + "cmp_pdfA4_defaultTextColorCheckWithPageOutputIntent.pdf"; PdfDocument pdfDocument = new PdfADocument(new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion - .PDF_2_0)), PdfAConformanceLevel.PDF_A_4, null); + .PDF_2_0)), PdfAConformance.PDF_A_4, null); PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "FreeSans.ttf", "Identity-H", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); PdfPage page = pdfDocument.AddNewPage(); @@ -560,7 +560,7 @@ public virtual void DefaultTextColorCheckForInvisibleTextTest() { String outPdf = DESTINATION_FOLDER + "pdfA4_defaultColorCheckInvisibleText.pdf"; String cmpPdf = CMP_FOLDER + "cmp_pdfA4_defaultColorCheckInvisibleText.pdf"; PdfDocument pdfDocument = new PdfADocument(new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion - .PDF_2_0)), PdfAConformanceLevel.PDF_A_4, null); + .PDF_2_0)), PdfAConformance.PDF_A_4, null); PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "FreeSans.ttf", "Identity-H", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); PdfPage page = pdfDocument.AddNewPage(); @@ -576,7 +576,7 @@ public virtual void DefaultTextColorCheckForInvisibleTextTest() { public virtual void DefaultStrokeColorCheckTest() { String outPdf = DESTINATION_FOLDER + "defaultColorCheck.pdf"; PdfDocument pdfDocument = new PdfADocument(new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion - .PDF_2_0)), PdfAConformanceLevel.PDF_A_4, null); + .PDF_2_0)), PdfAConformance.PDF_A_4, null); PdfPage page = pdfDocument.AddNewPage(); PdfCanvas canvas = new PdfCanvas(page); canvas.SaveState(); @@ -605,7 +605,7 @@ public virtual void ColorCheckWithDuplicatedCmykColorspaceTest1() { Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, outputIntent); + PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformance.PDF_A_4, outputIntent); PdfPage page = pdfDoc.AddNewPage(); page.AddOutputIntent(new PdfOutputIntent("Custom", "", "http://www.color.org", "cmyk", FileUtil.GetInputStreamForFile (SOURCE_FOLDER + "USWebUncoated.icc"))); @@ -627,7 +627,7 @@ public virtual void ColorCheckWithDuplicatedCmykColorspaceTest2() { Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, outputIntent); + PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformance.PDF_A_4, outputIntent); PdfPage page = pdfDoc.AddNewPage(); // Add page blending colorspace PdfTransparencyGroup transparencyGroup = new PdfTransparencyGroup(); @@ -654,7 +654,7 @@ public virtual void ColorCheckWithDuplicatedCmykColorspaceTest3() { Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, outputIntent); + PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformance.PDF_A_4, outputIntent); PdfPage page = pdfDoc.AddNewPage(); // Add page blending colorspace PdfTransparencyGroup transparencyGroup = new PdfTransparencyGroup(); @@ -690,7 +690,7 @@ public virtual void ColorCheckWithDuplicatedCmykColorspaceTest4() { Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, outputIntent); + PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformance.PDF_A_4, outputIntent); PdfPage page = pdfDoc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(page); // Create color @@ -729,7 +729,7 @@ public virtual void ColorCheckWithDuplicatedRgbColorspaceTest() { Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, outputIntent); + PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformance.PDF_A_4, outputIntent); PdfPage page = pdfDoc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(page); // Create color @@ -748,7 +748,7 @@ public virtual void ColorCheckWithDuplicatedRgbAndCmykColorspaceTest() { Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, outputIntent); + PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformance.PDF_A_4, outputIntent); PdfPage page = pdfDoc.AddNewPage(); page.AddOutputIntent(new PdfOutputIntent("Custom", "", "http://www.color.org", "cmyk", FileUtil.GetInputStreamForFile (SOURCE_FOLDER + "USWebUncoated.icc"))); @@ -772,7 +772,7 @@ public virtual void ColorCheckWithDuplicated2CmykColorspacesTest() { Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, outputIntent); + PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformance.PDF_A_4, outputIntent); PdfPage page = pdfDoc.AddNewPage(); page.AddOutputIntent(new PdfOutputIntent("Custom", "", "http://www.color.org", "cmyk", FileUtil.GetInputStreamForFile (SOURCE_FOLDER + "USWebUncoated.icc"))); @@ -794,8 +794,8 @@ public virtual void ColourSpaceTest01() { String cmpPdf = CMP_FOLDER + "cmp_pdfA4_colourSpaceTest01.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); PdfColorSpace alternateSpace = new PdfDeviceCs.Rgb(); //Tint transformation function is a stream @@ -819,8 +819,8 @@ public virtual void ColourSpaceTest02() { String cmpPdf = CMP_FOLDER + "cmp_pdfA4_colourSpaceTest02.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); PdfColorSpace alternateSpace = new PdfDeviceCs.Rgb(); //Tint transformation function is a dictionary @@ -844,8 +844,8 @@ public virtual void ColourSpaceTest03() { String cmpPdf = CMP_FOLDER + "cmp_pdfA4_colourSpaceTest03.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); PdfColorSpace alternateSpace = new PdfDeviceCs.Rgb(); //Tint transformation function is a dictionary @@ -875,7 +875,7 @@ public virtual void ImageFailureTest() { String outPdf = DESTINATION_FOLDER + "imageFailure.pdf"; String cmpPdf = CMP_FOLDER + "cmp_pdfA4_imageFailure.pdf"; PdfDocument pdfDoc = new PdfADocument(new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion - .PDF_2_0)), PdfAConformanceLevel.PDF_A_4, null); + .PDF_2_0)), PdfAConformance.PDF_A_4, null); PdfPage page = pdfDoc.AddNewPage(); // This should suppress transparency issue page.AddOutputIntent(new PdfOutputIntent("Custom", "", "http://www.color.org", "cmyk", FileUtil.GetInputStreamForFile @@ -896,7 +896,7 @@ public virtual void ImageTest() { String outPdf = DESTINATION_FOLDER + "pdfA4_image.pdf"; String cmpPdf = CMP_FOLDER + "cmp_pdfA4_image.pdf"; PdfDocument pdfDoc = new PdfADocument(new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion - .PDF_2_0)), PdfAConformanceLevel.PDF_A_4, null); + .PDF_2_0)), PdfAConformance.PDF_A_4, null); PdfPage page = pdfDoc.AddNewPage(); // This should suppress transparency and device RGB page.AddOutputIntent(new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", FileUtil @@ -914,7 +914,7 @@ public virtual void ImageTest() { public virtual void ImageJpeg20002ColorChannelsTest() { String outPdf = DESTINATION_FOLDER + "pdfA4_jpeg2000.pdf"; PdfDocument pdfDoc = new PdfADocument(new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion - .PDF_2_0)), PdfAConformanceLevel.PDF_A_4, null); + .PDF_2_0)), PdfAConformance.PDF_A_4, null); PdfPage page = pdfDoc.AddNewPage(); // This should suppress transparency and device RGB page.AddOutputIntent(new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", FileUtil @@ -934,7 +934,7 @@ public virtual void ImageJpeg2000Test() { String outPdf = DESTINATION_FOLDER + "pdfA4_jpeg2000.pdf"; String cmpPdf = CMP_FOLDER + "cmp_pdfA4_jpeg2000.pdf"; PdfDocument pdfDoc = new PdfADocument(new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion - .PDF_2_0)), PdfAConformanceLevel.PDF_A_4, null); + .PDF_2_0)), PdfAConformance.PDF_A_4, null); PdfPage page = pdfDoc.AddNewPage(); // This should suppress transparency and device RGB page.AddOutputIntent(new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", FileUtil @@ -953,7 +953,7 @@ public virtual void PdfA4AnnotationsNoOutputIntentTest() { String outPdf = DESTINATION_FOLDER + "pdfA4AnnotationsNoOutputIntent.pdf"; String cmpPdf = CMP_FOLDER + "cmp_pdfA4AnnotationsNoOutputIntent.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, null); + PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformance.PDF_A_4, null); PdfPage page = pdfDoc.AddNewPage(); PdfAnnotation annot = new PdfCircleAnnotation(new Rectangle(100, 100, 100, 100)); annot.SetFlag(PdfAnnotation.PRINT); @@ -974,7 +974,7 @@ public virtual void PdfA4AnnotationsWrongPageOutputIntentTest() { String outPdf = DESTINATION_FOLDER + "pdfA4AnnotationsWrongPageOutputIntent.pdf"; String cmpPdf = CMP_FOLDER + "cmp_pdfA4AnnotationsWrongPageOutputIntent.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, null); + PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformance.PDF_A_4, null); PdfPage page = pdfDoc.AddNewPage(); page.AddOutputIntent(new PdfOutputIntent("Custom", "", "http://www.color.org", "cmyk", FileUtil.GetInputStreamForFile (SOURCE_FOLDER + "USWebUncoated.icc"))); @@ -999,7 +999,7 @@ public virtual void PdfA4AnnotationsCorrectPageOutputIntentTest() { String outPdf = DESTINATION_FOLDER + "pdfA4AnnotationsCorrectPageOutputIntent.pdf"; String cmpPdf = CMP_FOLDER + "cmp_pdfA4AnnotationsCorrectPageOutputIntent.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, null); + PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformance.PDF_A_4, null); PdfPage page = pdfDoc.AddNewPage(); page.AddOutputIntent(new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", FileUtil .GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"))); @@ -1023,7 +1023,7 @@ public virtual void DestOutputIntentProfileNotAllowedTest() { String outPdf = DESTINATION_FOLDER + "pdfA4DestOutputIntentProfileNotAllowed.pdf"; String isoFilePath = SOURCE_FOLDER + "ISOcoated_v2_300_bas.icc"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, null); + PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformance.PDF_A_4, null); byte[] bytes = File.ReadAllBytes(System.IO.Path.Combine(isoFilePath)); byte[] manipulatedBytes = iText.Commons.Utils.JavaUtil.GetStringForBytes(bytes, System.Text.Encoding.ASCII ).Replace("prtr", "not_def").GetBytes(System.Text.Encoding.ASCII); @@ -1041,7 +1041,7 @@ public virtual void DestOutputIntentProfileNotAllowedInPageTest() { String outPdf = DESTINATION_FOLDER + "pdfA4DestOutputIntentProfileNotAllowedInPage.pdf"; String isoFilePath = SOURCE_FOLDER + "ISOcoated_v2_300_bas.icc"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, null); + PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformance.PDF_A_4, null); PdfPage page = pdfDoc.AddNewPage(); byte[] bytes = File.ReadAllBytes(System.IO.Path.Combine(isoFilePath)); byte[] manipulatedBytes = iText.Commons.Utils.JavaUtil.GetStringForBytes(bytes, System.Text.Encoding.ASCII @@ -1060,7 +1060,7 @@ public virtual void DestOutputIntentColorSpaceNotAllowedTest() { String outPdf = DESTINATION_FOLDER + "pdfA4DestOutputIntentProfileNotAllowed.pdf"; String isoFilePath = SOURCE_FOLDER + "ISOcoated_v2_300_bas.icc"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, null); + PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformance.PDF_A_4, null); byte[] bytes = File.ReadAllBytes(System.IO.Path.Combine(isoFilePath)); byte[] manipulatedBytes = iText.Commons.Utils.JavaUtil.GetStringForBytes(bytes, System.Text.Encoding.ASCII ).Replace("CMYK", "not_def").GetBytes(System.Text.Encoding.ASCII); @@ -1078,7 +1078,7 @@ public virtual void DestOutputIntentColorSpaceNotAllowedInPageTest() { String outPdf = DESTINATION_FOLDER + "pdfA4DestOutputIntentProfileNotAllowedInPage.pdf"; String isoFilePath = SOURCE_FOLDER + "ISOcoated_v2_300_bas.icc"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, null); + PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformance.PDF_A_4, null); PdfPage page = pdfDoc.AddNewPage(); byte[] bytes = File.ReadAllBytes(System.IO.Path.Combine(isoFilePath)); byte[] manipulatedBytes = iText.Commons.Utils.JavaUtil.GetStringForBytes(bytes, System.Text.Encoding.ASCII @@ -1095,9 +1095,9 @@ public virtual void DestOutputIntentColorSpaceNotAllowedInPageTest() { [NUnit.Framework.Test] public virtual void DestOutputIntentRefNotAllowedTest() { String outPdf = DESTINATION_FOLDER + "PdfWithOutputIntentProfileRef.pdf"; - PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_4; + PdfAConformance conformance = PdfAConformance.PDF_A_4; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - PdfADocument pdfADocument = new PdfADocument(writer, conformanceLevel, new PdfOutputIntent("Custom", "", "http://www.color.org" + PdfADocument pdfADocument = new PdfADocument(writer, conformance, new PdfOutputIntent("Custom", "", "http://www.color.org" , "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm")) ); PdfPage page = pdfADocument.AddNewPage(); @@ -1118,7 +1118,7 @@ private void TestWithColourant(PdfName color) { Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - using (PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, outputIntent)) { + using (PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, outputIntent)) { doc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(doc.GetLastPage()); PdfDictionary colourantHalftone = new PdfDictionary(); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA4MiscCheckTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA4MiscCheckTest.cs index 23ce39c9c4..880facc197 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA4MiscCheckTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA4MiscCheckTest.cs @@ -49,7 +49,7 @@ public virtual void PdfA4CheckThatAsKeyIsAllowedTest() { String outPdf = DESTINATION_FOLDER + "pdfA4CheckThatAsKeyIsAllowedTest.pdf"; String cmpPdf = CMP_FOLDER + "cmp_pdfA4CheckThatAsKeyIsAllowedTest.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - using (PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, CreateOutputIntent())) { + using (PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, CreateOutputIntent())) { doc.AddNewPage(); PdfArray configs = new PdfArray(); PdfDictionary config = new PdfDictionary(); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA4TransparencyCheckTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA4TransparencyCheckTest.cs index 7f31be211b..36c821d295 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA4TransparencyCheckTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfA4TransparencyCheckTest.cs @@ -61,7 +61,7 @@ public virtual void TextTransparencyPageOutputIntentTest() { String outPdf = DESTINATION_FOLDER + "textTransparencyPageOutputIntent.pdf"; String cmpPdf = CMP_FOLDER + "cmp_textTransparencyPageOutputIntent.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - PdfDocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, null); + PdfDocument pdfDocument = new PdfADocument(writer, PdfAConformance.PDF_A_4, null); PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "FreeSans.ttf", "Identity-H", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); PdfPage page1 = pdfDocument.AddNewPage(); @@ -84,7 +84,7 @@ public virtual void TextTransparencyPageOutputIntentTest() { public virtual void TextTransparencyPageWrongOutputIntentTest() { String outPdf = DESTINATION_FOLDER + "textTransparencyPageWrongOutputIntent.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - PdfDocument pdfDoc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, null); + PdfDocument pdfDoc = new PdfADocument(writer, PdfAConformance.PDF_A_4, null); PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "FreeSans.ttf", "Identity-H", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); PdfOutputIntent outputIntent = CreateOutputIntent(); @@ -108,7 +108,7 @@ public virtual void TransparentTextWithGroupColorSpaceTest() { String outPdf = DESTINATION_FOLDER + "transparencyAndCS.pdf"; String cmpPdf = CMP_FOLDER + "cmp_transparencyAndCS.pdf"; PdfDocument pdfDocument = new PdfADocument(new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion - .PDF_2_0)), PdfAConformanceLevel.PDF_A_4, null); + .PDF_2_0)), PdfAConformance.PDF_A_4, null); PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "FreeSans.ttf", "Identity-H", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); Stream streamGray = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "BlackWhite.icc"); @@ -139,7 +139,7 @@ public virtual void TransparentTextWithGroupColorSpaceTest() { public virtual void BlendModeTest() { PdfWriter writer = new PdfWriter(new MemoryStream(), new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0 )); - using (PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, CreateOutputIntent())) { + using (PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, CreateOutputIntent())) { PdfCanvas canvas = new PdfCanvas(doc.AddNewPage()); canvas.SaveState(); canvas.SetExtGState(new PdfExtGState().SetBlendMode(PdfName.Darken)); @@ -150,7 +150,7 @@ public virtual void BlendModeTest() { // Verapdf doesn't assert on PdfName.Compatible apparently but let's be strict here Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => canvas.SetExtGState(new PdfExtGState().SetBlendMode(PdfName.Compatible))); - NUnit.Framework.Assert.AreEqual(PdfAConformanceException.ONLY_STANDARD_BLEND_MODES_SHALL_BE_USED_FOR_THE_VALUE_OF_THE_BM_KEY_IN_AN_EXTENDED_GRAPHIC_STATE_DICTIONARY + NUnit.Framework.Assert.AreEqual(PdfaExceptionMessageConstant.ONLY_STANDARD_BLEND_MODES_SHALL_BE_USED_FOR_THE_VALUE_OF_THE_BM_KEY_IN_AN_EXTENDED_GRAPHIC_STATE_DICTIONARY , e.Message); } } @@ -159,7 +159,7 @@ public virtual void BlendModeTest() { public virtual void BlendModeAnnotationTest() { PdfWriter writer = new PdfWriter(new MemoryStream(), new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0 )); - PdfDocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, null); + PdfDocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, null); PdfFormXObject formXObject = new PdfFormXObject(new Rectangle(100f, 100f)); iText.Layout.Canvas canvas = new iText.Layout.Canvas(formXObject, doc); canvas.GetPdfCanvas().Circle(50f, 50f, 40f); @@ -180,7 +180,7 @@ public virtual void BlendModeAnnotationOutputIntentTest() { String outPdf = DESTINATION_FOLDER + "blendModeAnnotationOutputIntent.pdf"; String cmpPdf = CMP_FOLDER + "cmp_blendModeAnnotationOutputIntent.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - using (PdfDocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, null)) { + using (PdfDocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, null)) { PdfFormXObject formXObject = new PdfFormXObject(new Rectangle(100f, 100f)); iText.Layout.Canvas canvas = new iText.Layout.Canvas(formXObject, doc); canvas.GetPdfCanvas().Circle(50f, 50f, 40f); @@ -200,7 +200,7 @@ public virtual void BlendModeAnnotationOutputIntentTest() { public virtual void ForbiddenBlendModeAnnotationTest() { PdfWriter writer = new PdfWriter(new ByteArrayOutputStream(), new WriterProperties().SetPdfVersion(PdfVersion .PDF_2_0)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, CreateOutputIntent()); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, CreateOutputIntent()); PdfFormXObject formXObject = new PdfFormXObject(new Rectangle(0f, 0f)); PdfAnnotation annotation = new PdfPopupAnnotation(new Rectangle(0f, 0f)); annotation.SetNormalAppearance(formXObject.GetPdfObject()); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAAgnosticPdfDocumentUnitTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAAgnosticPdfDocumentUnitTest.cs deleted file mode 100644 index 4bf7a8bf73..0000000000 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAAgnosticPdfDocumentUnitTest.cs +++ /dev/null @@ -1,122 +0,0 @@ -/* -This file is part of the iText (R) project. -Copyright (c) 1998-2024 Apryse Group NV -Authors: Apryse Software. - -This program is offered under a commercial and under the AGPL license. -For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. - -AGPL licensing: -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . -*/ -using System; -using iText.IO.Source; -using iText.Kernel.Pdf; -using iText.Kernel.XMP; -using iText.Pdfa.Logs; -using iText.Test; -using iText.Test.Attributes; - -namespace iText.Pdfa { - [NUnit.Framework.Category("UnitTest")] - public class PdfAAgnosticPdfDocumentUnitTest : ExtendedITextTest { - public static readonly String sourceFolder = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext - .CurrentContext.TestDirectory) + "/resources/itext/pdfa/"; - - public static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory - + "/test/itext/pdfa/AgnosticPdfDocumentUnitTest/"; - - [NUnit.Framework.OneTimeSetUp] - public static void BeforeClass() { - CreateOrClearDestinationFolder(destinationFolder); - } - - [NUnit.Framework.Test] - public virtual void LoadPdfDocumentTest() { - PdfAAgnosticPdfDocumentUnitTest.TestAgnosticPdfDocument pdfDoc = new PdfAAgnosticPdfDocumentUnitTest.TestAgnosticPdfDocument - (this, new PdfReader(sourceFolder + "pdfs/simpleDoc.pdf"), new PdfWriter(new ByteArrayOutputStream())); - pdfDoc.FlushObjectPublic(pdfDoc.GetPage(1).GetPdfObject(), true); - NUnit.Framework.Assert.IsTrue(pdfDoc.GetPage(1).GetPdfObject().IsFlushed()); - pdfDoc.CheckIsoConformancePublic(); - // Does nothing for PdfDocument - NUnit.Framework.Assert.IsFalse(pdfDoc.GetPageFactoryPublic() is PdfAPageFactory); - NUnit.Framework.Assert.IsNull(pdfDoc.GetConformanceLevel()); - pdfDoc.UpdateXmpMetadataPublic(); - XMPMeta xmpMeta = XMPMetaFactory.ParseFromBuffer(pdfDoc.GetXmpMetadata(true)); - NUnit.Framework.Assert.IsNull(xmpMeta.GetProperty(XMPConst.NS_PDFA_ID, XMPConst.PART)); - NUnit.Framework.Assert.IsNull(xmpMeta.GetProperty(XMPConst.NS_PDFA_ID, XMPConst.CONFORMANCE)); - pdfDoc.Close(); - } - - [NUnit.Framework.Test] - public virtual void GetDefaultFont() { - PdfAAgnosticPdfDocumentUnitTest.TestAgnosticPdfDocument pdfDoc = new PdfAAgnosticPdfDocumentUnitTest.TestAgnosticPdfDocument - (this, new PdfReader(sourceFolder + "pdfs/simpleDoc.pdf"), new PdfWriter(new ByteArrayOutputStream())); - NUnit.Framework.Assert.IsNotNull(pdfDoc.GetDefaultFont()); - } - - [NUnit.Framework.Test] - [LogMessage(PdfALogMessageConstant.PDFA_OBJECT_FLUSHING_WAS_NOT_PERFORMED)] - public virtual void LoadPdfADocumentTest() { - PdfAAgnosticPdfDocumentUnitTest.TestAgnosticPdfDocument pdfADoc = new PdfAAgnosticPdfDocumentUnitTest.TestAgnosticPdfDocument - (this, new PdfReader(sourceFolder + "pdfs/pdfa.pdf"), new PdfWriter(new ByteArrayOutputStream()), new - StampingProperties()); - pdfADoc.FlushObjectPublic(pdfADoc.GetPage(1).GetPdfObject(), true); - NUnit.Framework.Assert.IsFalse(pdfADoc.GetPage(1).GetPdfObject().IsFlushed()); - pdfADoc.CheckIsoConformancePublic(); - NUnit.Framework.Assert.AreEqual(PdfAConformanceLevel.PDF_A_2B, pdfADoc.GetConformanceLevel()); - NUnit.Framework.Assert.IsTrue(pdfADoc.GetPageFactoryPublic() is PdfAPageFactory); - pdfADoc.UpdateXmpMetadataPublic(); - XMPMeta xmpMeta = XMPMetaFactory.ParseFromBuffer(pdfADoc.GetXmpMetadata(true)); - NUnit.Framework.Assert.IsNotNull(xmpMeta.GetProperty(XMPConst.NS_PDFA_ID, XMPConst.PART)); - NUnit.Framework.Assert.IsNotNull(xmpMeta.GetProperty(XMPConst.NS_PDFA_ID, XMPConst.CONFORMANCE)); - // Extra PdfA error message check - pdfADoc.FlushObjectPublic(pdfADoc.GetCatalog().GetPdfObject(), true); - NUnit.Framework.Assert.IsFalse(pdfADoc.GetCatalog().GetPdfObject().IsFlushed()); - pdfADoc.Close(); - } - - private class TestAgnosticPdfDocument : PdfAAgnosticPdfDocument { - public TestAgnosticPdfDocument(PdfAAgnosticPdfDocumentUnitTest _enclosing, PdfReader reader, PdfWriter writer - ) - : base(reader, writer, new StampingProperties()) { - this._enclosing = _enclosing; - } - - public TestAgnosticPdfDocument(PdfAAgnosticPdfDocumentUnitTest _enclosing, PdfReader reader, PdfWriter writer - , StampingProperties properties) - : base(reader, writer, properties) { - this._enclosing = _enclosing; - } - - public virtual void CheckIsoConformancePublic() { - base.CheckIsoConformance(); - } - - public virtual IPdfPageFactory GetPageFactoryPublic() { - return base.GetPageFactory(); - } - - public virtual void UpdateXmpMetadataPublic() { - base.UpdateXmpMetadata(); - } - - public virtual void FlushObjectPublic(PdfObject pdfObject, bool canBeInObjStm) { - base.FlushObject(pdfObject, canBeInObjStm); - } - - private readonly PdfAAgnosticPdfDocumentUnitTest _enclosing; - } - } -} diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAAppendModeTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAAppendModeTest.cs index f30c80fdca..8626cf3da2 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAAppendModeTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAAppendModeTest.cs @@ -72,8 +72,8 @@ public virtual void AddPageInAppendModeTest() { private static void CreateInputPdfADocument(String docName) { PdfWriter writer = new PdfWriter(docName); - PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1A, new PdfOutputIntent("Custom" - , "", "http://www.color.org", "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm" + PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformance.PDF_A_1A, new PdfOutputIntent("Custom", "", + "http://www.color.org", "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm" ))); pdfDoc.SetTagged(); pdfDoc.GetCatalog().SetLang(new PdfString("en-US")); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfABarcodeTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfABarcodeTest.cs index 7d45feb21c..987742fc9a 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfABarcodeTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfABarcodeTest.cs @@ -171,8 +171,8 @@ private void FillBarcode1D(Barcode1D barcode1D, String code) { private Document CreatePdfATaggedDocument(String outPdf) { PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfDocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom" - , "", "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfDocument pdfDocument = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", + "", "http://www.color.org", "sRGB IEC61966-2.1", @is)); Document doc = new Document(pdfDocument); pdfDocument.SetTagged(); return doc; diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfACheckfieldTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfACheckfieldTest.cs index abfba07a91..5179d19d90 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfACheckfieldTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfACheckfieldTest.cs @@ -57,15 +57,15 @@ public virtual void PdfA1aCheckFieldOffAppearanceTest() { String diff = "diff_" + name + "_"; PdfWriter writer = new PdfWriter(outPath); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1A, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1A, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.SetTagged(); doc.GetCatalog().SetLang(new PdfString("en-US")); doc.AddNewPage(); PdfAcroForm form = PdfFormCreator.GetAcroForm(doc, true); PdfFormField chk = new CheckBoxFormFieldBuilder(doc, "name").SetWidgetRectangle(new Rectangle(100, 500, 50 - , 50)).SetCheckType(CheckBoxType.CHECK).SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_1A).CreateCheckBox - ().SetValue("Off"); + , 50)).SetCheckType(CheckBoxType.CHECK).SetConformance(PdfConformance.PDF_A_1A).CreateCheckBox().SetValue + ("Off"); chk.GetFirstFormAnnotation().SetBorderColor(ColorConstants.BLACK); chk.GetFirstFormAnnotation().SetBorderWidth(1); form.AddField(chk); @@ -82,15 +82,15 @@ public virtual void PdfA1aCheckFieldOnAppearanceTest() { String diff = "diff_" + name + "_"; PdfWriter writer = new PdfWriter(outPath); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1A, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1A, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.SetTagged(); doc.GetCatalog().SetLang(new PdfString("en-US")); doc.AddNewPage(); PdfAcroForm form = PdfFormCreator.GetAcroForm(doc, true); PdfFormField chk = new CheckBoxFormFieldBuilder(doc, "name").SetWidgetRectangle(new Rectangle(100, 500, 50 - , 50)).SetCheckType(CheckBoxType.CHECK).SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_1A).CreateCheckBox - ().SetValue("On"); + , 50)).SetCheckType(CheckBoxType.CHECK).SetConformance(PdfConformance.PDF_A_1A).CreateCheckBox().SetValue + ("On"); chk.GetFirstFormAnnotation().SetBorderColor(ColorConstants.BLACK); chk.GetFirstFormAnnotation().SetBorderWidth(1); form.AddField(chk); @@ -107,13 +107,13 @@ public virtual void PdfA1bCheckFieldOffAppearanceTest() { String diff = "diff_" + name + "_"; PdfWriter writer = new PdfWriter(outPath); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfAcroForm form = PdfFormCreator.GetAcroForm(doc, true); PdfFormField chk = new CheckBoxFormFieldBuilder(doc, "name").SetWidgetRectangle(new Rectangle(100, 500, 50 - , 50)).SetCheckType(CheckBoxType.CHECK).SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_1B).CreateCheckBox - ().SetValue("Off"); + , 50)).SetCheckType(CheckBoxType.CHECK).SetConformance(PdfConformance.PDF_A_1B).CreateCheckBox().SetValue + ("Off"); chk.GetFirstFormAnnotation().SetBorderColor(ColorConstants.BLACK); chk.GetFirstFormAnnotation().SetBorderWidth(1); form.AddField(chk); @@ -130,13 +130,13 @@ public virtual void PdfA1bCheckFieldOnAppearanceTest() { String diff = "diff_" + name + "_"; PdfWriter writer = new PdfWriter(outPath); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfAcroForm form = PdfFormCreator.GetAcroForm(doc, true); PdfFormField chk = new CheckBoxFormFieldBuilder(doc, "name").SetWidgetRectangle(new Rectangle(100, 500, 50 - , 50)).SetCheckType(CheckBoxType.CHECK).SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_1B).CreateCheckBox - ().SetValue("On"); + , 50)).SetCheckType(CheckBoxType.CHECK).SetConformance(PdfConformance.PDF_A_1B).CreateCheckBox().SetValue + ("On"); chk.GetFirstFormAnnotation().SetBorderColor(ColorConstants.BLACK); chk.GetFirstFormAnnotation().SetBorderWidth(1); form.AddField(chk); @@ -153,15 +153,15 @@ public virtual void PdfA2aCheckFieldOffAppearanceTest() { String diff = "diff_" + name + "_"; PdfWriter writer = new PdfWriter(outPath); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2A, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2A, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.SetTagged(); doc.GetCatalog().SetLang(new PdfString("en-US")); doc.AddNewPage(); PdfAcroForm form = PdfFormCreator.GetAcroForm(doc, true); PdfFormField chk = new CheckBoxFormFieldBuilder(doc, "name").SetWidgetRectangle(new Rectangle(100, 500, 50 - , 50)).SetCheckType(CheckBoxType.CHECK).SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_2A).CreateCheckBox - ().SetValue("Off"); + , 50)).SetCheckType(CheckBoxType.CHECK).SetConformance(PdfConformance.PDF_A_2A).CreateCheckBox().SetValue + ("Off"); chk.GetFirstFormAnnotation().SetBorderColor(ColorConstants.BLACK); chk.GetFirstFormAnnotation().SetBorderWidth(1); form.AddField(chk); @@ -178,15 +178,15 @@ public virtual void PdfA2aCheckFieldOnAppearanceTest() { String diff = "diff_" + name + "_"; PdfWriter writer = new PdfWriter(outPath); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2A, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2A, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.SetTagged(); doc.GetCatalog().SetLang(new PdfString("en-US")); doc.AddNewPage(); PdfAcroForm form = PdfFormCreator.GetAcroForm(doc, true); PdfFormField chk = new CheckBoxFormFieldBuilder(doc, "name").SetWidgetRectangle(new Rectangle(100, 500, 50 - , 50)).SetCheckType(CheckBoxType.CHECK).SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_2A).CreateCheckBox - ().SetValue("On"); + , 50)).SetCheckType(CheckBoxType.CHECK).SetConformance(PdfConformance.PDF_A_2A).CreateCheckBox().SetValue + ("On"); chk.GetFirstFormAnnotation().SetBorderColor(ColorConstants.BLACK); chk.GetFirstFormAnnotation().SetBorderWidth(1); form.AddField(chk); @@ -203,13 +203,13 @@ public virtual void PdfA2bCheckFieldOffAppearanceTest() { String diff = "diff_" + name + "_"; PdfWriter writer = new PdfWriter(outPath); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfAcroForm form = PdfFormCreator.GetAcroForm(doc, true); PdfFormField chk = new CheckBoxFormFieldBuilder(doc, "name").SetWidgetRectangle(new Rectangle(100, 500, 50 - , 50)).SetCheckType(CheckBoxType.CHECK).SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_2B).CreateCheckBox - ().SetValue("Off"); + , 50)).SetCheckType(CheckBoxType.CHECK).SetConformance(PdfConformance.PDF_A_2B).CreateCheckBox().SetValue + ("Off"); chk.GetFirstFormAnnotation().SetBorderColor(ColorConstants.BLACK); chk.GetFirstFormAnnotation().SetBorderWidth(1); form.AddField(chk); @@ -226,13 +226,13 @@ public virtual void PdfA2bCheckFieldOnAppearanceTest() { String diff = "diff_" + name + "_"; PdfWriter writer = new PdfWriter(outPath); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfAcroForm form = PdfFormCreator.GetAcroForm(doc, true); PdfFormField chk = new CheckBoxFormFieldBuilder(doc, "name").SetWidgetRectangle(new Rectangle(100, 500, 50 - , 50)).SetCheckType(CheckBoxType.CHECK).SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_2B).CreateCheckBox - ().SetValue("On"); + , 50)).SetCheckType(CheckBoxType.CHECK).SetConformance(PdfConformance.PDF_A_2B).CreateCheckBox().SetValue + ("On"); chk.GetFirstFormAnnotation().SetBorderColor(ColorConstants.BLACK); chk.GetFirstFormAnnotation().SetBorderWidth(1); form.AddField(chk); @@ -249,13 +249,13 @@ public virtual void PdfA2uCheckFieldOffAppearanceTest() { String diff = "diff_" + name + "_"; PdfWriter writer = new PdfWriter(outPath); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2U, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2U, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfAcroForm form = PdfFormCreator.GetAcroForm(doc, true); PdfFormField chk = new CheckBoxFormFieldBuilder(doc, "name").SetWidgetRectangle(new Rectangle(100, 500, 50 - , 50)).SetCheckType(CheckBoxType.CHECK).SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_2U).CreateCheckBox - ().SetValue("Off"); + , 50)).SetCheckType(CheckBoxType.CHECK).SetConformance(PdfConformance.PDF_A_2U).CreateCheckBox().SetValue + ("Off"); chk.GetFirstFormAnnotation().SetBorderColor(ColorConstants.BLACK); chk.GetFirstFormAnnotation().SetBorderWidth(1); form.AddField(chk); @@ -272,13 +272,13 @@ public virtual void PdfA2uCheckFieldOnAppearanceTest() { String diff = "diff_" + name + "_"; PdfWriter writer = new PdfWriter(outPath); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2U, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2U, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfAcroForm form = PdfFormCreator.GetAcroForm(doc, true); PdfFormField chk = new CheckBoxFormFieldBuilder(doc, "name").SetWidgetRectangle(new Rectangle(100, 500, 50 - , 50)).SetCheckType(CheckBoxType.CHECK).SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_2U).CreateCheckBox - ().SetValue("On"); + , 50)).SetCheckType(CheckBoxType.CHECK).SetConformance(PdfConformance.PDF_A_2U).CreateCheckBox().SetValue + ("On"); chk.GetFirstFormAnnotation().SetBorderColor(ColorConstants.BLACK); chk.GetFirstFormAnnotation().SetBorderWidth(1); form.AddField(chk); @@ -295,15 +295,15 @@ public virtual void PdfA3aCheckFieldOffAppearanceTest() { String diff = "diff_" + name + "_"; PdfWriter writer = new PdfWriter(outPath); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_3A, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_3A, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.SetTagged(); doc.GetCatalog().SetLang(new PdfString("en-US")); doc.AddNewPage(); PdfAcroForm form = PdfFormCreator.GetAcroForm(doc, true); PdfFormField chk = new CheckBoxFormFieldBuilder(doc, "name").SetWidgetRectangle(new Rectangle(100, 500, 50 - , 50)).SetCheckType(CheckBoxType.CHECK).SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_3A).CreateCheckBox - ().SetValue("Off"); + , 50)).SetCheckType(CheckBoxType.CHECK).SetConformance(PdfConformance.PDF_A_3A).CreateCheckBox().SetValue + ("Off"); chk.GetFirstFormAnnotation().SetBorderColor(ColorConstants.BLACK); chk.GetFirstFormAnnotation().SetBorderWidth(1); form.AddField(chk); @@ -320,15 +320,15 @@ public virtual void PdfA3aCheckFieldOnAppearanceTest() { String diff = "diff_" + name + "_"; PdfWriter writer = new PdfWriter(outPath); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_3A, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_3A, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.SetTagged(); doc.GetCatalog().SetLang(new PdfString("en-US")); doc.AddNewPage(); PdfAcroForm form = PdfFormCreator.GetAcroForm(doc, true); PdfFormField chk = new CheckBoxFormFieldBuilder(doc, "name").SetWidgetRectangle(new Rectangle(100, 500, 50 - , 50)).SetCheckType(CheckBoxType.CHECK).SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_3A).CreateCheckBox - ().SetValue("On"); + , 50)).SetCheckType(CheckBoxType.CHECK).SetConformance(PdfConformance.PDF_A_3A).CreateCheckBox().SetValue + ("On"); chk.GetFirstFormAnnotation().SetBorderColor(ColorConstants.BLACK); chk.GetFirstFormAnnotation().SetBorderWidth(1); form.AddField(chk); @@ -345,13 +345,13 @@ public virtual void PdfA3bCheckFieldOffAppearanceTest() { String diff = "diff_" + name + "_"; PdfWriter writer = new PdfWriter(outPath); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_3B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_3B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfAcroForm form = PdfFormCreator.GetAcroForm(doc, true); PdfFormField chk = new CheckBoxFormFieldBuilder(doc, "name").SetWidgetRectangle(new Rectangle(100, 500, 50 - , 50)).SetCheckType(CheckBoxType.CHECK).SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_3B).CreateCheckBox - ().SetValue("Off"); + , 50)).SetCheckType(CheckBoxType.CHECK).SetConformance(PdfConformance.PDF_A_3B).CreateCheckBox().SetValue + ("Off"); chk.GetFirstFormAnnotation().SetBorderColor(ColorConstants.BLACK); chk.GetFirstFormAnnotation().SetBorderWidth(1); form.AddField(chk); @@ -368,13 +368,13 @@ public virtual void PdfA3bCheckFieldOnAppearanceTest() { String diff = "diff_" + name + "_"; PdfWriter writer = new PdfWriter(outPath); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_3B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_3B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfAcroForm form = PdfFormCreator.GetAcroForm(doc, true); PdfFormField chk = new CheckBoxFormFieldBuilder(doc, "name").SetWidgetRectangle(new Rectangle(100, 500, 50 - , 50)).SetCheckType(CheckBoxType.CHECK).SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_3B).CreateCheckBox - ().SetValue("On"); + , 50)).SetCheckType(CheckBoxType.CHECK).SetConformance(PdfConformance.PDF_A_3B).CreateCheckBox().SetValue + ("On"); chk.GetFirstFormAnnotation().SetBorderColor(ColorConstants.BLACK); chk.GetFirstFormAnnotation().SetBorderWidth(1); form.AddField(chk); @@ -391,13 +391,13 @@ public virtual void PdfA3uCheckFieldOffAppearanceTest() { String diff = "diff_" + name + "_"; PdfWriter writer = new PdfWriter(outPath); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_3U, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_3U, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfAcroForm form = PdfFormCreator.GetAcroForm(doc, true); PdfFormField chk = new CheckBoxFormFieldBuilder(doc, "name").SetWidgetRectangle(new Rectangle(100, 500, 50 - , 50)).SetCheckType(CheckBoxType.CHECK).SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_3U).CreateCheckBox - ().SetValue("Off"); + , 50)).SetCheckType(CheckBoxType.CHECK).SetConformance(PdfConformance.PDF_A_3U).CreateCheckBox().SetValue + ("Off"); chk.GetFirstFormAnnotation().SetBorderColor(ColorConstants.BLACK); chk.GetFirstFormAnnotation().SetBorderWidth(1); form.AddField(chk); @@ -414,13 +414,13 @@ public virtual void PdfA3uCheckFieldOnAppearanceTest() { String diff = "diff_" + name + "_"; PdfWriter writer = new PdfWriter(outPath); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_3U, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_3U, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); doc.AddNewPage(); PdfAcroForm form = PdfFormCreator.GetAcroForm(doc, true); PdfFormField chk = new CheckBoxFormFieldBuilder(doc, "name").SetWidgetRectangle(new Rectangle(100, 500, 50 - , 50)).SetCheckType(CheckBoxType.CHECK).SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_3U).CreateCheckBox - ().SetValue("On"); + , 50)).SetCheckType(CheckBoxType.CHECK).SetConformance(PdfConformance.PDF_A_3U).CreateCheckBox().SetValue + ("On"); chk.GetFirstFormAnnotation().SetBorderColor(ColorConstants.BLACK); chk.GetFirstFormAnnotation().SetBorderWidth(1); form.AddField(chk); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfADocumentTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfADocumentTest.cs index ba85e6d1c6..f3b447bcf8 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfADocumentTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfADocumentTest.cs @@ -24,8 +24,11 @@ You should have received a copy of the GNU Affero General Public License using System.IO; using iText.Commons.Utils; using iText.Kernel.Pdf; +using iText.Kernel.Validation.Context; using iText.Pdfa.Exceptions; +using iText.Pdfa.Logs; using iText.Test; +using iText.Test.Attributes; namespace iText.Pdfa { [NUnit.Framework.Category("UnitTest")] @@ -38,9 +41,9 @@ public virtual void CheckCadesSignatureTypeIsoConformance() { PdfWriter writer = new PdfWriter(new MemoryStream(), new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0 )); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfADocument document = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom" - , "", "http://www.color.org", "sRGB IEC61966-2.1", @is)); - document.CheckIsoConformance(true, IsoKey.SIGNATURE_TYPE, null, null); + PdfADocument document = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "" + , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + document.CheckIsoConformance(new SignTypeValidationContext(true)); } [NUnit.Framework.Test] @@ -48,12 +51,36 @@ public virtual void CheckCMSSignatureTypeIsoConformance() { PdfWriter writer = new PdfWriter(new MemoryStream(), new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0 )); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfADocument document = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom" - , "", "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument document = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "" + , "http://www.color.org", "sRGB IEC61966-2.1", @is)); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => document.CheckIsoConformance - (false, IsoKey.SIGNATURE_TYPE, null, null)); + (new SignTypeValidationContext(false))); NUnit.Framework.Assert.AreEqual(PdfaExceptionMessageConstant.SIGNATURE_SHALL_CONFORM_TO_ONE_OF_THE_PADES_PROFILE , e.Message); } + + [NUnit.Framework.Test] + public virtual void OpeningNonADocumentWithPdfADocumentTest() { + MemoryStream os = new MemoryStream(); + using (PdfDocument pdfDocument = new PdfDocument(new PdfWriter(os))) { + pdfDocument.AddNewPage(); + } + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => new PdfADocument(new PdfReader + (new MemoryStream(os.ToArray())), new PdfWriter(new MemoryStream()))); + NUnit.Framework.Assert.AreEqual(PdfaExceptionMessageConstant.DOCUMENT_TO_READ_FROM_SHALL_BE_A_PDFA_CONFORMANT_FILE_WITH_VALID_XMP_METADATA + , e.Message); + } + + [NUnit.Framework.Test] + [LogMessage(PdfALogMessageConstant.WRITER_PROPERTIES_PDF_VERSION_WAS_OVERRIDDEN, LogLevel = LogLevelConstants + .WARN)] + public virtual void SettingWrongPdfVersionTest() { + Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); + PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" + , @is); + PdfADocument doc = new PdfADocument(new PdfWriter(new MemoryStream(), new WriterProperties().SetPdfVersion + (PdfVersion.PDF_1_4)), PdfAConformance.PDF_A_4, outputIntent); + doc.Close(); + } } } diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAFlushingTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAFlushingTest.cs index b15e6bfbde..fe5b5b02d4 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAFlushingTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAFlushingTest.cs @@ -59,8 +59,8 @@ public virtual void FlushingTest01() { String cmpPdf = sourceFolder + "cmp/PdfAFlushingTest/cmp_pdfA1b_flushingTest01.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfCanvas canvas = new PdfCanvas(doc.AddNewPage()); PdfImageXObject imageXObject = new PdfImageXObject(ImageDataFactory.Create(sourceFolder + "Desert.jpg")); imageXObject.MakeIndirect(doc); @@ -80,8 +80,8 @@ public virtual void FlushingTest02() { String cmpPdf = sourceFolder + "cmp/PdfAFlushingTest/cmp_pdfA2b_flushingTest02.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfCanvas canvas = new PdfCanvas(doc.AddNewPage()); PdfImageXObject imageXObject = new PdfImageXObject(ImageDataFactory.Create(sourceFolder + "Desert.jpg")); imageXObject.MakeIndirect(doc); @@ -101,8 +101,8 @@ public virtual void FlushingTest03() { String cmpPdf = sourceFolder + "cmp/PdfAFlushingTest/cmp_pdfA3b_flushingTest03.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_3B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_3B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfCanvas canvas = new PdfCanvas(doc.AddNewPage()); PdfImageXObject imageXObject = new PdfImageXObject(ImageDataFactory.Create(sourceFolder + "Desert.jpg")); canvas.AddXObjectFittedIntoRectangle(imageXObject, new Rectangle(30, 300, 300, 300)); @@ -124,8 +124,8 @@ public virtual void TryToFlushFontTest() { String cmpPdf = sourceFolder + "cmp_tryToFlushFontTest.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument pdfDoc = (PdfADocument)new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent - ("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", @is)).SetTagged(); + PdfADocument pdfDoc = (PdfADocument)new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent( + "Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", @is)).SetTagged(); PdfFont font = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", "WinAnsi", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); font.MakeIndirect(pdfDoc); @@ -152,7 +152,7 @@ public virtual void AddUnusedStreamObjectsTest() { String cmpPdf = sourceFolder + "cmp/PdfAFlushingTest/cmp_pdfA1b_docWithUnusedObjects_3.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); - PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom" + PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom" , "", "http://www.color.org", "sRGB IEC61966-2.1", @is)); pdfDocument.AddNewPage(); PdfDictionary unusedDictionary = new PdfDictionary(); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAFontTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAFontTest.cs index 014746294e..e35270e16a 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAFontTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAFontTest.cs @@ -61,8 +61,8 @@ public virtual void FontCheckPdfA1_01() { String cmpPdf = SOURCE_FOLDER + "cmp/PdfAFontTest/cmp_pdfA1b_fontCheckPdfA1_01.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfDocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfDocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "FreeSans.ttf", "WinAnsi", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); @@ -77,8 +77,8 @@ public virtual void FontCheckPdfA1_01() { public virtual void FontCheckPdfA1_02() { PdfWriter writer = new PdfWriter(new MemoryStream()); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfDocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfDocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "FreeSans.ttf", PdfEncodings.WINANSI, PdfFontFactory.EmbeddingStrategy .FORCE_NOT_EMBEDDED); @@ -96,8 +96,8 @@ public virtual void FontCheckPdfA1_03() { String cmpPdf = SOURCE_FOLDER + "cmp/PdfAFontTest/cmp_pdfA1b_fontCheckPdfA1_03.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfDocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfDocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); // Identity-H must be embedded PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "FreeSans.ttf", "Identity-H", PdfFontFactory.EmbeddingStrategy @@ -113,8 +113,8 @@ public virtual void FontCheckPdfA1_03() { public virtual void FontCheckPdfA1_04() { PdfWriter writer = new PdfWriter(new MemoryStream()); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfDocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfDocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); PdfFont font = PdfFontFactory.CreateFont("Helvetica", "WinAnsi", PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED ); @@ -132,8 +132,8 @@ public virtual void FontCheckPdfA1_05() { String cmpPdf = SOURCE_FOLDER + "cmp/PdfAFontTest/cmp_pdfA1b_fontCheckPdfA1_05.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfDocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfDocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); // Identity-H must be embedded PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "NotoSansCJKtc-Light.otf", "Identity-H"); @@ -150,8 +150,8 @@ public virtual void FontCheckPdfA2_01() { String cmpPdf = SOURCE_FOLDER + "cmp/PdfAFontTest/cmp_pdfA2b_fontCheckPdfA2_01.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfDocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfDocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); // Identity-H must be embedded PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "FreeSans.ttf", "Identity-H", PdfFontFactory.EmbeddingStrategy @@ -169,8 +169,8 @@ public virtual void FontCheckPdfA3_01() { String cmpPdf = SOURCE_FOLDER + "cmp/PdfAFontTest/cmp_pdfA3b_fontCheckPdfA3_01.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfDocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_3B, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfDocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_3B, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); // Identity-H must be embedded PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "FreeSans.ttf", "Identity-H", PdfFontFactory.EmbeddingStrategy @@ -213,7 +213,7 @@ public virtual void SymbolicTtfCharEncodingsPdfA1Test01() { // Here we produced valid pdfa files in the past by silently removing not valid symbols // But right now we check for used glyphs which don't exist in the font and throw exception Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => CreateDocumentWithFont( - "symbolicTtfCharEncodingsPdfA1Test01.pdf", "Symbols1.ttf", "", PdfAConformanceLevel.PDF_A_1B)); + "symbolicTtfCharEncodingsPdfA1Test01.pdf", "Symbols1.ttf", "", PdfAConformance.PDF_A_1B)); NUnit.Framework.Assert.AreEqual(PdfaExceptionMessageConstant.EMBEDDED_FONTS_SHALL_DEFINE_ALL_REFERENCED_GLYPHS , e.Message); } @@ -222,8 +222,8 @@ public virtual void SymbolicTtfCharEncodingsPdfA1Test01() { public virtual void SymbolicTtfCharEncodingsPdfA1Test02() { // if you specify encoding, symbolic font is treated as non-symbolic Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => CreateDocumentWithFont( - "symbolicTtfCharEncodingsPdfA1Test02.pdf", "Symbols1.ttf", PdfEncodings.MACROMAN, PdfAConformanceLevel - .PDF_A_1B)); + "symbolicTtfCharEncodingsPdfA1Test02.pdf", "Symbols1.ttf", PdfEncodings.MACROMAN, PdfAConformance.PDF_A_1B + )); NUnit.Framework.Assert.AreEqual(PdfaExceptionMessageConstant.EMBEDDED_FONTS_SHALL_DEFINE_ALL_REFERENCED_GLYPHS , e.Message); } @@ -232,8 +232,7 @@ public virtual void SymbolicTtfCharEncodingsPdfA1Test02() { public virtual void SymbolicTtfCharEncodingsPdfA1Test03() { // if you specify encoding, symbolic font is treated as non-symbolic Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => CreateDocumentWithFont( - "symbolicTtfCharEncodingsPdfA1Test03.pdf", "Symbols1.ttf", "ISO-8859-1", PdfAConformanceLevel.PDF_A_1B - )); + "symbolicTtfCharEncodingsPdfA1Test03.pdf", "Symbols1.ttf", "ISO-8859-1", PdfAConformance.PDF_A_1B)); NUnit.Framework.Assert.AreEqual(PdfaExceptionMessageConstant.EMBEDDED_FONTS_SHALL_DEFINE_ALL_REFERENCED_GLYPHS , e.Message); } @@ -241,8 +240,8 @@ public virtual void SymbolicTtfCharEncodingsPdfA1Test03() { [NUnit.Framework.Test] public virtual void SymbolicTtfCharEncodingsPdfA1Test04() { Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => CreateDocumentWithFont( - "symbolicTtfCharEncodingsPdfA1Test04.pdf", "Symbols1.ttf", PdfEncodings.WINANSI, PdfAConformanceLevel. - PDF_A_1B)); + "symbolicTtfCharEncodingsPdfA1Test04.pdf", "Symbols1.ttf", PdfEncodings.WINANSI, PdfAConformance.PDF_A_1B + )); NUnit.Framework.Assert.AreEqual(PdfaExceptionMessageConstant.EMBEDDED_FONTS_SHALL_DEFINE_ALL_REFERENCED_GLYPHS , e.Message); } @@ -253,8 +252,8 @@ public virtual void SymbolicTtfCharEncodingsPdfA1Test05() { // Here we produced valid pdfa files in the past by silently removing not valid symbols // But right now we check for used glyphs which don't exist in the font and throw exception Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => CreateDocumentWithFont( - "symbolicTtfCharEncodingsPdfA1Test05.pdf", "Symbols1.ttf", PdfEncodings.IDENTITY_H, PdfAConformanceLevel - .PDF_A_1B)); + "symbolicTtfCharEncodingsPdfA1Test05.pdf", "Symbols1.ttf", PdfEncodings.IDENTITY_H, PdfAConformance.PDF_A_1B + )); NUnit.Framework.Assert.AreEqual(PdfaExceptionMessageConstant.EMBEDDED_FONTS_SHALL_DEFINE_ALL_REFERENCED_GLYPHS , e.Message); } @@ -263,15 +262,14 @@ public virtual void SymbolicTtfCharEncodingsPdfA1Test05() { public virtual void NonSymbolicTtfCharEncodingsPdfA1Test01() { // encoding must be either winansi or macroman, by default winansi is used CreateDocumentWithFont("nonSymbolicTtfCharEncodingsPdfA1Test01.pdf", "FreeSans.ttf", PdfEncodings.WINANSI, - PdfAConformanceLevel.PDF_A_1B); + PdfAConformance.PDF_A_1B); } [NUnit.Framework.Test] public virtual void NonSymbolicTtfCharEncodingsPdfA1Test02() { // encoding must be either winansi or macroman, by default winansi is used Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => CreateDocumentWithFont( - "nonSymbolicTtfCharEncodingsPdfA1Test02.pdf", "FreeSans.ttf", "ISO-8859-1", PdfAConformanceLevel.PDF_A_2B - )); + "nonSymbolicTtfCharEncodingsPdfA1Test02.pdf", "FreeSans.ttf", "ISO-8859-1", PdfAConformance.PDF_A_2B)); NUnit.Framework.Assert.AreEqual(PdfaExceptionMessageConstant.ALL_NON_SYMBOLIC_TRUE_TYPE_FONT_SHALL_SPECIFY_MAC_ROMAN_ENCODING_OR_WIN_ANSI_ENCODING , e.Message); } @@ -281,8 +279,8 @@ public virtual void NotdefInTrueTypeFontTest() { String outPdf = DESTINATION_FOLDER + "notdefInTrueTypeFont.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfDocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "", - "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfDocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "FreeSans.ttf", "# simple 32 0020 00C5 1987", PdfFontFactory.EmbeddingStrategy .PREFER_EMBEDDED); PdfCanvas canvas = new PdfCanvas(doc.AddNewPage()); @@ -298,8 +296,8 @@ public virtual void NotdefFontTest2() { String outPdf = DESTINATION_FOLDER + "notdefFontTest2.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfDocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "", - "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfDocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "NotoSans-Regular.ttf", "", PdfFontFactory.EmbeddingStrategy .PREFER_EMBEDDED); PdfCanvas canvas = new PdfCanvas(doc.AddNewPage()); @@ -315,7 +313,7 @@ public virtual void GlyphLineWithUndefinedGlyphsTest() { String outPdf = DESTINATION_FOLDER + "glyphLineWithUndefinedGlyphs.pdf"; Stream icm = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); Document document = new Document(new PdfADocument(new PdfWriter(outPdf, new WriterProperties().SetPdfVersion - (PdfVersion.PDF_2_0)), PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + (PdfVersion.PDF_2_0)), PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" , "sRGB ICC preference", icm))); PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "NotoSans-Regular.ttf", "", PdfFontFactory.EmbeddingStrategy .PREFER_EMBEDDED); @@ -331,8 +329,8 @@ public virtual void PdfArrayWithUndefinedGlyphsTest() { String outPdf = DESTINATION_FOLDER + "pdfArrayWithUndefinedGlyphs.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfDocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "", - "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfDocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "NotoSans-Regular.ttf", "", PdfFontFactory.EmbeddingStrategy .PREFER_EMBEDDED); PdfCanvas canvas = new PdfCanvas(doc.AddNewPage()); @@ -354,8 +352,8 @@ public virtual void CreateDocumentWithType1FontAfmTest() { PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); writer.SetCompressionLevel(CompressionConstants.NO_COMPRESSION); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfDocument pdfDoc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", - "", "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfDocument pdfDoc = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfFont pdfType1Font = PdfFontFactory.CreateFont(FontProgramFactory.CreateType1Font(SOURCE_FOLDER + "cmr10.afm" , SOURCE_FOLDER + "cmr10.pfb"), FontEncoding.FONT_SPECIFIC, PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED ); @@ -383,8 +381,8 @@ public virtual void CheckPdfA4FreeSansForceEmbeddedTest() { writerProperties.SetPdfVersion(PdfVersion.PDF_2_0); PdfWriter writer = new PdfWriter(outPdf, writerProperties); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfDocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "", - "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfDocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "FreeSans.ttf", "WinAnsi", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); @@ -401,8 +399,8 @@ public virtual void CheckPdfA4FreeSansForceNotEmbeddedTest() { writerProperties.SetPdfVersion(PdfVersion.PDF_2_0); PdfWriter writer = new PdfWriter(new MemoryStream(), writerProperties); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfDocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "", - "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfDocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "FreeSans.ttf", PdfEncodings.WINANSI, PdfFontFactory.EmbeddingStrategy .FORCE_NOT_EMBEDDED); @@ -410,7 +408,7 @@ public virtual void CheckPdfA4FreeSansForceNotEmbeddedTest() { canvas.SaveState().SetFillColor(ColorConstants.GREEN).BeginText().MoveText(36, 700).SetFontAndSize(font, 36 ).ShowText("Hello World! Pdf/A-4").EndText().RestoreState(); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => doc.Close()); - NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(PdfAConformanceException.ALL_THE_FONTS_MUST_BE_EMBEDDED_THIS_ONE_IS_NOT_0 + NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(PdfaExceptionMessageConstant.ALL_THE_FONTS_MUST_BE_EMBEDDED_THIS_ONE_IS_NOT_0 , "FreeSans"), e.Message); } @@ -422,8 +420,8 @@ public virtual void CheckPdfA4FreeSansPreferNotEmbeddedTest() { writerProperties.SetPdfVersion(PdfVersion.PDF_2_0); PdfWriter writer = new PdfWriter(outPdf, writerProperties); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfDocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "", - "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfDocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); // Identity-H must be embedded PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "FreeSans.ttf", "Identity-H", PdfFontFactory.EmbeddingStrategy @@ -441,8 +439,8 @@ public virtual void CheckPdfA4HelveticaPreferEmbeddedTest() { writerProperties.SetPdfVersion(PdfVersion.PDF_2_0); PdfWriter writer = new PdfWriter(new MemoryStream(), writerProperties); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfDocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "", - "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfDocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); PdfFont font = PdfFontFactory.CreateFont("Helvetica", "WinAnsi", PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED ); @@ -450,7 +448,7 @@ public virtual void CheckPdfA4HelveticaPreferEmbeddedTest() { canvas.SaveState().SetFillColor(ColorConstants.GREEN).BeginText().MoveText(36, 700).SetFontAndSize(font, 36 ).ShowText("Hello World! Pdf/A-4").EndText().RestoreState(); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => doc.Close()); - NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(PdfAConformanceException.ALL_THE_FONTS_MUST_BE_EMBEDDED_THIS_ONE_IS_NOT_0 + NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(PdfaExceptionMessageConstant.ALL_THE_FONTS_MUST_BE_EMBEDDED_THIS_ONE_IS_NOT_0 , "Helvetica"), e.Message); } @@ -462,8 +460,8 @@ public virtual void CheckPdfA4NotoSansCJKtcLightTest() { writerProperties.SetPdfVersion(PdfVersion.PDF_2_0); PdfWriter writer = new PdfWriter(outPdf, writerProperties); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfDocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "", - "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfDocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); // Identity-H must be embedded PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "NotoSansCJKtc-Light.otf", "Identity-H"); @@ -483,8 +481,8 @@ public virtual void CheckPdfA4Puritan2Test() { writerProperties.SetPdfVersion(PdfVersion.PDF_2_0); PdfWriter writer = new PdfWriter(outPdf, writerProperties); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfDocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "", - "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfDocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); // Identity-H must be embedded PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "Puritan2.otf", "Identity-H"); @@ -503,8 +501,8 @@ public virtual void CheckPdfA4Type3Test() { writerProperties.SetPdfVersion(PdfVersion.PDF_2_0); PdfWriter writer = new PdfWriter(outPdf, writerProperties); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfDocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "", - "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfDocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); // A A A A E E E ~ é String testString = "A A A A E E E ~ \u00E9"; //writing type3 font characters @@ -555,8 +553,8 @@ public virtual void CheckPdfA4UmingTtcTest() { writerProperties.SetPdfVersion(PdfVersion.PDF_2_0); PdfWriter writer = new PdfWriter(outPdf, writerProperties); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfDocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "", - "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfDocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); PdfFont font = PdfFontFactory.CreateTtcFont(SOURCE_FOLDER + "uming.ttc", 0, "Identity-H", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED, false); @@ -575,8 +573,8 @@ public virtual void CheckPdfA4WoffTest() { writerProperties.SetPdfVersion(PdfVersion.PDF_2_0); PdfWriter writer = new PdfWriter(outPdf, writerProperties); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfDocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "", - "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfDocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "SourceSerif4-Black.woff", "Identity-H", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); @@ -595,8 +593,8 @@ public virtual void CheckPdfA4SurrogatePairTest() { writerProperties.SetPdfVersion(PdfVersion.PDF_2_0); PdfWriter writer = new PdfWriter(outPdf, writerProperties); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfDocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "", - "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfDocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "NotoEmoji-Regular.ttf", "Identity-H", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); @@ -607,13 +605,13 @@ public virtual void CheckPdfA4SurrogatePairTest() { CompareResult(outPdf, cmpPdf, null); } - private void CreateDocumentWithFont(String outFileName, String fontFileName, String encoding, PdfAConformanceLevel - conformanceLevel) { + private void CreateDocumentWithFont(String outFileName, String fontFileName, String encoding, PdfAConformance + conformance) { String outPdf = DESTINATION_FOLDER + outFileName; String cmpPdf = SOURCE_FOLDER + "cmp/PdfAFontTest/cmp_" + outFileName; PdfWriter writer = new PdfWriter(outPdf); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfDocument doc = new PdfADocument(writer, conformanceLevel, new PdfOutputIntent("Custom", "", "http://www.color.org" + PdfDocument doc = new PdfADocument(writer, conformance, new PdfOutputIntent("Custom", "", "http://www.color.org" , "sRGB IEC61966-2.1", @is)); PdfPage page = doc.AddNewPage(); PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + fontFileName, encoding, PdfFontFactory.EmbeddingStrategy @@ -637,8 +635,8 @@ private void CompareResult(String outPdf, String cmpPdf, String expectedVeraPdfW private void GeneratePdfA2WithCidFont(String fontFile, String outPdf) { using (PdfWriter writer = new PdfWriter(outPdf)) { using (Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm")) { - using (PdfDocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom" - , "", "http://www.color.org", "sRGB IEC61966-2.1", @is))) { + using (PdfDocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_2B, new PdfOutputIntent("Custom", + "", "http://www.color.org", "sRGB IEC61966-2.1", @is))) { PdfPage page = doc.AddNewPage(); // Identity-H must be embedded PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + fontFile, "Identity-H", PdfFontFactory.EmbeddingStrategy diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAFormFieldTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAFormFieldTest.cs index 81eefa979b..799e18af71 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAFormFieldTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAFormFieldTest.cs @@ -67,15 +67,15 @@ public virtual void PdfAButtonFieldTest() { Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); String file = "pdfAButtonField.pdf"; String filename = DESTINATION_FOLDER + file; - pdf = new PdfADocument(new PdfWriter(FileUtil.GetFileOutputStream(filename)), PdfAConformanceLevel.PDF_A_1B - , new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB ICC preference", @is)); + pdf = new PdfADocument(new PdfWriter(FileUtil.GetFileOutputStream(filename)), PdfAConformance.PDF_A_1B, new + PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB ICC preference", @is)); PageSize pageSize = PageSize.LETTER; Document doc = new Document(pdf, pageSize); PdfFontFactory.Register(SOURCE_FOLDER + "FreeSans.ttf", SOURCE_FOLDER + "FreeSans.ttf"); PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "FreeSans.ttf", PdfFontFactory.EmbeddingStrategy. PREFER_EMBEDDED); - PdfButtonFormField group = new RadioFormFieldBuilder(pdf, "group").SetGenericConformanceLevel(PdfAConformanceLevel - .PDF_A_1B).CreateRadioGroup(); + PdfButtonFormField group = new RadioFormFieldBuilder(pdf, "group").SetConformance(PdfConformance.PDF_A_1B) + .CreateRadioGroup(); group.SetValue(""); group.SetReadOnly(true); Paragraph p = new Paragraph(); @@ -112,15 +112,15 @@ public virtual void PdfA1DocWithPdfA1ButtonFieldTest() { String fileName = DESTINATION_FOLDER + name + ".pdf"; String cmp = SOURCE_FOLDER + "cmp/PdfAFormFieldTest/cmp_pdfA1DocWithPdfA1ButtonField.pdf"; Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_1B; - PdfADocument pdfDoc = new PdfADocument(new PdfWriter(fileName), conformanceLevel, new PdfOutputIntent("Custom" - , "", "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfConformance conformance = PdfConformance.PDF_A_1B; + PdfADocument pdfDoc = new PdfADocument(new PdfWriter(fileName), conformance.GetAConformance(), new PdfOutputIntent + ("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", @is)); PdfAcroForm form = PdfFormCreator.GetAcroForm(pdfDoc, true); - PdfFormField emptyField = new NonTerminalFormFieldBuilder(pdfDoc, "empty").SetGenericConformanceLevel(conformanceLevel - ).CreateNonTerminalFormField(); + PdfFormField emptyField = new NonTerminalFormFieldBuilder(pdfDoc, "empty").SetConformance(conformance).CreateNonTerminalFormField + (); emptyField.AddKid(new PushButtonFormFieldBuilder(pdfDoc, "button").SetWidgetRectangle(new Rectangle(36, 756 - , 20, 20)).SetGenericConformanceLevel(conformanceLevel).CreatePushButton().SetFieldFlags(PdfAnnotation - .PRINT).SetFieldName("button").SetValue("hello")); + , 20, 20)).SetConformance(conformance).CreatePushButton().SetFieldFlags(PdfAnnotation.PRINT).SetFieldName + ("button").SetValue("hello")); form.AddField(emptyField); pdfDoc.Close(); NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(fileName, cmp, DESTINATION_FOLDER)); @@ -134,13 +134,12 @@ public virtual void PdfA1DocWithPdfA1CheckBoxFieldTest() { String fileName = DESTINATION_FOLDER + name + ".pdf"; String cmp = SOURCE_FOLDER + "cmp/PdfAFormFieldTest/cmp_pdfA1DocWithPdfA1CheckBoxField.pdf"; Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_1B; - PdfADocument pdfDoc = new PdfADocument(new PdfWriter(fileName), conformanceLevel, new PdfOutputIntent("Custom" - , "", "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfConformance conformance = PdfConformance.PDF_A_1B; + PdfADocument pdfDoc = new PdfADocument(new PdfWriter(fileName), conformance.GetAConformance(), new PdfOutputIntent + ("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", @is)); PdfAcroForm form = PdfFormCreator.GetAcroForm(pdfDoc, true); form.AddField(new CheckBoxFormFieldBuilder(pdfDoc, "checkBox").SetWidgetRectangle(new Rectangle(36, 726, 20 - , 20)).SetCheckType(CheckBoxType.STAR).SetGenericConformanceLevel(conformanceLevel).CreateCheckBox().SetValue - ("1")); + , 20)).SetCheckType(CheckBoxType.STAR).SetConformance(conformance).CreateCheckBox().SetValue("1")); pdfDoc.Close(); NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(fileName, cmp, DESTINATION_FOLDER)); NUnit.Framework.Assert.IsNull(new VeraPdfValidator().Validate(fileName)); @@ -156,16 +155,15 @@ public virtual void PdfA1DocWithPdfA1ChoiceFieldTest() { PdfFont fontFreeSans = PdfFontFactory.CreateFont(SOURCE_FOLDER + "FreeSans.ttf", "WinAnsi", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_1B; - PdfADocument pdfDoc = new PdfADocument(new PdfWriter(fileName), conformanceLevel, new PdfOutputIntent("Custom" - , "", "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfConformance conformance = PdfConformance.PDF_A_1B; + PdfADocument pdfDoc = new PdfADocument(new PdfWriter(fileName), conformance.GetAConformance(), new PdfOutputIntent + ("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", @is)); PdfAcroForm form = PdfFormCreator.GetAcroForm(pdfDoc, true); PdfArray options = new PdfArray(); options.Add(new PdfString("Name")); options.Add(new PdfString("Surname")); PdfFormField choiceFormField = new ChoiceFormFieldBuilder(pdfDoc, "choice").SetWidgetRectangle(new Rectangle - (36, 696, 100, 70)).SetOptions(options).SetGenericConformanceLevel(conformanceLevel).CreateList().SetValue - ("1", true); + (36, 696, 100, 70)).SetOptions(options).SetConformance(conformance).CreateList().SetValue("1", true); choiceFormField.SetFont(fontFreeSans); form.AddField(choiceFormField); pdfDoc.Close(); @@ -182,13 +180,13 @@ public virtual void PdfA1DocWithPdfA1ComboBoxFieldTest() { PdfFont fontCJK = PdfFontFactory.CreateFont(SOURCE_FOLDER + "NotoSansCJKtc-Light.otf", PdfEncodings.IDENTITY_H , PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_1B; - PdfADocument pdfDoc = new PdfADocument(new PdfWriter(fileName), conformanceLevel, new PdfOutputIntent("Custom" - , "", "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfConformance conformance = PdfConformance.PDF_A_1B; + PdfADocument pdfDoc = new PdfADocument(new PdfWriter(fileName), conformance.GetAConformance(), new PdfOutputIntent + ("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", @is)); PdfAcroForm form = PdfFormCreator.GetAcroForm(pdfDoc, true); PdfFormField choiceFormField = new ChoiceFormFieldBuilder(pdfDoc, "combo").SetWidgetRectangle(new Rectangle - (156, 616, 70, 70)).SetOptions(new String[] { "用", "规", "表" }).SetGenericConformanceLevel(conformanceLevel - ).CreateComboBox().SetValue("用"); + (156, 616, 70, 70)).SetOptions(new String[] { "用", "规", "表" }).SetConformance(conformance).CreateComboBox + ().SetValue("用"); choiceFormField.SetFont(fontCJK); form.AddField(choiceFormField); pdfDoc.Close(); @@ -198,7 +196,6 @@ public virtual void PdfA1DocWithPdfA1ComboBoxFieldTest() { // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf\a validation on Android) [NUnit.Framework.Test] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.MULTIPLE_VALUES_ON_A_NON_MULTISELECT_FIELD)] public virtual void PdfA1DocWithPdfA1ListFieldTest() { String name = "pdfA1DocWithPdfA1ListField"; String fileName = DESTINATION_FOLDER + name + ".pdf"; @@ -206,16 +203,17 @@ public virtual void PdfA1DocWithPdfA1ListFieldTest() { PdfFont fontFreeSans = PdfFontFactory.CreateFont(SOURCE_FOLDER + "FreeSans.ttf", "WinAnsi", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_1B; - PdfADocument pdfDoc = new PdfADocument(new PdfWriter(fileName), conformanceLevel, new PdfOutputIntent("Custom" - , "", "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfConformance conformance = PdfConformance.PDF_A_1B; + PdfADocument pdfDoc = new PdfADocument(new PdfWriter(fileName), conformance.GetAConformance(), new PdfOutputIntent + ("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", @is)); PdfAcroForm form = PdfFormCreator.GetAcroForm(pdfDoc, true); PdfChoiceFormField f = new ChoiceFormFieldBuilder(pdfDoc, "list").SetWidgetRectangle(new Rectangle(86, 556 - , 50, 200)).SetOptions(new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }).SetGenericConformanceLevel - (conformanceLevel).CreateList(); + , 50, 200)).SetOptions(new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }).SetConformance + (conformance).CreateList(); f.SetValue("9").SetFont(fontFreeSans); f.SetValue("4"); f.SetTopIndex(2); + f.SetMultiSelect(true); f.SetListSelected(new String[] { "3", "5" }); form.AddField(f); pdfDoc.Close(); @@ -232,13 +230,12 @@ public virtual void PdfA1DocWithPdfA1PushButtonFieldTest() { PdfFont fontFreeSans = PdfFontFactory.CreateFont(SOURCE_FOLDER + "FreeSans.ttf", "WinAnsi", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_1B; - PdfADocument pdfDoc = new PdfADocument(new PdfWriter(fileName), conformanceLevel, new PdfOutputIntent("Custom" - , "", "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfConformance conformance = PdfConformance.PDF_A_1B; + PdfADocument pdfDoc = new PdfADocument(new PdfWriter(fileName), conformance.GetAConformance(), new PdfOutputIntent + ("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", @is)); PdfAcroForm form = PdfFormCreator.GetAcroForm(pdfDoc, true); PdfFormField pushButtonFormField = new PushButtonFormFieldBuilder(pdfDoc, "push button").SetWidgetRectangle - (new Rectangle(36, 526, 100, 20)).SetCaption("Push").SetGenericConformanceLevel(conformanceLevel).CreatePushButton - (); + (new Rectangle(36, 526, 100, 20)).SetCaption("Push").SetConformance(conformance).CreatePushButton(); pushButtonFormField.SetFont(fontFreeSans).SetFontSize(12); form.AddField(pushButtonFormField); pdfDoc.Close(); @@ -253,14 +250,14 @@ public virtual void PdfA1DocWithPdfA1RadioButtonFieldTest() { String fileName = DESTINATION_FOLDER + name + ".pdf"; String cmp = SOURCE_FOLDER + "cmp/PdfAFormFieldTest/cmp_pdfA1DocWithPdfA1RadioButtonField.pdf"; Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_1B; - PdfADocument pdfDoc = new PdfADocument(new PdfWriter(fileName), conformanceLevel, new PdfOutputIntent("Custom" - , "", "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfConformance conformance = PdfConformance.PDF_A_1B; + PdfADocument pdfDoc = new PdfADocument(new PdfWriter(fileName), conformance.GetAConformance(), new PdfOutputIntent + ("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", @is)); PdfAcroForm form = PdfFormCreator.GetAcroForm(pdfDoc, true); String pdfFormFieldName = "radio group"; - RadioFormFieldBuilder builder = new RadioFormFieldBuilder(pdfDoc, pdfFormFieldName).SetGenericConformanceLevel - (conformanceLevel); - PdfButtonFormField radioGroup = builder.SetGenericConformanceLevel(conformanceLevel).CreateRadioGroup(); + RadioFormFieldBuilder builder = new RadioFormFieldBuilder(pdfDoc, pdfFormFieldName).SetConformance(conformance + ); + PdfButtonFormField radioGroup = builder.SetConformance(conformance).CreateRadioGroup(); radioGroup.SetValue(""); PdfFormAnnotation radio1 = builder.CreateRadioButton("1", new Rectangle(36, 496, 20, 20)).SetBorderWidth(2 ).SetBorderColor(ColorConstants.ORANGE); @@ -284,13 +281,12 @@ public virtual void PdfA1DocWithPdfA1TextFieldTest() { .FORCE_EMBEDDED); fontFreeSans.SetSubset(false); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_1B; - PdfADocument pdfDoc = new PdfADocument(new PdfWriter(fileName), conformanceLevel, new PdfOutputIntent("Custom" - , "", "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfConformance conformance = PdfConformance.PDF_A_1B; + PdfADocument pdfDoc = new PdfADocument(new PdfWriter(fileName), conformance.GetAConformance(), new PdfOutputIntent + ("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", @is)); PdfAcroForm form = PdfFormCreator.GetAcroForm(pdfDoc, true); PdfFormField textFormField = new TextFormFieldBuilder(pdfDoc, "text").SetWidgetRectangle(new Rectangle(36, - 466, 90, 20)).SetGenericConformanceLevel(conformanceLevel).CreateText().SetValue("textField").SetValue - ("iText"); + 466, 90, 20)).SetConformance(conformance).CreateText().SetValue("textField").SetValue("iText"); textFormField.SetFont(fontFreeSans).SetFontSize(12); form.AddField(textFormField); pdfDoc.Close(); @@ -308,12 +304,12 @@ public virtual void PdfA1DocWithPdfA1SignatureFieldTest() { .FORCE_EMBEDDED); fontFreeSans.SetSubset(false); Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm"); - PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_1B; - PdfADocument pdfDoc = new PdfADocument(new PdfWriter(fileName), conformanceLevel, new PdfOutputIntent("Custom" - , "", "http://www.color.org", "sRGB IEC61966-2.1", @is)); + PdfConformance conformance = PdfConformance.PDF_A_1B; + PdfADocument pdfDoc = new PdfADocument(new PdfWriter(fileName), conformance.GetAConformance(), new PdfOutputIntent + ("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", @is)); PdfAcroForm form = PdfFormCreator.GetAcroForm(pdfDoc, true); - PdfFormField signFormField = new SignatureFormFieldBuilder(pdfDoc, "signature").SetGenericConformanceLevel - (conformanceLevel).CreateSignature(); + PdfFormField signFormField = new SignatureFormFieldBuilder(pdfDoc, "signature").SetConformance(conformance + ).CreateSignature(); signFormField.SetFont(fontFreeSans).SetFontSize(20); form.AddField(signFormField); pdfDoc.Close(); @@ -327,15 +323,14 @@ public virtual void MergePdfADocWithFormTest() { String fileName = DESTINATION_FOLDER + "pdfADocWithTextFormField.pdf"; String mergedDocFileName = DESTINATION_FOLDER + "mergedPdfADoc.pdf"; using (Stream @is = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm")) { - using (PdfADocument pdfDoc = new PdfADocument(new PdfWriter(fileName), PdfAConformanceLevel.PDF_A_1B, new - PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB ICC preference", @is))) { + using (PdfADocument pdfDoc = new PdfADocument(new PdfWriter(fileName), PdfAConformance.PDF_A_1B, new PdfOutputIntent + ("Custom", "", "http://www.color.org", "sRGB ICC preference", @is))) { using (Document doc = new Document(pdfDoc)) { PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "FreeSans.ttf", PdfEncodings.WINANSI); doc.Add(new Paragraph(new Text("Some text").SetFont(font).SetFontSize(10))); PdfAcroForm form = PdfFormCreator.GetAcroForm(pdfDoc, true); PdfFormField field = new TextFormFieldBuilder(pdfDoc, "text").SetWidgetRectangle(new Rectangle(150, 100, 100 - , 20)).SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_1B).CreateText().SetValue("textField").SetFieldName - ("text"); + , 20)).SetConformance(PdfConformance.PDF_A_1B).CreateText().SetValue("textField").SetFieldName("text"); field.SetFont(font).SetFontSize(10); field.GetFirstFormAnnotation().SetPage(1); form.AddField(field, pdfDoc.GetPage(1)); @@ -347,8 +342,8 @@ public virtual void MergePdfADocWithFormTest() { PdfADocument pdfDocToMerge; using (Stream is_1 = FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm")) { using (PdfDocument newDoc = new PdfDocument(new PdfReader(fileName))) { - pdfDocToMerge = new PdfADocument(new PdfWriter(mergedDocFileName).SetSmartMode(true), PdfAConformanceLevel - .PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB ICC preference", is_1)); + pdfDocToMerge = new PdfADocument(new PdfWriter(mergedDocFileName).SetSmartMode(true), PdfAConformance.PDF_A_1B + , new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB ICC preference", is_1)); newDoc.CopyPagesTo(1, newDoc.GetNumberOfPages(), pdfDocToMerge, new PdfPageFormCopier()); } } @@ -416,7 +411,7 @@ public virtual void TestCheckboxWithPDFA() { CheckBox checkBox = new CheckBox("CheckBox"); checkBox.SetChecked(true); checkBox.SetInteractive(true); - checkBox.SetPdfAConformanceLevel(PdfAConformanceLevel.PDF_A_1A); + checkBox.SetPdfConformance(PdfConformance.PDF_A_1A); doc.Add(checkBox); } ); @@ -432,7 +427,11 @@ public virtual void TestMultipleCombinationsFontOnFieldSeparate() { foreach (Func formFieldSupplier in GenerateFormFields()) { IFormField formField = formFieldSupplier(); formField.SetProperty(Property.FONT, font); - formField.SetProperty(Property.BORDER, new SolidBorder(ColorConstants.BLACK, 1)); + SolidBorder border = new SolidBorder(ColorConstants.BLACK, 1); + formField.SetProperty(Property.BORDER_TOP, border); + formField.SetProperty(Property.BORDER_RIGHT, border); + formField.SetProperty(Property.BORDER_BOTTOM, border); + formField.SetProperty(Property.BORDER_LEFT, border); formField.SetInteractive(true); document.Add(formField); } @@ -449,7 +448,11 @@ public virtual void TestMultipleCombinationsWriteAndReload() { foreach (Func formFieldSupplier in GenerateFormFields()) { IFormField formField = formFieldSupplier(); formField.SetProperty(Property.FONT, font); - formField.SetProperty(Property.BORDER, new SolidBorder(ColorConstants.BLACK, 1)); + SolidBorder border = new SolidBorder(ColorConstants.BLACK, 1); + formField.SetProperty(Property.BORDER_TOP, border); + formField.SetProperty(Property.BORDER_RIGHT, border); + formField.SetProperty(Property.BORDER_BOTTOM, border); + formField.SetProperty(Property.BORDER_LEFT, border); formField.SetInteractive(true); document.Add(formField); } @@ -478,7 +481,11 @@ public virtual void TestMultipleCombinationsOnDocument() { document.SetFont(font); foreach (Func formFieldSupplier in GenerateFormFields()) { IFormField formField = formFieldSupplier(); - formField.SetProperty(Property.BORDER, new SolidBorder(ColorConstants.BLACK, 1)); + SolidBorder border = new SolidBorder(ColorConstants.BLACK, 1); + formField.SetProperty(Property.BORDER_TOP, border); + formField.SetProperty(Property.BORDER_RIGHT, border); + formField.SetProperty(Property.BORDER_BOTTOM, border); + formField.SetProperty(Property.BORDER_LEFT, border); formField.SetProperty(Property.FONT, font); formField.SetInteractive(true); document.Add(formField); @@ -497,7 +504,11 @@ public virtual void TestMultipleCombinationsFontOnFieldSeparateNonInteractive() foreach (Func formFieldSupplier in GenerateFormFields()) { IFormField formField = formFieldSupplier(); formField.SetProperty(Property.FONT, font); - formField.SetProperty(Property.BORDER, new SolidBorder(ColorConstants.BLACK, 1)); + SolidBorder border = new SolidBorder(ColorConstants.BLACK, 1); + formField.SetProperty(Property.BORDER_TOP, border); + formField.SetProperty(Property.BORDER_RIGHT, border); + formField.SetProperty(Property.BORDER_BOTTOM, border); + formField.SetProperty(Property.BORDER_LEFT, border); formField.SetInteractive(false); document.Add(formField); } @@ -515,7 +526,11 @@ public virtual void TestMultipleCombinationsOnDocumentNonInteractive() { document.SetFont(font); foreach (Func formFieldSupplier in GenerateFormFields()) { IFormField formField = formFieldSupplier(); - formField.SetProperty(Property.BORDER, new SolidBorder(ColorConstants.BLACK, 1)); + SolidBorder border = new SolidBorder(ColorConstants.BLACK, 1); + formField.SetProperty(Property.BORDER_TOP, border); + formField.SetProperty(Property.BORDER_RIGHT, border); + formField.SetProperty(Property.BORDER_BOTTOM, border); + formField.SetProperty(Property.BORDER_LEFT, border); formField.SetProperty(Property.FONT, font); formField.SetInteractive(false); document.Add(formField); @@ -532,17 +547,17 @@ public virtual void TestCopyPagesDoesntEmbedHelveticaFont() { PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "FreeSans.ttf", "WinAnsi", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); PdfWriter writer = new PdfWriter(simplePdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4E, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm" - ))); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4E, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm")) + ); Document document = new Document(doc); document.Add(new InputField("inputfield1").SetFont(font).SetInteractive(true).SetValue("Hello there")); document.Add(new Paragraph("Hello there paragraph").SetFont(font)); doc.Close(); PdfWriter writer2 = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - PdfADocument doc2 = new PdfADocument(writer2, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", - "", "http://www.color.org", "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm" - ))); + PdfADocument doc2 = new PdfADocument(writer2, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm")) + ); PdfDocument docToCopy = new PdfDocument(new PdfReader(simplePdf)); docToCopy.CopyPagesTo(1, 1, doc2, new PdfPageFormCopier()); docToCopy.Close(); @@ -573,8 +588,7 @@ public virtual void PdfASignatureFieldWithTextAndFontTest() { signatureFieldAppearance2.SetContent(new SignedAppearanceText().SetLocationLine("Byeeee")); signatureFieldAppearance2.SetInteractive(true); PdfSignatureFormField signatureFormField = signatureFormFieldBuilder.SetWidgetRectangle(new Rectangle(200, - 200, 40, 40)).SetFont(fontFreeSans).SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_4).CreateSignature - (); + 200, 40, 40)).SetFont(fontFreeSans).SetConformance(PdfConformance.PDF_A_4).CreateSignature(); signatureFormField.GetFirstFormAnnotation().SetFormFieldElement(signatureFieldAppearance2); form.AddField(signatureFormField); } @@ -583,9 +597,9 @@ public virtual void PdfASignatureFieldWithTextAndFontTest() { private void MakePdfDocument(String outPdf, String cmp, Action consumer) { PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4E, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm" - ))); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4E, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm")) + ); Document document = new Document(doc); consumer(document); doc.Close(); @@ -602,14 +616,14 @@ private IList> GenerateFormFields() { inputs.Add(() => { CheckBox checkBox = new CheckBox("CheckBox"); checkBox.SetChecked(true); - checkBox.SetPdfAConformanceLevel(PdfAConformanceLevel.PDF_A_4); + checkBox.SetPdfConformance(PdfConformance.PDF_A_4); return checkBox; } ); inputs.Add(() => { CheckBox checkBox = new CheckBox("CheckBox1"); checkBox.SetChecked(false); - checkBox.SetPdfAConformanceLevel(PdfAConformanceLevel.PDF_A_4); + checkBox.SetPdfConformance(PdfConformance.PDF_A_4); return checkBox; } ); @@ -696,8 +710,8 @@ public override void Draw(DrawContext context) { Rectangle bbox = GetInnerAreaBBox(); PdfDocument pdf = context.GetDocument(); PdfAcroForm form = PdfFormCreator.GetAcroForm(pdf, true); - PdfFormAnnotation chk = new RadioFormFieldBuilder(pdf, "").SetGenericConformanceLevel(PdfAConformanceLevel - .PDF_A_1B).CreateRadioButton(_value, bbox); + PdfFormAnnotation chk = new RadioFormFieldBuilder(pdf, "").SetConformance(PdfConformance.PDF_A_1B).CreateRadioButton + (_value, bbox); _group.AddKid(chk); chk.SetPage(pageNumber); chk.SetVisibility(PdfFormAnnotation.VISIBLE); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAIndirectObjectsCountLimitTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAIndirectObjectsCountLimitTest.cs index c49d2a3082..4d28c16ad1 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAIndirectObjectsCountLimitTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAIndirectObjectsCountLimitTest.cs @@ -26,6 +26,7 @@ You should have received a copy of the GNU Affero General Public License using iText.IO.Font; using iText.Kernel.Font; using iText.Kernel.Pdf; +using iText.Kernel.Validation; using iText.Layout; using iText.Layout.Element; using iText.Pdfa.Checker; @@ -40,21 +41,23 @@ public class PdfAIndirectObjectsCountLimitTest : ExtendedITextTest { [NUnit.Framework.Test] public virtual void ValidAmountOfIndirectObjectsTest() { - PdfA1Checker testChecker = new _PdfA1Checker_59(PdfAConformanceLevel.PDF_A_1B); + PdfA1Checker testChecker = new _PdfA1Checker_58(PdfAConformance.PDF_A_1B); using (Stream icm = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm")) { using (Stream fos = new MemoryStream()) { - using (Document document = new Document(new PdfADocument(new PdfWriter(fos), PdfAConformanceLevel.PDF_A_1B - , GetOutputIntent(icm)))) { + using (Document document = new Document(new PdfADocument(new PdfWriter(fos), PdfAConformance.PDF_A_1B, GetOutputIntent + (icm)))) { PdfADocument pdfa = (PdfADocument)document.GetPdfDocument(); - pdfa.checker = testChecker; + ValidationContainer container = new ValidationContainer(); + container.AddChecker(testChecker); + pdfa.GetDiContainer().Register(typeof(ValidationContainer), container); document.Add(BuildContent()); } } } } - private sealed class _PdfA1Checker_59 : PdfA1Checker { - public _PdfA1Checker_59(PdfAConformanceLevel baseArg1) + private sealed class _PdfA1Checker_58 : PdfA1Checker { + public _PdfA1Checker_58(PdfAConformance baseArg1) : base(baseArg1) { } @@ -67,13 +70,15 @@ protected internal override long GetMaxNumberOfIndirectObjects() { // limit per "mock specification" conformance exception shouldn't be thrown [NUnit.Framework.Test] public virtual void InvalidAmountOfIndirectObjectsTest() { - PdfA1Checker testChecker = new _PdfA1Checker_84(PdfAConformanceLevel.PDF_A_1B); + PdfA1Checker testChecker = new _PdfA1Checker_85(PdfAConformance.PDF_A_1B); using (Stream icm = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm")) { using (Stream fos = new MemoryStream()) { - Document document = new Document(new PdfADocument(new PdfWriter(fos), PdfAConformanceLevel.PDF_A_1B, GetOutputIntent + Document document = new Document(new PdfADocument(new PdfWriter(fos), PdfAConformance.PDF_A_1B, GetOutputIntent (icm))); PdfADocument pdfa = (PdfADocument)document.GetPdfDocument(); - pdfa.checker = testChecker; + ValidationContainer container = new ValidationContainer(); + container.AddChecker(testChecker); + pdfa.GetDiContainer().Register(typeof(ValidationContainer), container); document.Add(BuildContent()); // generated document contains exactly 10 indirect objects. Given 9 is the allowed // limit per "mock specification" conformance exception should be thrown as the limit @@ -85,8 +90,8 @@ public virtual void InvalidAmountOfIndirectObjectsTest() { } } - private sealed class _PdfA1Checker_84 : PdfA1Checker { - public _PdfA1Checker_84(PdfAConformanceLevel baseArg1) + private sealed class _PdfA1Checker_85 : PdfA1Checker { + public _PdfA1Checker_85(PdfAConformance baseArg1) : base(baseArg1) { } @@ -97,12 +102,14 @@ protected internal override long GetMaxNumberOfIndirectObjects() { [NUnit.Framework.Test] public virtual void InvalidAmountOfIndirectObjectsAppendModeTest() { - PdfA1Checker testChecker = new _PdfA1Checker_112(PdfAConformanceLevel.PDF_A_1B); + PdfA1Checker testChecker = new _PdfA1Checker_115(PdfAConformance.PDF_A_1B); using (Stream fis = FileUtil.GetInputStreamForFile(sourceFolder + "pdfs/pdfa10IndirectObjects.pdf")) { using (Stream fos = new MemoryStream()) { PdfADocument pdfa = new PdfADocument(new PdfReader(fis), new PdfWriter(fos), new StampingProperties().UseAppendMode ()); - pdfa.checker = testChecker; + ValidationContainer container = new ValidationContainer(); + container.AddChecker(testChecker); + pdfa.GetDiContainer().Register(typeof(ValidationContainer), container); pdfa.AddNewPage(); // during closing of pdfa object exception will be thrown as new document will contain // 12 indirect objects and limit per "mock specification" conformance will be exceeded @@ -113,8 +120,8 @@ public virtual void InvalidAmountOfIndirectObjectsAppendModeTest() { } } - private sealed class _PdfA1Checker_112 : PdfA1Checker { - public _PdfA1Checker_112(PdfAConformanceLevel baseArg1) + private sealed class _PdfA1Checker_115 : PdfA1Checker { + public _PdfA1Checker_115(PdfAConformance baseArg1) : base(baseArg1) { } diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfALongStringTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfALongStringTest.cs index 57b91c4ff2..cc1118da50 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfALongStringTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfALongStringTest.cs @@ -55,7 +55,7 @@ public virtual void RunTest() { String filename = destinationFolder + file; using (Stream icm = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm")) { using (Stream fos = FileUtil.GetFileOutputStream(filename)) { - Document document = new Document(new PdfADocument(new PdfWriter(fos), PdfAConformanceLevel.PDF_A_3U, new PdfOutputIntent + Document document = new Document(new PdfADocument(new PdfWriter(fos), PdfAConformance.PDF_A_3U, new PdfOutputIntent ("Custom", "", "http://www.color.org", "sRGB ICC preference", icm))); StringBuilder stringBuilder = new StringBuilder(LOREM_IPSUM); while (stringBuilder.Length < STRING_LENGTH_LIMIT) { diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAPageTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAPageTest.cs index e961faba4f..c4e23f8f57 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAPageTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAPageTest.cs @@ -22,9 +22,11 @@ You should have received a copy of the GNU Affero General Public License */ using System; using iText.Commons.Utils; -using iText.Kernel.Events; using iText.Kernel.Geom; using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Event; +using iText.Kernel.Validation; +using iText.Kernel.Validation.Context; using iText.Layout; using iText.Layout.Element; using iText.Pdfa.Logs; @@ -53,8 +55,8 @@ public virtual void CheckThatFlushingPreventedWhenAddingElementToDocument() { // Expected log message that page flushing was not performed String outPdf = destinationFolder + "checkThatFlushingPreventedWhenAddingElementToDocument.pdf"; PdfWriter writer = new PdfWriter(outPdf); - PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1A, new PdfOutputIntent("Custom" - , "", "http://www.color.org", "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm" + PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformance.PDF_A_1A, new PdfOutputIntent("Custom", "", + "http://www.color.org", "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm" ))); pdfDoc.SetTagged(); pdfDoc.GetCatalog().SetLang(new PdfString("en-US")); @@ -83,8 +85,8 @@ public virtual void CheckThatFlushingPreventedWithFalseFlushResourcesContentStre // Expected log message that page flushing was not performed String outPdf = destinationFolder + "checkThatFlushingPreventedWithFalseFlushResourcesContentStreams.pdf"; PdfWriter writer = new PdfWriter(outPdf); - PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1A, new PdfOutputIntent("Custom" - , "", "http://www.color.org", "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm" + PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformance.PDF_A_1A, new PdfOutputIntent("Custom", "", + "http://www.color.org", "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm" ))); pdfDoc.SetTagged(); pdfDoc.GetCatalog().SetLang(new PdfString("en-US")); @@ -106,8 +108,8 @@ public virtual void CheckThatFlushingPreventedWithFalseFlushResourcesContentStre public virtual void CheckFlushingWhenPdfDocumentIsClosing() { String outPdf = destinationFolder + "checkFlushingWhenPdfDocumentIsClosing.pdf"; PdfWriter writer = new PdfWriter(outPdf); - PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1A, new PdfOutputIntent("Custom" - , "", "http://www.color.org", "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm" + PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformance.PDF_A_1A, new PdfOutputIntent("Custom", "", + "http://www.color.org", "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm" ))); pdfDoc.SetTagged(); pdfDoc.GetCatalog().SetLang(new PdfString("en-US")); @@ -129,8 +131,8 @@ public virtual void CheckFlushingWhenPdfDocumentIsClosing() { public virtual void CheckFlushingWithTrueFlushResourcesContentStreams() { String outPdf = destinationFolder + "checkFlushingWithTrueFlushResourcesContentStreams.pdf"; PdfWriter writer = new PdfWriter(outPdf); - PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1A, new PdfOutputIntent("Custom" - , "", "http://www.color.org", "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm" + PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformance.PDF_A_1A, new PdfOutputIntent("Custom", "", + "http://www.color.org", "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm" ))); pdfDoc.SetTagged(); pdfDoc.GetCatalog().SetLang(new PdfString("en-US")); @@ -152,8 +154,8 @@ public virtual void CheckFlushingWithTrueFlushResourcesContentStreams() { public virtual void CheckFlushingOfCheckedPage() { String outPdf = destinationFolder + "checkFlushingOfCheckedPage.pdf"; PdfWriter writer = new PdfWriter(outPdf); - PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1A, new PdfOutputIntent("Custom" - , "", "http://www.color.org", "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm" + PdfADocument pdfDoc = new PdfADocument(writer, PdfAConformance.PDF_A_1A, new PdfOutputIntent("Custom", "", + "http://www.color.org", "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm" ))); pdfDoc.SetTagged(); pdfDoc.GetCatalog().SetLang(new PdfString("en-US")); @@ -162,7 +164,7 @@ public virtual void CheckFlushingOfCheckedPage() { int pageCount = 3; for (int i = 0; i < pageCount; i++) { PdfPage page = pdfDoc.AddNewPage(); - pdfDoc.checker.CheckSinglePage(page); + pdfDoc.GetDiContainer().GetInstance().Validate(new PdfPageValidationContext(page)); page.Flush(false); } NUnit.Framework.Assert.AreEqual(pageCount, pdfDoc.GetNumberOfPages()); @@ -174,7 +176,7 @@ public virtual void CheckFlushingOfCheckedPage() { //\cond DO_NOT_DOCUMENT // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf\a validation on Android) - internal class EndPageEventHandler : iText.Kernel.Events.IEventHandler { + internal class EndPageEventHandler : AbstractPdfDocumentEventHandler { private int counter = 0; //\cond DO_NOT_DOCUMENT @@ -186,7 +188,7 @@ public virtual int GetCounter() { return counter; } - public virtual void HandleEvent(Event @event) { + protected override void OnAcceptedEvent(AbstractPdfDocumentEvent @event) { counter++; } } diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAPushbuttonfieldTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAPushbuttonfieldTest.cs index d67358d278..7bc426649a 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAPushbuttonfieldTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAPushbuttonfieldTest.cs @@ -60,7 +60,7 @@ public virtual void PdfA1bButtonAppearanceTest() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, outputIntent); doc.SetTagged(); doc.GetCatalog().SetLang(new PdfString("en-US")); doc.AddNewPage(); @@ -69,7 +69,7 @@ public virtual void PdfA1bButtonAppearanceTest() { PdfFont font = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", "WinAnsi", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); PdfFormField button = new PushButtonFormFieldBuilder(doc, "push button").SetWidgetRectangle(rect).SetCaption - ("push").SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_1B).CreatePushButton(); + ("push").SetConformance(PdfConformance.PDF_A_1B).CreatePushButton(); button.SetFont(font).SetFontSize(12); form.AddField(button); doc.Close(); @@ -89,7 +89,7 @@ public virtual void PdfA1bButtonAppearanceRegenerateTest() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, outputIntent); doc.SetTagged(); doc.GetCatalog().SetLang(new PdfString("en-US")); doc.AddNewPage(); @@ -98,7 +98,7 @@ public virtual void PdfA1bButtonAppearanceRegenerateTest() { PdfFont font = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", "WinAnsi", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); PdfFormField button = new PushButtonFormFieldBuilder(doc, "push button").SetWidgetRectangle(rect).SetCaption - ("push").SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_1B).CreatePushButton(); + ("push").SetConformance(PdfConformance.PDF_A_1B).CreatePushButton(); button.SetFont(font).SetFontSize(12); button.RegenerateField(); form.AddField(button); @@ -119,7 +119,7 @@ public virtual void PdfA1bButtonAppearanceSetValueTest() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, outputIntent); doc.SetTagged(); doc.GetCatalog().SetLang(new PdfString("en-US")); doc.AddNewPage(); @@ -128,7 +128,7 @@ public virtual void PdfA1bButtonAppearanceSetValueTest() { PdfFont font = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", "WinAnsi", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); PdfFormField button = new PushButtonFormFieldBuilder(doc, "push button").SetWidgetRectangle(rect).SetCaption - ("push").SetGenericConformanceLevel(PdfAConformanceLevel.PDF_A_1B).CreatePushButton(); + ("push").SetConformance(PdfConformance.PDF_A_1B).CreatePushButton(); button.SetFont(font).SetFontSize(12); button.SetValue("button"); form.AddField(button); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfARadiofieldTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfARadiofieldTest.cs index a97b1222bb..3ad83af184 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfARadiofieldTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfARadiofieldTest.cs @@ -58,7 +58,7 @@ public virtual void PdfA1aRadioFieldOffAppearanceTest() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, outputIntent); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_1B, outputIntent); doc.SetTagged(); doc.GetCatalog().SetLang(new PdfString("en-US")); doc.AddNewPage(); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfATransparencyCheckTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfATransparencyCheckTest.cs index 6286fa0e64..12949dc306 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfATransparencyCheckTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfATransparencyCheckTest.cs @@ -55,7 +55,7 @@ public static void BeforeClass() { [NUnit.Framework.Test] public virtual void TextTransparencyNoOutputIntentTest() { PdfWriter writer = new PdfWriter(new MemoryStream()); - PdfDocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_3B, null); + PdfDocument pdfDocument = new PdfADocument(writer, PdfAConformance.PDF_A_3B, null); PdfFont font = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", "Identity-H", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); PdfPage page1 = pdfDocument.AddNewPage(); @@ -75,7 +75,7 @@ public virtual void TextTransparencyNoOutputIntentTest() { public virtual void TransparentTextWithGroupColorSpaceTest() { String outPdf = destinationFolder + "transparencyAndCS.pdf"; String cmpPdf = cmpFolder + "cmp_transparencyAndCS.pdf"; - PdfDocument pdfDocument = new PdfADocument(new PdfWriter(outPdf), PdfAConformanceLevel.PDF_A_3B, null); + PdfDocument pdfDocument = new PdfADocument(new PdfWriter(outPdf), PdfAConformance.PDF_A_3B, null); PdfFont font = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", "Identity-H", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); PdfPage page = pdfDocument.AddNewPage(); @@ -104,8 +104,7 @@ public virtual void TransparentTextWithGroupColorSpaceTest() { [NUnit.Framework.Test] public virtual void ImageTransparencyTest() { - PdfDocument pdfDoc = new PdfADocument(new PdfWriter(new MemoryStream()), PdfAConformanceLevel.PDF_A_3B, null - ); + PdfDocument pdfDoc = new PdfADocument(new PdfWriter(new MemoryStream()), PdfAConformance.PDF_A_3B, null); PdfPage page = pdfDoc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(page); page.GetResources().SetDefaultRgb(new PdfCieBasedCs.CalRgb(new float[] { 0.3f, 0.4f, 0.5f })); @@ -121,7 +120,7 @@ public virtual void ImageTransparencyTest() { [NUnit.Framework.Test] public virtual void NestedXObjectWithTransparencyTest() { PdfWriter writer = new PdfWriter(new MemoryStream()); - PdfDocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_3B, null); + PdfDocument pdfDocument = new PdfADocument(writer, PdfAConformance.PDF_A_3B, null); PdfFormXObject form1 = new PdfFormXObject(new Rectangle(0, 0, 50, 50)); PdfCanvas canvas1 = new PdfCanvas(form1, pdfDocument); canvas1.SaveState(); @@ -155,7 +154,7 @@ public virtual void NestedXObjectWithTransparencyTest() { public virtual void TestTransparencyObjectsAbsence() { String outPdf = destinationFolder + "transparencyObjectsAbsence.pdf"; String cmpPdf = cmpFolder + "cmp_transparencyObjectsAbsence.pdf"; - PdfDocument pdfDocument = new PdfADocument(new PdfWriter(outPdf), PdfAConformanceLevel.PDF_A_3B, null); + PdfDocument pdfDocument = new PdfADocument(new PdfWriter(outPdf), PdfAConformance.PDF_A_3B, null); PdfPage page = pdfDocument.AddNewPage(); PdfFont font = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", "Identity-H", PdfFontFactory.EmbeddingStrategy .FORCE_EMBEDDED); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAXmpTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAXmpTest.cs index 906e23c0c8..f371aa5061 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAXmpTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/PdfAXmpTest.cs @@ -54,7 +54,7 @@ public virtual void KeywordsInfoTestPdfA1b() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(new PdfWriter(outFile), PdfAConformanceLevel.PDF_A_1B, outputIntent); + PdfADocument doc = new PdfADocument(new PdfWriter(outFile), PdfAConformance.PDF_A_1B, outputIntent); doc.AddNewPage(); doc.GetDocumentInfo().SetKeywords("key1, key2 , key3;key4,key5"); doc.Close(); @@ -71,7 +71,7 @@ public virtual void KeywordsInfoTestPdfA2b() { Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfADocument doc = new PdfADocument(new PdfWriter(outFile), PdfAConformanceLevel.PDF_A_2B, outputIntent); + PdfADocument doc = new PdfADocument(new PdfWriter(outFile), PdfAConformance.PDF_A_2B, outputIntent); doc.AddNewPage(); doc.GetDocumentInfo().SetKeywords("key1, key2 , key3;key4,key5"); doc.Close(); @@ -85,18 +85,18 @@ public virtual void KeywordsInfoTestPdfA2b() { public virtual void SaveAndReadDocumentWithCanonicalXmpMetadata() { String outFile = destinationFolder + "saveAndReadDocumentWithCanonicalXmpMetadata.pdf"; String cmpFile = cmpFolder + "cmp_saveAndReadDocumentWithCanonicalXmpMetadata.pdf"; - PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_2B; + PdfAConformance conformance = PdfAConformance.PDF_A_2B; PdfOutputIntent outputIntent; using (Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm")) { outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", @is); } - using (PdfADocument doc = new PdfADocument(new PdfWriter(outFile), conformanceLevel, outputIntent)) { + using (PdfADocument doc = new PdfADocument(new PdfWriter(outFile), conformance, outputIntent)) { doc.AddNewPage(); XMPMeta xmp = XMPMetaFactory.Create(); - xmp.SetProperty(XMPConst.NS_PDFA_ID, XMPConst.PART, conformanceLevel.GetPart(), new PropertyOptions().SetSchemaNode + xmp.SetProperty(XMPConst.NS_PDFA_ID, XMPConst.PART, conformance.GetPart(), new PropertyOptions().SetSchemaNode + (true)); + xmp.SetProperty(XMPConst.NS_PDFA_ID, XMPConst.CONFORMANCE, conformance.GetLevel(), new PropertyOptions().SetSchemaNode (true)); - xmp.SetProperty(XMPConst.NS_PDFA_ID, XMPConst.CONFORMANCE, conformanceLevel.GetConformance(), new PropertyOptions - ().SetSchemaNode(true)); SerializeOptions options = new SerializeOptions().SetUseCanonicalFormat(true).SetUseCompactFormat(false); doc.SetXmpMetadata(xmp, options); doc.SetTagged(); @@ -104,8 +104,8 @@ public virtual void SaveAndReadDocumentWithCanonicalXmpMetadata() { // Closing document and reopening it to flush it XMP metadata ModifyDate using (PdfDocument doc_1 = new PdfDocument(new PdfReader(outFile))) { using (PdfDocument cmpDoc = new PdfDocument(new PdfReader(cmpFile))) { - byte[] rdf = doc_1.GetXmpMetadata(); - byte[] expectedRdf = cmpDoc.GetXmpMetadata(); + byte[] rdf = doc_1.GetXmpMetadataBytes(); + byte[] expectedRdf = cmpDoc.GetXmpMetadataBytes(); // Comparing angle brackets, since it's the main difference between canonical and compact format. NUnit.Framework.Assert.AreEqual(Count(expectedRdf, (byte)'<'), Count(rdf, (byte)'<')); NUnit.Framework.Assert.IsNull(new CompareTool().CompareXmp(cmpFile, outFile, true)); @@ -130,20 +130,21 @@ public virtual void TestPdfUAIdSchemaNameSpaceUriIsNotText() { GeneratePdfAWithUA(baos); // check whether the pdfuaid NS URI was properly encoded as a URI with rdf:resource PdfDocument readDoc = new PdfDocument(new PdfReader(new MemoryStream(baos.ToArray()))); - String xmpString = iText.Commons.Utils.JavaUtil.GetStringForBytes(readDoc.GetXmpMetadata(), System.Text.Encoding + String xmpString = iText.Commons.Utils.JavaUtil.GetStringForBytes(readDoc.GetXmpMetadataBytes(), System.Text.Encoding .UTF8); NUnit.Framework.Assert.IsTrue(xmpString.Contains("" ), "Did not find expected namespaceURI definition"); } private void GeneratePdfAWithUA(Stream os) { - WriterProperties wp = new WriterProperties().AddUAXmpMetadata(); + WriterProperties wp = new WriterProperties().AddPdfUaXmpMetadata(PdfUAConformance.PDF_UA_1); using (PdfWriter w = new PdfWriter(os, wp)) { PdfOutputIntent outputIntent; using (Stream @is = FileUtil.GetInputStreamForFile(sourceFolder + "sRGB Color Space Profile.icm")) { outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", @is); } - PdfDocument pdfDoc = new PdfADocument(w, PdfAConformanceLevel.PDF_A_2A, outputIntent).SetTagged(); + PdfDocument pdfDoc = new PdfADocument(w, PdfAConformance.PDF_A_2A, outputIntent); + pdfDoc.SetTagged(); pdfDoc.GetDocumentInfo().SetTitle("Test document"); pdfDoc.GetCatalog().SetViewerPreferences(new PdfViewerPreferences().SetDisplayDocTitle(true)); pdfDoc.GetCatalog().SetLang(new PdfString("en")); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA1CheckerTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA1CheckerTest.cs index 32efcb9a0e..51832a0d0a 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA1CheckerTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA1CheckerTest.cs @@ -31,7 +31,7 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Pdfa.Checker { [NUnit.Framework.Category("UnitTest")] public class PdfA1CheckerTest : ExtendedITextTest { - private PdfA1Checker pdfA1Checker = new PdfA1Checker(PdfAConformanceLevel.PDF_A_1B); + private PdfA1Checker pdfA1Checker = new PdfA1Checker(PdfAConformance.PDF_A_1B); [NUnit.Framework.SetUp] public virtual void Before() { @@ -89,7 +89,7 @@ public virtual void DeprecatedCheckColorShadingTest() { pattern.SetShading(dictionary); Color color = new PatternColor(pattern); NUnit.Framework.Assert.DoesNotThrow(() => { - pdfA1Checker.CheckColor(color, new PdfDictionary(), true, null); + pdfA1Checker.CheckColor(null, color, new PdfDictionary(), true, null); } ); } @@ -98,7 +98,7 @@ public virtual void DeprecatedCheckColorShadingTest() { public virtual void CheckSignatureTest() { PdfDictionary dict = new PdfDictionary(); pdfA1Checker.CheckSignature(dict); - NUnit.Framework.Assert.IsTrue(pdfA1Checker.ObjectIsChecked(dict)); + NUnit.Framework.Assert.IsTrue(pdfA1Checker.IsPdfObjectReadyToFlush(dict)); } [NUnit.Framework.Test] diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA1ImplementationLimitsCheckerTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA1ImplementationLimitsCheckerTest.cs index 85156311bf..7a53af827e 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA1ImplementationLimitsCheckerTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA1ImplementationLimitsCheckerTest.cs @@ -34,7 +34,7 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Pdfa.Checker { [NUnit.Framework.Category("UnitTest")] public class PdfA1ImplementationLimitsCheckerTest : ExtendedITextTest { - private PdfA1Checker pdfA1Checker = new PdfA1Checker(PdfAConformanceLevel.PDF_A_1B); + private PdfA1Checker pdfA1Checker = new PdfA1Checker(PdfAConformance.PDF_A_1B); private const int MAX_ARRAY_CAPACITY = 8191; diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA2CheckerGlyphsTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA2CheckerGlyphsTest.cs index 73d940fc19..08bacaab2b 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA2CheckerGlyphsTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA2CheckerGlyphsTest.cs @@ -32,7 +32,7 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Pdfa.Checker { [NUnit.Framework.Category("UnitTest")] public class PdfA2CheckerGlyphsTest : ExtendedITextTest { - private readonly PdfA2Checker pdfA2Checker = new PdfA2Checker(PdfAConformanceLevel.PDF_A_2B); + private readonly PdfA2Checker pdfA2Checker = new PdfA2Checker(PdfAConformance.PDF_A_2B); [NUnit.Framework.SetUp] public virtual void Before() { diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA2CheckerTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA2CheckerTest.cs index 5e0a2b9cfb..3e2fbea7fd 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA2CheckerTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA2CheckerTest.cs @@ -22,6 +22,7 @@ You should have received a copy of the GNU Affero General Public License */ using System; using System.Collections.Generic; +using System.IO; using iText.Commons.Utils; using iText.Kernel.Colors; using iText.Kernel.Pdf; @@ -35,7 +36,7 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Pdfa.Checker { [NUnit.Framework.Category("UnitTest")] public class PdfA2CheckerTest : ExtendedITextTest { - private PdfA2Checker pdfA2Checker = new PdfA2Checker(PdfAConformanceLevel.PDF_A_2B); + private PdfA2Checker pdfA2Checker = new PdfA2Checker(PdfAConformance.PDF_A_2B); [NUnit.Framework.Test] public virtual void CheckNameEntryShouldBeUniqueBetweenDefaultAndAdditionalConfigs() { @@ -69,7 +70,7 @@ public virtual void CheckAsKeyInContentConfigDictTest() { catalog.Put(PdfName.OCProperties, ocProperties); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => pdfA2Checker.CheckCatalogValidEntries (catalog)); - NUnit.Framework.Assert.AreEqual(PdfAConformanceException.THE_AS_KEY_SHALL_NOT_APPEAR_IN_ANY_OPTIONAL_CONTENT_CONFIGURATION_DICTIONARY + NUnit.Framework.Assert.AreEqual(PdfaExceptionMessageConstant.THE_AS_KEY_SHALL_NOT_APPEAR_IN_ANY_OPTIONAL_CONTENT_CONFIGURATION_DICTIONARY , e.Message); } @@ -323,7 +324,7 @@ public virtual void DeprecatedCheckColorShadingTest() { pattern.SetShading(dictionary); Color color = new PatternColor(pattern); NUnit.Framework.Assert.DoesNotThrow(() => { - pdfA2Checker.CheckColor(color, new PdfDictionary(), true, null); + pdfA2Checker.CheckColor(null, color, new PdfDictionary(), true, null); } ); } @@ -348,7 +349,7 @@ public virtual void CheckColorShadingWithoutExtGStatePropertyInPatternDictTest() public virtual void CheckSignatureTest() { PdfDictionary signatureDict = CreateSignatureDict(); pdfA2Checker.CheckSignature(signatureDict); - NUnit.Framework.Assert.IsTrue(pdfA2Checker.ObjectIsChecked(signatureDict)); + NUnit.Framework.Assert.IsTrue(pdfA2Checker.IsPdfObjectReadyToFlush(signatureDict)); } [NUnit.Framework.Test] @@ -684,7 +685,7 @@ public virtual void CheckColorSpaceWithDeviceNWithoutAttributes() { .GetPdfObject()); PdfDictionary currentColorSpaces = new PdfDictionary(); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => pdfA2Checker.CheckColorSpace - (new PdfSpecialCs.DeviceN(deviceNAsArray), currentColorSpaces, true, false)); + (new PdfSpecialCs.DeviceN(deviceNAsArray), null, currentColorSpaces, true, false)); NUnit.Framework.Assert.AreEqual(PdfaExceptionMessageConstant.COLORANTS_DICTIONARY_SHALL_NOT_BE_EMPTY_IN_DEVICE_N_COLORSPACE , e.Message); } @@ -708,11 +709,61 @@ public virtual void CheckColorSpaceWithDeviceNWithoutColorants() { PdfDictionary attributes = new PdfDictionary(); deviceNAsArray.Add(attributes); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => pdfA2Checker.CheckColorSpace - (new PdfSpecialCs.DeviceN(deviceNAsArray), currentColorSpaces, true, false)); + (new PdfSpecialCs.DeviceN(deviceNAsArray), null, currentColorSpaces, true, false)); NUnit.Framework.Assert.AreEqual(PdfaExceptionMessageConstant.COLORANTS_DICTIONARY_SHALL_NOT_BE_EMPTY_IN_DEVICE_N_COLORSPACE , e.Message); } + [NUnit.Framework.Test] + public virtual void CheckColorSpaceWithIndexedTest() { + PdfDictionary currentColorSpaces = new PdfDictionary(); + PdfSpecialCs.Indexed indexed = new PdfSpecialCs.Indexed(PdfName.Indexed, 255, new PdfString(iText.Commons.Utils.JavaUtil.GetStringForBytes + ("".GetBytes(System.Text.Encoding.UTF8), System.Text.Encoding.UTF8))); + pdfA2Checker.CheckColorSpace(indexed, null, currentColorSpaces, true, false); + } + + //Nothing to check, no error should be thrown. + [NUnit.Framework.Test] + public virtual void CheckColorSpaceWithUnColoredTilingTest() { + PdfDictionary currentColorSpaces = new PdfDictionary(); + PdfSpecialCs.UncoloredTilingPattern uncoloredTilingCmykCs = new PdfSpecialCs.UncoloredTilingPattern(new PdfDeviceCs.Cmyk + ()); + pdfA2Checker.CheckColorSpace(uncoloredTilingCmykCs, null, currentColorSpaces, true, false); + } + + //Nothing to check, no error should be thrown. + [NUnit.Framework.Test] + public virtual void CheckExtGateTest() { + PdfExtGState egs = new PdfExtGState(); + egs.SetOverprintMode(1); + egs.SetFillOverPrintFlag(true); + egs.SetSoftMask(new PdfDictionary()); + egs.SetStrokeOpacity(0.3f); + PdfDocument dummyDoc = new PdfDocument(new PdfWriter(new MemoryStream())); + PdfCanvas canvas = new PdfCanvas(dummyDoc.AddNewPage()); + canvas.SetExtGState(egs); + CanvasGraphicsState canvasGraphicsState = new CanvasGraphicsState(canvas.GetGraphicsState()); + pdfA2Checker.CheckExtGState(canvasGraphicsState, null); + NUnit.Framework.Assert.AreEqual(0.3f, canvasGraphicsState.GetStrokeOpacity(), 0.00001); + NUnit.Framework.Assert.IsNotNull(canvasGraphicsState.GetSoftMask()); + NUnit.Framework.Assert.IsTrue(canvasGraphicsState.GetSoftMask().IsDictionary()); + NUnit.Framework.Assert.IsTrue(canvasGraphicsState.GetFillOverprint()); + NUnit.Framework.Assert.AreEqual(1, canvasGraphicsState.GetOverprintMode()); + } + + [NUnit.Framework.Test] + public virtual void CheckExtGateOverprintModeTest() { + PdfExtGState egs = new PdfExtGState(); + egs.SetSoftMask(new PdfDictionary()); + egs.SetStrokeOpacity(0.3f); + PdfDocument dummyDoc = new PdfDocument(new PdfWriter(new MemoryStream())); + PdfCanvas canvas = new PdfCanvas(dummyDoc.AddNewPage()); + canvas.SetExtGState(egs); + CanvasGraphicsState canvasGraphicsState = new CanvasGraphicsState(canvas.GetGraphicsState()); + pdfA2Checker.CheckExtGState(canvasGraphicsState, null); + } + + //Nothing to check, no error should be thrown. private static PdfDictionary CreateSignatureDict() { PdfDictionary signatureDict = new PdfDictionary(); PdfDictionary reference = new PdfDictionary(); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA2CheckerTransparencyTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA2CheckerTransparencyTest.cs index 63f900d928..8d2e3819e9 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA2CheckerTransparencyTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA2CheckerTransparencyTest.cs @@ -37,7 +37,7 @@ public class PdfA2CheckerTransparencyTest : ExtendedITextTest { [NUnit.Framework.SetUp] public virtual void Before() { - pdfA2Checker = new PdfA2Checker(PdfAConformanceLevel.PDF_A_2B); + pdfA2Checker = new PdfA2Checker(PdfAConformance.PDF_A_2B); pdfA2Checker.SetFullCheckMode(true); } diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA2ImplementationLimitsCheckerTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA2ImplementationLimitsCheckerTest.cs index 3ecb7df306..eedba13a96 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA2ImplementationLimitsCheckerTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA2ImplementationLimitsCheckerTest.cs @@ -35,7 +35,7 @@ public class PdfA2ImplementationLimitsCheckerTest : ExtendedITextTest { [NUnit.Framework.SetUp] public virtual void Before() { - pdfA2Checker = new PdfA2Checker(PdfAConformanceLevel.PDF_A_2B); + pdfA2Checker = new PdfA2Checker(PdfAConformance.PDF_A_2B); pdfA2Checker.SetFullCheckMode(true); } diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA3CheckerTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA3CheckerTest.cs index 2a14bf21aa..a67c8aec8e 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA3CheckerTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA3CheckerTest.cs @@ -28,7 +28,7 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Pdfa.Checker { [NUnit.Framework.Category("UnitTest")] public class PdfA3CheckerTest : ExtendedITextTest { - private PdfA1Checker pdfA3Checker = new PdfA3Checker(PdfAConformanceLevel.PDF_A_3B); + private PdfA1Checker pdfA3Checker = new PdfA3Checker(PdfAConformance.PDF_A_3B); [NUnit.Framework.SetUp] public virtual void Before() { diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA4ImplementationLimitsTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA4ImplementationLimitsTest.cs index a2d52c55f1..8b48f8d2f7 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA4ImplementationLimitsTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA4ImplementationLimitsTest.cs @@ -30,7 +30,7 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Pdfa.Checker { [NUnit.Framework.Category("UnitTest")] public class PdfA4ImplementationLimitsTest : ExtendedITextTest { - private PdfA4Checker pdfA4Checker = new PdfA4Checker(PdfAConformanceLevel.PDF_A_4); + private PdfA4Checker pdfA4Checker = new PdfA4Checker(PdfAConformance.PDF_A_4); [NUnit.Framework.SetUp] public virtual void Before() { @@ -39,7 +39,7 @@ public virtual void Before() { [NUnit.Framework.Test] public virtual void IndependentLongStringTest() { - int maxAllowedLength = new PdfA2Checker(PdfAConformanceLevel.PDF_A_2B).GetMaxStringLength(); + int maxAllowedLength = new PdfA2Checker(PdfAConformance.PDF_A_2B).GetMaxStringLength(); int testLength = maxAllowedLength + 1; PdfString longString = PdfACheckerTestUtils.GetLongString(testLength); //An exception should not be thrown because pdf/a-4 spec allows any length strings @@ -49,7 +49,7 @@ public virtual void IndependentLongStringTest() { [NUnit.Framework.Test] public virtual void LongStringInContentStreamTest() { - int maxAllowedLength = new PdfA2Checker(PdfAConformanceLevel.PDF_A_2B).GetMaxStringLength(); + int maxAllowedLength = new PdfA2Checker(PdfAConformance.PDF_A_2B).GetMaxStringLength(); int testLength = maxAllowedLength + 1; PdfString longString = PdfACheckerTestUtils.GetLongString(testLength); String newContentString = PdfACheckerTestUtils.GetStreamWithValue(longString); @@ -62,7 +62,7 @@ public virtual void LongStringInContentStreamTest() { [NUnit.Framework.Test] public virtual void IndependentLargeRealTest() { - PdfNumber largeNumber = new PdfNumber(new PdfA2Checker(PdfAConformanceLevel.PDF_A_2B).GetMaxRealValue()); + PdfNumber largeNumber = new PdfNumber(new PdfA2Checker(PdfAConformance.PDF_A_2B).GetMaxRealValue()); // An exception shall not be thrown pdf/a-4 has no number limits pdfA4Checker.CheckPdfObject(largeNumber); NUnit.Framework.Assert.AreEqual(float.MaxValue, largeNumber.FloatValue(), 0.001f); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA4MetaDataTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA4MetaDataTest.cs index 5eb85c7499..d848332bb1 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA4MetaDataTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfA4MetaDataTest.cs @@ -36,7 +36,7 @@ namespace iText.Pdfa.Checker { [NUnit.Framework.Category("IntegrationTest")] public class PdfA4MetaDataTest : ExtendedITextTest { private static readonly String DESTINATION_FOLDER = NUnit.Framework.TestContext.CurrentContext.TestDirectory - + "/test/itext/pdfa/PdfA4ActionCheckTest/"; + + "/test/itext/pdfa/PdfA4MetaDataTest/"; private static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext .CurrentContext.TestDirectory) + "/resources/itext/pdfa/"; @@ -49,12 +49,12 @@ public static void BeforeClass() { [NUnit.Framework.Test] public virtual void PdfA4DocumentShallContainMetaDataKey() { PdfDictionary dictionary = new PdfDictionary(); - PdfA4Checker checker = new PdfA4Checker(PdfAConformanceLevel.PDF_A_4); + PdfA4Checker checker = new PdfA4Checker(PdfAConformance.PDF_A_4); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { - new PdfA4Checker(PdfAConformanceLevel.PDF_A_4).CheckMetaData(dictionary); + new PdfA4Checker(PdfAConformance.PDF_A_4).CheckMetaData(dictionary); } ); - NUnit.Framework.Assert.AreEqual(e.Message, PdfAConformanceException.A_CATALOG_DICTIONARY_SHALL_CONTAIN_METADATA_ENTRY + NUnit.Framework.Assert.AreEqual(e.Message, PdfaExceptionMessageConstant.A_CATALOG_DICTIONARY_SHALL_CONTAIN_METADATA_ENTRY ); } @@ -62,7 +62,7 @@ public virtual void PdfA4DocumentShallContainMetaDataKey() { public virtual void PdfA4DocumentMetaDataDocumentShallNotContainBytes() { String startHeader = "\n"; byte[] bytes = startHeader.GetBytes(); - PdfA4Checker checker = new PdfA4Checker(PdfAConformanceLevel.PDF_A_4); + PdfA4Checker checker = new PdfA4Checker(PdfAConformance.PDF_A_4); PdfDictionary catalog = new PdfDictionary(); catalog.Put(PdfName.Metadata, new PdfStream(bytes)); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { @@ -77,7 +77,7 @@ public virtual void PdfA4DocumentMetaDataDocumentShallNotContainBytes() { public virtual void PdfA4DocumentMetaDataDocumentShallNotContainEncoding() { String startHeader = "\n"; byte[] bytes = startHeader.GetBytes(); - PdfA4Checker checker = new PdfA4Checker(PdfAConformanceLevel.PDF_A_4); + PdfA4Checker checker = new PdfA4Checker(PdfAConformance.PDF_A_4); PdfDictionary catalog = new PdfDictionary(); catalog.Put(PdfName.Metadata, new PdfStream(bytes)); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { @@ -93,7 +93,7 @@ public virtual void PdfA4DocumentMetaDataDocumentShallNotContainEncodingInAnyPac String startHeader = "\n"; startHeader += "\n"; byte[] bytes = startHeader.GetBytes(); - PdfA4Checker checker = new PdfA4Checker(PdfAConformanceLevel.PDF_A_4); + PdfA4Checker checker = new PdfA4Checker(PdfAConformance.PDF_A_4); PdfDictionary catalog = new PdfDictionary(); catalog.Put(PdfName.Metadata, new PdfStream(bytes)); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { @@ -108,7 +108,7 @@ public virtual void PdfA4DocumentMetaDataDocumentShallNotContainEncodingInAnyPac public virtual void PdfA4DocumentMetaDataDocumentShallNotThrowInAnyPacket() { byte[] bytes = File.ReadAllBytes(System.IO.Path.Combine(SOURCE_FOLDER + "xmp/xmpWithMultipleXmpHeaders.xmp" )); - PdfA4Checker checker = new PdfA4Checker(PdfAConformanceLevel.PDF_A_4); + PdfA4Checker checker = new PdfA4Checker(PdfAConformance.PDF_A_4); PdfDictionary catalog = new PdfDictionary(); catalog.Put(PdfName.Metadata, new PdfStream(bytes)); NUnit.Framework.Assert.DoesNotThrow(() => { @@ -123,7 +123,7 @@ public virtual void PdfA4DocumentMetaDataRevPropertyHasCorrectPrefix() { )); String xmpContent = iText.Commons.Utils.JavaUtil.GetStringForBytes(bytes, System.Text.Encoding.ASCII).Replace ("pdfaid:rev", "rev"); - PdfA4Checker checker = new PdfA4Checker(PdfAConformanceLevel.PDF_A_4); + PdfA4Checker checker = new PdfA4Checker(PdfAConformance.PDF_A_4); PdfDictionary catalog = new PdfDictionary(); catalog.Put(PdfName.Metadata, new PdfStream(xmpContent.GetBytes(System.Text.Encoding.UTF8))); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => { @@ -138,7 +138,7 @@ public virtual void PdfA4DocumentMetaDataIdentificationSchemaUsesCorrectNamespac )); String xmpContent = iText.Commons.Utils.JavaUtil.GetStringForBytes(bytes, System.Text.Encoding.ASCII).Replace ("http://www.aiim.org/pdfa/ns/id/", "no_link"); - PdfA4Checker checker = new PdfA4Checker(PdfAConformanceLevel.PDF_A_4); + PdfA4Checker checker = new PdfA4Checker(PdfAConformance.PDF_A_4); PdfDictionary catalog = new PdfDictionary(); catalog.Put(PdfName.Metadata, new PdfStream(xmpContent.GetBytes(System.Text.Encoding.UTF8))); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { @@ -153,7 +153,7 @@ public virtual void PdfA4DocumentMetaDataIdentificationSchemaUsesCorrectNamespac public virtual void PdfA4DocumentMetaDataDocumentShallThrowInSecondPacket() { byte[] bytes = File.ReadAllBytes(System.IO.Path.Combine(SOURCE_FOLDER + "xmp/xmpWithMultipleXmpHeadersWithEnconding.xmp" )); - PdfA4Checker checker = new PdfA4Checker(PdfAConformanceLevel.PDF_A_4); + PdfA4Checker checker = new PdfA4Checker(PdfAConformance.PDF_A_4); PdfDictionary catalog = new PdfDictionary(); catalog.Put(PdfName.Metadata, new PdfStream(bytes)); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { @@ -167,8 +167,8 @@ public virtual void PdfA4DocumentMetaDataDocumentShallThrowInSecondPacket() { [NUnit.Framework.Test] public virtual void TestAbsentPartPropertyPDFA4() { String outPdf = DESTINATION_FOLDER + "testAbsentPartPropertyPDFA4.pdf"; - PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_4; - GeneratePdfADocument(conformanceLevel, outPdf, (doc) => { + PdfAConformance conformance = PdfAConformance.PDF_A_4; + GeneratePdfADocument(conformance, outPdf, (doc) => { } ); PdfADocument pdfADocument = new PdfADocument(new PdfReader(outPdf), new PdfWriter(new MemoryStream())); @@ -177,7 +177,7 @@ public virtual void TestAbsentPartPropertyPDFA4() { } )); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { - new PdfA4Checker(conformanceLevel).CheckMetaData(catalog); + new PdfA4Checker(conformance).CheckMetaData(catalog); } ); NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(PdfaExceptionMessageConstant.XMP_METADATA_HEADER_SHALL_CONTAIN_VERSION_IDENTIFIER_PART @@ -187,8 +187,8 @@ public virtual void TestAbsentPartPropertyPDFA4() { [NUnit.Framework.Test] public virtual void TestInvalidPartPropertyPDFA4() { String outPdf = DESTINATION_FOLDER + "testInvalidPartPropertyPDFA4.pdf"; - PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_4; - GeneratePdfADocument(conformanceLevel, outPdf, (doc) => { + PdfAConformance conformance = PdfAConformance.PDF_A_4; + GeneratePdfADocument(conformance, outPdf, (doc) => { } ); PdfADocument pdfADocument = new PdfADocument(new PdfReader(outPdf), new PdfWriter(new MemoryStream())); @@ -202,7 +202,7 @@ public virtual void TestInvalidPartPropertyPDFA4() { } )); Exception e_1 = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { - new PdfA4Checker(conformanceLevel).CheckMetaData(catalog); + new PdfA4Checker(conformance).CheckMetaData(catalog); } ); NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(PdfaExceptionMessageConstant.XMP_METADATA_HEADER_SHALL_CONTAIN_VERSION_IDENTIFIER_PART @@ -212,8 +212,8 @@ public virtual void TestInvalidPartPropertyPDFA4() { [NUnit.Framework.Test] public virtual void TestNullPartPropertyPDFA4() { String outPdf = DESTINATION_FOLDER + "testNullPartPropertyPDFA4.pdf"; - PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_4; - GeneratePdfADocument(conformanceLevel, outPdf, (doc) => { + PdfAConformance conformance = PdfAConformance.PDF_A_4; + GeneratePdfADocument(conformance, outPdf, (doc) => { } ); PdfADocument pdfADocument = new PdfADocument(new PdfReader(outPdf), new PdfWriter(new MemoryStream())); @@ -227,7 +227,7 @@ public virtual void TestNullPartPropertyPDFA4() { } )); Exception e_1 = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { - new PdfA4Checker(conformanceLevel).CheckMetaData(catalog); + new PdfA4Checker(conformance).CheckMetaData(catalog); } ); NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(PdfaExceptionMessageConstant.XMP_METADATA_HEADER_SHALL_CONTAIN_VERSION_IDENTIFIER_PART @@ -237,8 +237,8 @@ public virtual void TestNullPartPropertyPDFA4() { [NUnit.Framework.Test] public virtual void TestAbsentRevisionPropertyPDFA4() { String outPdf = DESTINATION_FOLDER + "testNullRevisionPropertyPDFA4.pdf"; - PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_4; - GeneratePdfADocument(conformanceLevel, outPdf, (doc) => { + PdfAConformance conformance = PdfAConformance.PDF_A_4; + GeneratePdfADocument(conformance, outPdf, (doc) => { } ); PdfADocument pdfADocument = new PdfADocument(new PdfReader(outPdf), new PdfWriter(new MemoryStream())); @@ -247,7 +247,7 @@ public virtual void TestAbsentRevisionPropertyPDFA4() { } )); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { - new PdfA4Checker(conformanceLevel).CheckMetaData(catalog); + new PdfA4Checker(conformance).CheckMetaData(catalog); } ); NUnit.Framework.Assert.AreEqual(PdfaExceptionMessageConstant.XMP_METADATA_HEADER_SHALL_CONTAIN_VERSION_IDENTIFIER_REV @@ -257,8 +257,8 @@ public virtual void TestAbsentRevisionPropertyPDFA4() { [NUnit.Framework.Test] public virtual void TestInvalidValueNotNumberRevisionPropertyPDFA4() { String outPdf = DESTINATION_FOLDER + "testInvalidValueNotNumberRevisionPropertyPDFA4.pdf"; - PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_4; - GeneratePdfADocument(conformanceLevel, outPdf, (doc) => { + PdfAConformance conformance = PdfAConformance.PDF_A_4; + GeneratePdfADocument(conformance, outPdf, (doc) => { } ); PdfADocument pdfADocument = new PdfADocument(new PdfReader(outPdf), new PdfWriter(new MemoryStream())); @@ -272,7 +272,7 @@ public virtual void TestInvalidValueNotNumberRevisionPropertyPDFA4() { } )); Exception e_1 = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { - new PdfA4Checker(conformanceLevel).CheckMetaData(catalog); + new PdfA4Checker(conformance).CheckMetaData(catalog); } ); NUnit.Framework.Assert.AreEqual(PdfaExceptionMessageConstant.XMP_METADATA_HEADER_SHALL_CONTAIN_VERSION_IDENTIFIER_REV @@ -282,8 +282,8 @@ public virtual void TestInvalidValueNotNumberRevisionPropertyPDFA4() { [NUnit.Framework.Test] public virtual void TestInvalidValueNotLength4RevisionPropertyPDFA4() { String outPdf = DESTINATION_FOLDER + "testInvalidValueNotLength4RevisionPropertyPDFA4.pdf"; - PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_4; - GeneratePdfADocument(conformanceLevel, outPdf, (doc) => { + PdfAConformance conformance = PdfAConformance.PDF_A_4; + GeneratePdfADocument(conformance, outPdf, (doc) => { } ); PdfADocument pdfADocument = new PdfADocument(new PdfReader(outPdf), new PdfWriter(new MemoryStream())); @@ -297,7 +297,7 @@ public virtual void TestInvalidValueNotLength4RevisionPropertyPDFA4() { } )); Exception e_1 = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { - new PdfA4Checker(conformanceLevel).CheckMetaData(catalog); + new PdfA4Checker(conformance).CheckMetaData(catalog); } ); NUnit.Framework.Assert.AreEqual(PdfaExceptionMessageConstant.XMP_METADATA_HEADER_SHALL_CONTAIN_VERSION_IDENTIFIER_REV @@ -307,8 +307,8 @@ public virtual void TestInvalidValueNotLength4RevisionPropertyPDFA4() { [NUnit.Framework.Test] public virtual void TestInvalidValueLength4ButContainsLettersRevisionPropertyPDFA4() { String outPdf = DESTINATION_FOLDER + "testInvalidValueLength4ButContainsLettersRevisionPropertyPDFA4.pdf"; - PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_4; - GeneratePdfADocument(conformanceLevel, outPdf, (doc) => { + PdfAConformance conformance = PdfAConformance.PDF_A_4; + GeneratePdfADocument(conformance, outPdf, (doc) => { } ); PdfADocument pdfADocument = new PdfADocument(new PdfReader(outPdf), new PdfWriter(new MemoryStream())); @@ -322,7 +322,7 @@ public virtual void TestInvalidValueLength4ButContainsLettersRevisionPropertyPDF } )); Exception e_1 = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { - new PdfA4Checker(conformanceLevel).CheckMetaData(catalog); + new PdfA4Checker(conformance).CheckMetaData(catalog); } ); NUnit.Framework.Assert.AreEqual(PdfaExceptionMessageConstant.XMP_METADATA_HEADER_SHALL_CONTAIN_VERSION_IDENTIFIER_REV @@ -332,8 +332,8 @@ public virtual void TestInvalidValueLength4ButContainsLettersRevisionPropertyPDF [NUnit.Framework.Test] public virtual void TestValidPropertiesPDFA4() { String outPdf = DESTINATION_FOLDER + "testValidPropertiesPDFA4.pdf"; - PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_4; - GeneratePdfADocument(conformanceLevel, outPdf, (doc) => { + PdfAConformance conformance = PdfAConformance.PDF_A_4; + GeneratePdfADocument(conformance, outPdf, (doc) => { } ); PdfADocument pdfADocument = new PdfADocument(new PdfReader(outPdf), new PdfWriter(new MemoryStream())); @@ -341,7 +341,7 @@ public virtual void TestValidPropertiesPDFA4() { } )); NUnit.Framework.Assert.DoesNotThrow(() => { - new PdfA4Checker(conformanceLevel).CheckMetaData(catalog); + new PdfA4Checker(conformance).CheckMetaData(catalog); } ); } @@ -349,8 +349,8 @@ public virtual void TestValidPropertiesPDFA4() { [NUnit.Framework.Test] public virtual void TestValidPropertiesPDFA4F() { String outPdf = DESTINATION_FOLDER + "testValidPropertiesPDFA4F.pdf"; - PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_4F; - GeneratePdfADocument(conformanceLevel, outPdf, (doc) => { + PdfAConformance conformance = PdfAConformance.PDF_A_4F; + GeneratePdfADocument(conformance, outPdf, (doc) => { PdfFileSpec fs = PdfFileSpec.CreateEmbeddedFileSpec(doc, "file".GetBytes(), "description", "file.txt", null , null, null); doc.AddFileAttachment("file.txt", fs); @@ -361,7 +361,7 @@ public virtual void TestValidPropertiesPDFA4F() { } )); NUnit.Framework.Assert.DoesNotThrow(() => { - new PdfA4Checker(conformanceLevel).CheckMetaData(catalog); + new PdfA4Checker(conformance).CheckMetaData(catalog); } ); } @@ -369,8 +369,8 @@ public virtual void TestValidPropertiesPDFA4F() { [NUnit.Framework.Test] public virtual void TestValidPropertiesPDFA4E() { String outPdf = DESTINATION_FOLDER + "testValidPropertiesPDFA4E.pdf"; - PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_4E; - GeneratePdfADocument(conformanceLevel, outPdf, (doc) => { + PdfAConformance conformance = PdfAConformance.PDF_A_4E; + GeneratePdfADocument(conformance, outPdf, (doc) => { } ); PdfADocument pdfADocument = new PdfADocument(new PdfReader(outPdf), new PdfWriter(new MemoryStream())); @@ -378,7 +378,7 @@ public virtual void TestValidPropertiesPDFA4E() { } )); NUnit.Framework.Assert.DoesNotThrow(() => { - new PdfA4Checker(conformanceLevel).CheckMetaData(catalog); + new PdfA4Checker(conformance).CheckMetaData(catalog); } ); } @@ -386,8 +386,8 @@ public virtual void TestValidPropertiesPDFA4E() { [NUnit.Framework.Test] public virtual void TestAbsentConformancePropertyPDFA4F() { String outPdf = DESTINATION_FOLDER + "testAbsentConformancePropertyPDFA4F.pdf"; - PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_4F; - GeneratePdfADocument(conformanceLevel, outPdf, (doc) => { + PdfAConformance conformance = PdfAConformance.PDF_A_4F; + GeneratePdfADocument(conformance, outPdf, (doc) => { PdfFileSpec fs = PdfFileSpec.CreateEmbeddedFileSpec(doc, "file".GetBytes(), "description", "file.txt", null , null, null); doc.AddFileAttachment("file.txt", fs); @@ -398,14 +398,14 @@ public virtual void TestAbsentConformancePropertyPDFA4F() { xmpMeta.DeleteProperty(XMPConst.NS_PDFA_ID, XMPConst.CONFORMANCE); } )); - NUnit.Framework.Assert.DoesNotThrow(() => new PdfA4Checker(conformanceLevel).CheckMetaData(catalog)); + NUnit.Framework.Assert.DoesNotThrow(() => new PdfA4Checker(conformance).CheckMetaData(catalog)); } [NUnit.Framework.Test] public virtual void TestInvalidConformancePropertyPDFA4F() { String outPdf = DESTINATION_FOLDER + "testInvalidConformancePropertyPDFA4F.pdf"; - PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_4F; - GeneratePdfADocument(conformanceLevel, outPdf, (doc) => { + PdfAConformance conformance = PdfAConformance.PDF_A_4F; + GeneratePdfADocument(conformance, outPdf, (doc) => { PdfFileSpec fs = PdfFileSpec.CreateEmbeddedFileSpec(doc, "file".GetBytes(), "description", "file.txt", null , null, null); doc.AddFileAttachment("file.txt", fs); @@ -422,7 +422,7 @@ public virtual void TestInvalidConformancePropertyPDFA4F() { } )); Exception e_1 = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { - new PdfA4Checker(conformanceLevel).CheckMetaData(catalog); + new PdfA4Checker(conformance).CheckMetaData(catalog); } ); NUnit.Framework.Assert.AreEqual(PdfaExceptionMessageConstant.XMP_METADATA_HEADER_SHALL_CONTAIN_VERSION_IDENTIFIER_CONFORMANCE @@ -431,26 +431,26 @@ public virtual void TestInvalidConformancePropertyPDFA4F() { [NUnit.Framework.Test] public virtual void HistoryWithXmpMetaData() { - PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_4; + PdfAConformance conformance = PdfAConformance.PDF_A_4; byte[] bytes = File.ReadAllBytes(System.IO.Path.Combine(SOURCE_FOLDER + "xmp/xmpWithCorrectHistory.xmp")); XMPMeta xmpMeta = XMPMetaFactory.Parse(new MemoryStream(bytes)); PdfDictionary catalog = new PdfDictionary(); MemoryStream baos = new MemoryStream(); XMPMetaFactory.Serialize(xmpMeta, baos); catalog.Put(PdfName.Metadata, new PdfStream(baos.ToArray())); - NUnit.Framework.Assert.DoesNotThrow(() => new PdfA4Checker(conformanceLevel).CheckMetaData(catalog)); + NUnit.Framework.Assert.DoesNotThrow(() => new PdfA4Checker(conformance).CheckMetaData(catalog)); } [NUnit.Framework.Test] public virtual void HistoryWithInvalidWhenXmpMetaData() { - PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_4; + PdfAConformance conformance = PdfAConformance.PDF_A_4; byte[] bytes = File.ReadAllBytes(System.IO.Path.Combine(SOURCE_FOLDER + "xmp/xmpWithInvalidWhen.xmp")); XMPMeta xmpMeta = XMPMetaFactory.Parse(new MemoryStream(bytes)); PdfDictionary catalog = new PdfDictionary(); MemoryStream baos = new MemoryStream(); XMPMetaFactory.Serialize(xmpMeta, baos); catalog.Put(PdfName.Metadata, new PdfStream(baos.ToArray())); - Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => new PdfA4Checker(conformanceLevel + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => new PdfA4Checker(conformance ).CheckMetaData(catalog)); NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(PdfaExceptionMessageConstant.XMP_METADATA_HISTORY_ENTRY_SHALL_CONTAIN_KEY , "stEvt:when"), e.Message); @@ -458,14 +458,14 @@ public virtual void HistoryWithInvalidWhenXmpMetaData() { [NUnit.Framework.Test] public virtual void HistoryWithInvalidActionXmpMetaData() { - PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_4; + PdfAConformance conformance = PdfAConformance.PDF_A_4; byte[] bytes = File.ReadAllBytes(System.IO.Path.Combine(SOURCE_FOLDER + "xmp/xmpWithInvalidAction.xmp")); XMPMeta xmpMeta = XMPMetaFactory.Parse(new MemoryStream(bytes)); PdfDictionary catalog = new PdfDictionary(); MemoryStream baos = new MemoryStream(); XMPMetaFactory.Serialize(xmpMeta, baos); catalog.Put(PdfName.Metadata, new PdfStream(baos.ToArray())); - Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => new PdfA4Checker(conformanceLevel + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => new PdfA4Checker(conformance ).CheckMetaData(catalog)); NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(PdfaExceptionMessageConstant.XMP_METADATA_HISTORY_ENTRY_SHALL_CONTAIN_KEY , "stEvt:action"), e.Message); @@ -473,22 +473,22 @@ public virtual void HistoryWithInvalidActionXmpMetaData() { [NUnit.Framework.Test] public virtual void HistoryWithEmptyEntryXmpMetaData() { - PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_4; + PdfAConformance conformance = PdfAConformance.PDF_A_4; byte[] bytes = File.ReadAllBytes(System.IO.Path.Combine(SOURCE_FOLDER + "xmp/xmpWithEmpty.xmp")); XMPMeta xmpMeta = XMPMetaFactory.Parse(new MemoryStream(bytes)); PdfDictionary catalog = new PdfDictionary(); MemoryStream baos = new MemoryStream(); XMPMetaFactory.Serialize(xmpMeta, baos); catalog.Put(PdfName.Metadata, new PdfStream(baos.ToArray())); - new PdfA4Checker(conformanceLevel).CheckMetaData(catalog); + new PdfA4Checker(conformance).CheckMetaData(catalog); NUnit.Framework.Assert.IsTrue(true); } [NUnit.Framework.Test] public virtual void TestNullConformancePropertyPDFA4F() { String outPdf = DESTINATION_FOLDER + "testNullConformancePropertyPDFA4F.pdf"; - PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_4F; - GeneratePdfADocument(conformanceLevel, outPdf, (doc) => { + PdfAConformance conformance = PdfAConformance.PDF_A_4F; + GeneratePdfADocument(conformance, outPdf, (doc) => { PdfFileSpec fs = PdfFileSpec.CreateEmbeddedFileSpec(doc, "file".GetBytes(), "description", "file.txt", null , null, null); doc.AddFileAttachment("file.txt", fs); @@ -505,7 +505,7 @@ public virtual void TestNullConformancePropertyPDFA4F() { } )); Exception e_1 = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { - new PdfA4Checker(conformanceLevel).CheckMetaData(catalog); + new PdfA4Checker(conformance).CheckMetaData(catalog); } ); NUnit.Framework.Assert.AreEqual(PdfaExceptionMessageConstant.XMP_METADATA_HEADER_SHALL_CONTAIN_VERSION_IDENTIFIER_CONFORMANCE @@ -516,9 +516,9 @@ public virtual void TestNullConformancePropertyPDFA4F() { public virtual void PdfA4DocumentMetaDataIsNotUTF8Encoded() { String outPdf = DESTINATION_FOLDER + "metadataNotUTF8.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm" - ))); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm")) + ); doc.AddNewPage(); byte[] bytes = File.ReadAllBytes(System.IO.Path.Combine(SOURCE_FOLDER + "xmp/xmpWithEmpty.xmp")); XMPMeta xmpMeta = XMPMetaFactory.Parse(new MemoryStream(bytes)); @@ -537,9 +537,9 @@ public virtual void PdfA4DocumentPageMetaDataIsNotUTF8Encoded() { byte[] bytes = File.ReadAllBytes(System.IO.Path.Combine(SOURCE_FOLDER + "encodedXmp.xmp")); String outPdf = DESTINATION_FOLDER + "metadataNotUTF8.pdf"; PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_4, new PdfOutputIntent("Custom", "" - , "http://www.color.org", "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm" - ))); + PdfADocument doc = new PdfADocument(writer, PdfAConformance.PDF_A_4, new PdfOutputIntent("Custom", "", "http://www.color.org" + , "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm")) + ); doc.AddNewPage(); doc.GetPage(1).SetXmpMetadata(bytes); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { @@ -549,13 +549,13 @@ public virtual void PdfA4DocumentPageMetaDataIsNotUTF8Encoded() { NUnit.Framework.Assert.AreEqual(PdfaExceptionMessageConstant.INVALID_XMP_METADATA_ENCODING, e.Message); } - private void GeneratePdfADocument(PdfAConformanceLevel conformanceLevel, String outPdf, Action consumer) { + private void GeneratePdfADocument(PdfAConformance conformance, String outPdf, Action consumer + ) { if (outPdf == null) { NUnit.Framework.Assert.Fail(); } PdfWriter writer = new PdfWriter(outPdf, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)); - PdfADocument doc = new PdfADocument(writer, conformanceLevel, new PdfOutputIntent("Custom", "", "http://www.color.org" + PdfADocument doc = new PdfADocument(writer, conformance, new PdfOutputIntent("Custom", "", "http://www.color.org" , "sRGB IEC61966-2.1", FileUtil.GetInputStreamForFile(SOURCE_FOLDER + "sRGB Color Space Profile.icm")) ); doc.AddNewPage(); @@ -564,7 +564,7 @@ private void GeneratePdfADocument(PdfAConformanceLevel conformanceLevel, String } private static PdfDictionary GenerateCustomXmpCatalog(PdfADocument pdfADocument, Action action) { - XMPMeta xmpMeta = XMPMetaFactory.Parse(new MemoryStream(pdfADocument.GetXmpMetadata())); + XMPMeta xmpMeta = pdfADocument.GetXmpMetadata(); PdfDictionary catalog = pdfADocument.GetCatalog().GetPdfObject(); MemoryStream baos = new MemoryStream(); action(xmpMeta); diff --git a/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfACheckerTest.cs b/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfACheckerTest.cs index ad34f837da..64c5456cce 100644 --- a/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfACheckerTest.cs +++ b/itext.tests/itext.pdfa.tests/itext/pdfa/checker/PdfACheckerTest.cs @@ -76,7 +76,7 @@ public virtual void CheckAppearanceStreamsWithCycle() { [NUnit.Framework.Test] public virtual void CheckContentStreamPdfAText() { //TODO adapt after DEVSIX-5759 is fixed - PdfA1Checker testChecker = new PdfA1Checker(PdfAConformanceLevel.PDF_A_1B); + PdfA1Checker testChecker = new PdfA1Checker(PdfAConformance.PDF_A_1B); PdfADocument pdfa = new PdfADocument(new PdfReader(new FileInfo(SOURCE_FOLDER + "InlineImagesPdfA.pdf")), new PdfWriter(new MemoryStream()).SetSmartMode(true)); PdfStream firstContentStream = pdfa.GetPage(1).GetFirstContentStream(); @@ -90,14 +90,17 @@ protected internal EmptyPdfAChecker() : base(null) { } + public override void CheckSignatureType(bool isCAdES) { + } + public override void CheckCanvasStack(char stackOperation) { } public override void CheckInlineImage(PdfStream inlineImage, PdfDictionary currentColorSpaces) { } - public override void CheckColor(Color color, PdfDictionary currentColorSpaces, bool? fill, PdfStream contentStream - ) { + public override void CheckColor(CanvasGraphicsState gState, Color color, PdfDictionary currentColorSpaces, + bool? fill, PdfStream contentStream) { } public override void CheckColorSpace(PdfColorSpace colorSpace, PdfObject @object, PdfDictionary currentColorSpaces @@ -119,6 +122,12 @@ public override void CheckFont(PdfFont pdfFont) { public override void CheckXrefTable(PdfXrefTable xrefTable) { } + public override void CheckCrypto(PdfObject crypto) { + } + + public override void CheckText(String text, PdfFont font) { + } + protected internal override void CheckContentStream(PdfStream contentStream) { } @@ -146,7 +155,8 @@ protected internal override void CheckAnnotation(PdfDictionary annotDic) { protected internal override void CheckCatalogValidEntries(PdfDictionary catalogDict) { } - protected internal override void CheckColorsUsages() { + protected internal override void CheckPageColorsUsages(PdfDictionary pageDict, PdfDictionary pageResources + ) { } protected internal override void CheckImage(PdfStream image, PdfDictionary currentColorSpaces) { diff --git a/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfA1AnnotationCheckTest/cmp_pdfA1a_annotationCheckTest09.pdf b/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfA1AnnotationCheckTest/cmp_pdfA1a_annotationCheckTest09.pdf index 1d94298d1b..19f2793d77 100644 Binary files a/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfA1AnnotationCheckTest/cmp_pdfA1a_annotationCheckTest09.pdf and b/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfA1AnnotationCheckTest/cmp_pdfA1a_annotationCheckTest09.pdf differ diff --git a/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfA2GraphicsCheckTest/cmp_pdfA2b_colorCheckTest4.pdf b/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfA2GraphicsCheckTest/cmp_pdfA2b_colorCheckTest4.pdf deleted file mode 100644 index ca0fc0546f..0000000000 Binary files a/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfA2GraphicsCheckTest/cmp_pdfA2b_colorCheckTest4.pdf and /dev/null differ diff --git a/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfA2GraphicsCheckTest/cmp_pdfA2b_colorCheckTest6.pdf b/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfA2GraphicsCheckTest/cmp_pdfA2b_colorCheckTest6.pdf deleted file mode 100644 index 2a5ba75b8a..0000000000 Binary files a/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfA2GraphicsCheckTest/cmp_pdfA2b_colorCheckTest6.pdf and /dev/null differ diff --git a/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfA2GraphicsCheckTest/cmp_pdfA2b_colorCheckTest7.pdf b/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfA2GraphicsCheckTest/cmp_pdfA2b_colorCheckTest7.pdf deleted file mode 100644 index 89885ae339..0000000000 Binary files a/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfA2GraphicsCheckTest/cmp_pdfA2b_colorCheckTest7.pdf and /dev/null differ diff --git a/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfA4ActionCheckTest/cmp_GoTo3Dview.pdf b/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfA4ActionCheckTest/cmp_GoTo3Dview.pdf deleted file mode 100644 index aa615c7892..0000000000 Binary files a/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfA4ActionCheckTest/cmp_GoTo3Dview.pdf and /dev/null differ diff --git a/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfA4ActionCheckTest/cmp_pdfA4ESetOcgState.pdf b/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfA4ActionCheckTest/cmp_pdfA4ESetOcgState.pdf deleted file mode 100644 index 7524fd4868..0000000000 Binary files a/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfA4ActionCheckTest/cmp_pdfA4ESetOcgState.pdf and /dev/null differ diff --git a/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfA4CatalogCheckTest/cmp_invalidOperatorTest.pdf b/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfA4CatalogCheckTest/cmp_invalidOperatorTest.pdf deleted file mode 100644 index 0f1058f591..0000000000 Binary files a/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfA4CatalogCheckTest/cmp_invalidOperatorTest.pdf and /dev/null differ diff --git a/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfAFormFieldTest/cmp_pdfA1DocWithPdfA1ChoiceField.pdf b/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfAFormFieldTest/cmp_pdfA1DocWithPdfA1ChoiceField.pdf index 1e27c9906c..7936559ba2 100644 Binary files a/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfAFormFieldTest/cmp_pdfA1DocWithPdfA1ChoiceField.pdf and b/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfAFormFieldTest/cmp_pdfA1DocWithPdfA1ChoiceField.pdf differ diff --git a/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfAFormFieldTest/cmp_pdfA1DocWithPdfA1ComboBoxField.pdf b/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfAFormFieldTest/cmp_pdfA1DocWithPdfA1ComboBoxField.pdf index 619b096a9f..4d84455d50 100644 Binary files a/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfAFormFieldTest/cmp_pdfA1DocWithPdfA1ComboBoxField.pdf and b/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfAFormFieldTest/cmp_pdfA1DocWithPdfA1ComboBoxField.pdf differ diff --git a/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfAFormFieldTest/cmp_pdfA1DocWithPdfA1ListField.pdf b/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfAFormFieldTest/cmp_pdfA1DocWithPdfA1ListField.pdf index d7bfead506..abec3ad555 100644 Binary files a/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfAFormFieldTest/cmp_pdfA1DocWithPdfA1ListField.pdf and b/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfAFormFieldTest/cmp_pdfA1DocWithPdfA1ListField.pdf differ diff --git a/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfAFormFieldTest/cmp_testButtonNoFont.pdf b/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfAFormFieldTest/cmp_testButtonNoFont.pdf deleted file mode 100644 index c0bd611a0b..0000000000 Binary files a/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfAFormFieldTest/cmp_testButtonNoFont.pdf and /dev/null differ diff --git a/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfAFormFieldTest/cmp_testComboBoxNoFont.pdf b/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfAFormFieldTest/cmp_testComboBoxNoFont.pdf deleted file mode 100644 index 331f19c66f..0000000000 Binary files a/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfAFormFieldTest/cmp_testComboBoxNoFont.pdf and /dev/null differ diff --git a/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfAFormFieldTest/cmp_testMultipleCombinationsDefaultFont.pdf b/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfAFormFieldTest/cmp_testMultipleCombinationsDefaultFont.pdf deleted file mode 100644 index 791ee94be5..0000000000 Binary files a/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfAFormFieldTest/cmp_testMultipleCombinationsDefaultFont.pdf and /dev/null differ diff --git a/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfAFormFieldTest/cmp_testMultipleCombinationsWriteAndLoad.pdf b/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfAFormFieldTest/cmp_testMultipleCombinationsWriteAndLoad.pdf index 28535fd9c8..d570819439 100644 Binary files a/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfAFormFieldTest/cmp_testMultipleCombinationsWriteAndLoad.pdf and b/itext.tests/itext.pdfa.tests/resources/itext/pdfa/cmp/PdfAFormFieldTest/cmp_testMultipleCombinationsWriteAndLoad.pdf differ diff --git a/itext.tests/itext.pdftest.tests/Properties/AssemblyInfo.cs b/itext.tests/itext.pdftest.tests/Properties/AssemblyInfo.cs index 43456058ec..2a12bba3c7 100644 --- a/itext.tests/itext.pdftest.tests/Properties/AssemblyInfo.cs +++ b/itext.tests/itext.pdftest.tests/Properties/AssemblyInfo.cs @@ -15,6 +15,6 @@ [assembly: Guid("f9880dc4-f015-4413-af86-66d0e9512774")] -[assembly: AssemblyVersion("8.0.5.0")] -[assembly: AssemblyFileVersion("8.0.5.0")] -[assembly: AssemblyInformationalVersion("8.0.5")] +[assembly: AssemblyVersion("9.0.0.0")] +[assembly: AssemblyFileVersion("9.0.0.0")] +[assembly: AssemblyInformationalVersion("9.0.0")] diff --git a/itext.tests/itext.pdfua.tests/Properties/AssemblyInfo.cs b/itext.tests/itext.pdfua.tests/Properties/AssemblyInfo.cs index abf5afc849..cfb7ab9639 100644 --- a/itext.tests/itext.pdfua.tests/Properties/AssemblyInfo.cs +++ b/itext.tests/itext.pdfua.tests/Properties/AssemblyInfo.cs @@ -15,9 +15,9 @@ [assembly: Guid("f542854e-7f6b-4207-b6ca-004a5d266e65")] -[assembly: AssemblyVersion("8.0.5.0")] -[assembly: AssemblyFileVersion("8.0.5.0")] -[assembly: AssemblyInformationalVersion("8.0.5")] +[assembly: AssemblyVersion("9.0.0.0")] +[assembly: AssemblyFileVersion("9.0.0.0")] +[assembly: AssemblyInformationalVersion("9.0.0")] #if !NETSTANDARD2_0 [assembly: NUnit.Framework.Timeout(300000)] diff --git a/itext.tests/itext.pdfua.tests/itext.pdfua.tests.csproj b/itext.tests/itext.pdfua.tests/itext.pdfua.tests.csproj index 920838aeed..77b9aa70a7 100644 --- a/itext.tests/itext.pdfua.tests/itext.pdfua.tests.csproj +++ b/itext.tests/itext.pdfua.tests/itext.pdfua.tests.csproj @@ -39,7 +39,7 @@ - + diff --git a/itext.tests/itext.pdfua.tests/itext/pdfua/PdfUAAnnotationsTest.cs b/itext.tests/itext.pdfua.tests/itext/pdfua/PdfUAAnnotationsTest.cs index fca0c37e40..9b23a93c7c 100644 --- a/itext.tests/itext.pdfua.tests/itext/pdfua/PdfUAAnnotationsTest.cs +++ b/itext.tests/itext.pdfua.tests/itext/pdfua/PdfUAAnnotationsTest.cs @@ -72,12 +72,12 @@ public virtual void InitializeFramework() { [NUnit.Framework.Test] public virtual void Ua1LinkAnnotNoDirectChildOfAnnotTest() { - framework.AddSuppliers(new _Generator_123()); + framework.AddSuppliers(new _Generator_118()); framework.AssertBothValid("ua1LinkAnnotNoDirectChildOfAnnotTest"); } - private sealed class _Generator_123 : UaValidationTestFramework.Generator { - public _Generator_123() { + private sealed class _Generator_118 : UaValidationTestFramework.Generator { + public _Generator_118() { } public IBlockElement Generate() { @@ -98,7 +98,7 @@ public virtual void Ua1WidgetAnnotNoDirectChildOfAnnotTest() { framework.AddBeforeGenerationHook((pdfDoc) => { PdfAcroForm acroForm = PdfFormCreator.GetAcroForm(pdfDoc, true); PdfButtonFormField checkBox = new CheckBoxFormFieldBuilder(pdfDoc, "checkbox").SetWidgetRectangle(new Rectangle - (10, 650, 40, 20)).SetGenericConformanceLevel(PdfUAConformanceLevel.PDFUA_1).CreateCheckBox(); + (10, 650, 40, 20)).SetConformance(PdfConformance.PDF_UA_1).CreateCheckBox(); checkBox.SetAlternativeName("widget"); acroForm.AddField(checkBox); } @@ -350,8 +350,7 @@ public virtual void Ua1PushBtnNestedWithinFormTest() { PdfAcroForm acroForm = PdfFormCreator.GetAcroForm(pdfDoc, true); // The rest of the tests for widgets can be found in com.itextpdf.pdfua.checkers.PdfUAFormFieldsTest PdfFormField button = new PushButtonFormFieldBuilder(pdfDoc, "push button").SetWidgetRectangle(new Rectangle - (10, 650, 40, 20)).SetGenericConformanceLevel(PdfUAConformanceLevel.PDFUA_1).SetFont(LoadFont()).CreatePushButton - (); + (10, 650, 40, 20)).SetConformance(PdfConformance.PDF_UA_1).SetFont(LoadFont()).CreatePushButton(); button.SetAlternativeName("widget"); acroForm.AddField(button); } diff --git a/itext.tests/itext.pdfua.tests/itext/pdfua/PdfUADocumentTest.cs b/itext.tests/itext.pdfua.tests/itext/pdfua/PdfUADocumentTest.cs new file mode 100644 index 0000000000..c841e499d1 --- /dev/null +++ b/itext.tests/itext.pdfua.tests/itext/pdfua/PdfUADocumentTest.cs @@ -0,0 +1,53 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using System.IO; +using iText.Kernel.Pdf; +using iText.Pdfua.Logs; +using iText.Test; +using iText.Test.Attributes; + +namespace iText.Pdfua { + [NUnit.Framework.Category("IntegrationTest")] + public class PdfUADocumentTest : ExtendedITextTest { + private static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + .CurrentContext.TestDirectory) + "/resources/itext/pdfua/PdfUADocumentTest/"; + + [NUnit.Framework.Test] + [LogMessage(PdfUALogMessageConstants.PDF_TO_PDF_UA_CONVERSION_IS_NOT_SUPPORTED, LogLevel = LogLevelConstants + .WARN)] + public virtual void OpenNotUaDocumentTest() { + NUnit.Framework.Assert.DoesNotThrow(() => new PdfUADocument(new PdfReader(SOURCE_FOLDER + "usualPdf.pdf"), + new PdfWriter(new MemoryStream()), new PdfUAConfig(PdfUAConformance.PDF_UA_1, "simple doc", "eng"))); + } + + [NUnit.Framework.Test] + [LogMessage(PdfUALogMessageConstants.WRITER_PROPERTIES_PDF_VERSION_WAS_OVERRIDDEN, LogLevel = LogLevelConstants + .WARN)] + public virtual void SettingWrongPdfVersionTest() { + PdfUADocument doc = new PdfUADocument(new PdfWriter(new MemoryStream(), new WriterProperties().SetPdfVersion + (PdfVersion.PDF_1_4)), new PdfUAConfig(PdfUAConformance.PDF_UA_1, "en-us", "title")); + doc.Close(); + } + } +} diff --git a/itext.tests/itext.pdfua.tests/itext/pdfua/PdfUAMetadataUnitTest.cs b/itext.tests/itext.pdfua.tests/itext/pdfua/PdfUAMetadataUnitTest.cs index 463a23630b..d65977270d 100644 --- a/itext.tests/itext.pdfua.tests/itext/pdfua/PdfUAMetadataUnitTest.cs +++ b/itext.tests/itext.pdfua.tests/itext/pdfua/PdfUAMetadataUnitTest.cs @@ -26,6 +26,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Pdfua.Checkers; using iText.Pdfua.Exceptions; using iText.Test; +using iText.Test.Attributes; namespace iText.Pdfua { [NUnit.Framework.Category("UnitTest")] @@ -51,18 +52,20 @@ public virtual void DocumentWithNoTitleInMetadataTest() { [NUnit.Framework.Test] public virtual void DocumentWithInvalidMetadataVersionTest() { - using (PdfDocument pdfDocument = new PdfUATestPdfDocument(new PdfWriter(new MemoryStream()))) { - pdfDocument.AddNewPage(); - PdfCatalog catalog = pdfDocument.GetCatalog(); - byte[] bytes = File.ReadAllBytes(System.IO.Path.Combine(SOURCE_FOLDER + "invalid_version_metadata.xmp")); - catalog.Put(PdfName.Metadata, new PdfStream(bytes)); - PdfUAMetadataUnitTest.PdfUA1MetadataChecker checker = new PdfUAMetadataUnitTest.PdfUA1MetadataChecker(pdfDocument - ); - Exception e = NUnit.Framework.Assert.Catch(typeof(PdfUAConformanceException), () => checker.CheckMetadata( - catalog)); - NUnit.Framework.Assert.AreEqual(PdfUAExceptionMessageConstants.METADATA_SHALL_CONTAIN_UA_VERSION_IDENTIFIER - , e.Message); - } + PdfDocument pdfDocument = new PdfUATestPdfDocument(new PdfWriter(new MemoryStream())); + pdfDocument.AddNewPage(); + PdfCatalog catalog = pdfDocument.GetCatalog(); + byte[] bytes = File.ReadAllBytes(System.IO.Path.Combine(SOURCE_FOLDER + "invalid_version_metadata.xmp")); + catalog.Put(PdfName.Metadata, new PdfStream(bytes)); + PdfUAMetadataUnitTest.PdfUA1MetadataChecker checker = new PdfUAMetadataUnitTest.PdfUA1MetadataChecker(pdfDocument + ); + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfUAConformanceException), () => checker.CheckMetadata( + catalog)); + NUnit.Framework.Assert.AreEqual(PdfUAExceptionMessageConstants.METADATA_SHALL_CONTAIN_UA_VERSION_IDENTIFIER + , e.Message); + e = NUnit.Framework.Assert.Catch(typeof(PdfUAConformanceException), () => pdfDocument.Close()); + NUnit.Framework.Assert.AreEqual(PdfUAExceptionMessageConstants.METADATA_SHALL_CONTAIN_UA_VERSION_IDENTIFIER + , e.Message); } [NUnit.Framework.Test] @@ -98,27 +101,31 @@ public virtual void DocumentWithInvalidMetadataTypeTest() { [NUnit.Framework.Test] public virtual void DocumentWithInvalidPdfVersionTest() { - PdfDocument pdfDocument = new PdfUATestPdfDocument(new PdfWriter(new MemoryStream(), new WriterProperties( - ).SetPdfVersion(PdfVersion.PDF_2_0))); + PdfUAMetadataUnitTest.PdfDocumentCustomVersion pdfDocument = new PdfUAMetadataUnitTest.PdfDocumentCustomVersion + (new PdfWriter(new MemoryStream()), new PdfUAConfig(PdfUAConformance.PDF_UA_1, "en-us", "title")); + pdfDocument.SetPdfVersion(PdfVersion.PDF_2_0); pdfDocument.AddNewPage(); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfUAConformanceException), () => pdfDocument.Close()); NUnit.Framework.Assert.AreEqual(PdfUAExceptionMessageConstants.INVALID_PDF_VERSION, e.Message); } [NUnit.Framework.Test] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.EXCEPTION_WHILE_UPDATING_XMPMETADATA)] public virtual void DocumentWithBrokenMetadataTest() { - using (PdfDocument pdfDocument = new PdfUATestPdfDocument(new PdfWriter(new MemoryStream()))) { - pdfDocument.AddNewPage(); - PdfCatalog catalog = pdfDocument.GetCatalog(); - byte[] bytes = File.ReadAllBytes(System.IO.Path.Combine(SOURCE_FOLDER + "invalid_metadata.xmp")); - catalog.Put(PdfName.Metadata, new PdfStream(bytes)); - PdfUAMetadataUnitTest.PdfUA1MetadataChecker checker = new PdfUAMetadataUnitTest.PdfUA1MetadataChecker(pdfDocument - ); - Exception e = NUnit.Framework.Assert.Catch(typeof(PdfUAConformanceException), () => checker.CheckMetadata( - catalog)); - NUnit.Framework.Assert.AreEqual(PdfUAExceptionMessageConstants.DOCUMENT_SHALL_CONTAIN_XMP_METADATA_STREAM, - e.Message); - } + PdfDocument pdfDocument = new PdfUATestPdfDocument(new PdfWriter(new MemoryStream())); + pdfDocument.AddNewPage(); + PdfCatalog catalog = pdfDocument.GetCatalog(); + byte[] bytes = File.ReadAllBytes(System.IO.Path.Combine(SOURCE_FOLDER + "invalid_metadata.xmp")); + catalog.Put(PdfName.Metadata, new PdfStream(bytes)); + PdfUAMetadataUnitTest.PdfUA1MetadataChecker checker = new PdfUAMetadataUnitTest.PdfUA1MetadataChecker(pdfDocument + ); + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfUAConformanceException), () => checker.CheckMetadata( + catalog)); + NUnit.Framework.Assert.AreEqual(PdfUAExceptionMessageConstants.DOCUMENT_SHALL_CONTAIN_XMP_METADATA_STREAM, + e.Message); + e = NUnit.Framework.Assert.Catch(typeof(PdfUAConformanceException), () => pdfDocument.Close()); + NUnit.Framework.Assert.AreEqual(PdfUAExceptionMessageConstants.DOCUMENT_SHALL_CONTAIN_XMP_METADATA_STREAM, + e.Message); } private class PdfUA1MetadataChecker : PdfUA1Checker { @@ -133,5 +140,15 @@ protected internal override void CheckMetadata(PdfCatalog catalog) { base.CheckMetadata(catalog); } } + + private class PdfDocumentCustomVersion : PdfUADocument { + public PdfDocumentCustomVersion(PdfWriter writer, PdfUAConfig config) + : base(writer, config) { + } + + public virtual void SetPdfVersion(PdfVersion pdfVersion) { + this.pdfVersion = pdfVersion; + } + } } } diff --git a/itext.tests/itext.pdfua.tests/itext/pdfua/PdfUATaggedGridContainerTest.cs b/itext.tests/itext.pdfua.tests/itext/pdfua/PdfUATaggedGridContainerTest.cs new file mode 100644 index 0000000000..70a94de9a0 --- /dev/null +++ b/itext.tests/itext.pdfua.tests/itext/pdfua/PdfUATaggedGridContainerTest.cs @@ -0,0 +1,201 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using iText.Commons.Utils; +using iText.IO.Font; +using iText.Kernel.Colors; +using iText.Kernel.Font; +using iText.Kernel.Pdf; +using iText.Layout; +using iText.Layout.Borders; +using iText.Layout.Element; +using iText.Layout.Properties; +using iText.Layout.Properties.Grid; +using iText.Test; +using iText.Test.Pdfa; + +namespace iText.Pdfua { + // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf/ua validation on Android) + [NUnit.Framework.Category("IntegrationTest")] + public class PdfUATaggedGridContainerTest : ExtendedITextTest { + private static readonly String DESTINATION_FOLDER = NUnit.Framework.TestContext.CurrentContext.TestDirectory + + "/test/itext/pdfua/PdfUATaggedGridContainerTest/"; + + private static readonly String FONT = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + .CurrentContext.TestDirectory) + "/resources/itext/pdfua/font/FreeSans.ttf"; + + [NUnit.Framework.SetUp] + public virtual void Setup() { + CreateOrClearDestinationFolder(DESTINATION_FOLDER); + } + + [NUnit.Framework.Test] + public virtual void SimpleBorderBoxSizingTest() { + String outputPdf = DESTINATION_FOLDER + "border.pdf"; + PdfUATestPdfDocument doc = new PdfUATestPdfDocument(new PdfWriter(outputPdf)); + Document document = new Document(doc); + PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.WINANSI, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED + ); + document.SetFont(font); + GridContainer gridContainer0 = CreateGridBoxWithText(); + document.Add(new Paragraph("BOX_SIZING: BORDER_BOX")); + gridContainer0.SetProperty(Property.BOX_SIZING, BoxSizingPropertyValue.BORDER_BOX); + gridContainer0.SetBorder(new SolidBorder(ColorConstants.BLACK, 20)); + document.Add(gridContainer0); + document.Add(new Paragraph("BOX_SIZING: CONTENT_BOX")); + GridContainer gridContainer1 = CreateGridBoxWithText(); + gridContainer1.SetProperty(Property.BOX_SIZING, BoxSizingPropertyValue.CONTENT_BOX); + gridContainer1.SetBorder(new SolidBorder(ColorConstants.BLACK, 20)); + document.Add(gridContainer1); + document.Close(); + ValidateOutputPdf(outputPdf); + } + + [NUnit.Framework.Test] + public virtual void SimpleMarginTest() { + String outputPdf = DESTINATION_FOLDER + "margin.pdf"; + PdfUATestPdfDocument doc = new PdfUATestPdfDocument(new PdfWriter(outputPdf)); + Document document = new Document(doc); + PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.WINANSI, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED + ); + document.SetFont(font); + document.Add(new Paragraph("Validate Grid Container with Margin ")); + GridContainer gridContainer0 = CreateGridBoxWithText(); + gridContainer0.SetMarginTop(50); + gridContainer0.SetMarginBottom(100); + gridContainer0.SetMarginLeft(10); + gridContainer0.SetMarginRight(10); + document.Add(gridContainer0); + document.Close(); + ValidateOutputPdf(outputPdf); + } + + [NUnit.Framework.Test] + public virtual void SimplePaddingTest() { + String outputPdf = DESTINATION_FOLDER + "padding.pdf"; + PdfUATestPdfDocument doc = new PdfUATestPdfDocument(new PdfWriter(outputPdf)); + Document document = new Document(doc); + PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.WINANSI, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED + ); + document.SetFont(font); + document.Add(new Paragraph("Validate Grid Container with Padding")); + GridContainer gridContainer0 = CreateGridBoxWithText(); + gridContainer0.SetPaddingTop(50); + gridContainer0.SetPaddingBottom(100); + gridContainer0.SetPaddingLeft(10); + gridContainer0.SetPaddingRight(10); + document.Add(gridContainer0); + document.Close(); + ValidateOutputPdf(outputPdf); + } + + [NUnit.Framework.Test] + public virtual void SimpleBackgroundTest() { + String outputPdf = DESTINATION_FOLDER + "background.pdf"; + PdfUATestPdfDocument doc = new PdfUATestPdfDocument(new PdfWriter(outputPdf)); + Document document = new Document(doc); + PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.WINANSI, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED + ); + document.SetFont(font); + document.Add(new Paragraph("Validate Grid Container with Background")); + GridContainer gridContainer0 = CreateGridBoxWithText(); + gridContainer0.SetBackgroundColor(ColorConstants.RED); + document.Add(gridContainer0); + document.Close(); + ValidateOutputPdf(outputPdf); + } + + [NUnit.Framework.Test] + public virtual void EmptyGridContainerTest() { + String outputPdf = DESTINATION_FOLDER + "emptyGridContainer.pdf"; + PdfUATestPdfDocument doc = new PdfUATestPdfDocument(new PdfWriter(outputPdf)); + Document document = new Document(doc); + GridContainer gridContainer0 = new GridContainer(); + gridContainer0.SetProperty(Property.COLUMN_GAP_BORDER, null); + gridContainer0.SetBackgroundColor(ColorConstants.RED); + gridContainer0.SetProperty(Property.GRID_TEMPLATE_COLUMNS, JavaUtil.ArraysAsList((TemplateValue)new PointValue + (150.0f), (TemplateValue)new PointValue(150.0f), (TemplateValue)new PointValue(150.0f))); + gridContainer0.SetProperty(Property.COLUMN_GAP, 12.0f); + document.Add(gridContainer0); + document.Close(); + ValidateOutputPdf(outputPdf); + } + + private void ValidateOutputPdf(String outputPdf) { + NUnit.Framework.Assert.IsNull(new VeraPdfValidator().Validate(outputPdf)); + } + + // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf/ua validation on Android) + private GridContainer CreateGridBoxWithText() { + GridContainer gridContainer0 = new GridContainer(); + gridContainer0.SetProperty(Property.COLUMN_GAP_BORDER, null); + gridContainer0.SetProperty(Property.GRID_TEMPLATE_COLUMNS, JavaUtil.ArraysAsList((TemplateValue)new PointValue + (150.0f), (TemplateValue)new PointValue(150.0f), (TemplateValue)new PointValue(150.0f))); + gridContainer0.SetProperty(Property.COLUMN_GAP, 12.0f); + Div div1 = new Div(); + div1.SetBackgroundColor(ColorConstants.YELLOW); + div1.SetProperty(Property.COLUMN_GAP_BORDER, null); + div1.SetProperty(Property.COLUMN_GAP, 12.0f); + Paragraph paragraph2 = new Paragraph(); + Text text3 = new Text("One"); + paragraph2.Add(text3); + div1.Add(paragraph2); + gridContainer0.Add(div1); + Div div4 = new Div(); + div4.SetProperty(Property.COLUMN_GAP_BORDER, null); + div4.SetProperty(Property.COLUMN_GAP, 12.0f); + Paragraph paragraph5 = new Paragraph(); + Text text6 = new Text("Two"); + paragraph5.Add(text6); + div4.Add(paragraph5); + gridContainer0.Add(div4); + Div div7 = new Div(); + div7.SetBackgroundColor(ColorConstants.GREEN); + div7.SetProperty(Property.COLUMN_GAP_BORDER, null); + div7.SetProperty(Property.COLUMN_GAP, 12.0f); + Paragraph paragraph8 = new Paragraph(); + Text text9 = new Text("Three"); + paragraph8.Add(text9); + div7.Add(paragraph8); + gridContainer0.Add(div7); + Div div10 = new Div(); + div10.SetBackgroundColor(ColorConstants.CYAN); + div10.SetProperty(Property.COLUMN_GAP_BORDER, null); + div10.SetProperty(Property.COLUMN_GAP, 12.0f); + Paragraph paragraph11 = new Paragraph(); + Text text12 = new Text("Four"); + paragraph11.Add(text12); + div10.Add(paragraph11); + gridContainer0.Add(div10); + Div div13 = new Div(); + div13.SetProperty(Property.COLUMN_GAP_BORDER, null); + div13.SetProperty(Property.COLUMN_GAP, 12.0f); + Paragraph paragraph14 = new Paragraph(); + Text text15 = new Text("Five"); + paragraph14.Add(text15); + div13.Add(paragraph14); + gridContainer0.Add(div13); + return gridContainer0; + } + } +} diff --git a/itext.tests/itext.pdfua.tests/itext/pdfua/PdfUATestPdfDocument.cs b/itext.tests/itext.pdfua.tests/itext/pdfua/PdfUATestPdfDocument.cs index 67e5377103..9939cfa818 100644 --- a/itext.tests/itext.pdfua.tests/itext/pdfua/PdfUATestPdfDocument.cs +++ b/itext.tests/itext.pdfua.tests/itext/pdfua/PdfUATestPdfDocument.cs @@ -42,7 +42,7 @@ public PdfUATestPdfDocument(PdfReader reader, PdfWriter writer, StampingProperti } private static PdfUAConfig CreateConfig() { - return new PdfUAConfig(PdfUAConformanceLevel.PDFUA_1, "English pangram", "en-US"); + return new PdfUAConfig(PdfUAConformance.PDF_UA_1, "English pangram", "en-US"); } } } diff --git a/itext.tests/itext.pdfua.tests/itext/pdfua/UaValidationTestFramework.cs b/itext.tests/itext.pdfua.tests/itext/pdfua/UaValidationTestFramework.cs index 45a5083800..966ad3d25c 100644 --- a/itext.tests/itext.pdfua.tests/itext/pdfua/UaValidationTestFramework.cs +++ b/itext.tests/itext.pdfua.tests/itext/pdfua/UaValidationTestFramework.cs @@ -26,7 +26,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Utils; using iText.IO.Util; using iText.Kernel.Pdf; -using iText.Kernel.Utils; +using iText.Kernel.Validation; using iText.Layout; using iText.Layout.Element; using iText.Pdfua.Exceptions; diff --git a/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUACanvasTest.cs b/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUACanvasTest.cs index 8d9d754778..750da8b8dd 100644 --- a/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUACanvasTest.cs +++ b/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUACanvasTest.cs @@ -178,6 +178,49 @@ public virtual void CheckPoint_01_005_TextGlyphLineContentIsTaggedButNotInTagTre , e.Message); } + [NUnit.Framework.Test] + public virtual void CheckPoint_01_005_TextGlyphLineInBadStructure() { + String outPdf = DESTINATION_FOLDER + "checkPoint_01_005_TextGlyphLineInBadStructure.pdf"; + PdfUATestPdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(outPdf)); + PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.WINANSI, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED + ); + PdfCanvas canvas = new _PdfCanvas_249(pdfDoc.AddNewPage()); + // disable the checkIsoConformance call check by simulating generating not tagged content + // same as in annotations of formfields. + GlyphLine glyphLine = font.CreateGlyphLine("Hello World!"); + TagTreePointer pointer = pdfDoc.GetTagStructureContext().GetAutoTaggingPointer(); + pointer.AddTag(StandardRoles.DIV); + pointer.SetPageForTagging(pdfDoc.GetFirstPage()); + canvas.SaveState(); + canvas.OpenTag(pointer.GetTagReference()); + canvas.OpenTag(new CanvasArtifact()); + pointer.AddTag(StandardRoles.P); + canvas.OpenTag(pointer.GetTagReference()); + canvas.SetFontAndSize(font, 12); + canvas.BeginText(); + canvas.MoveText(200, 200); + canvas.SetColor(ColorConstants.RED, true); + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfUAConformanceException), () => { + canvas.ShowText(glyphLine); + } + ); + NUnit.Framework.Assert.AreEqual(PdfUAExceptionMessageConstants.REAL_CONTENT_INSIDE_ARTIFACT_OR_VICE_VERSA, + e.Message); + } + + private sealed class _PdfCanvas_249 : PdfCanvas { + public _PdfCanvas_249(PdfPage baseArg1) + : base(baseArg1) { + } + + public override PdfCanvas OpenTag(CanvasTag tag) { + this.SetDrawingOnPage(false); + base.OpenTag(tag); + this.SetDrawingOnPage(true); + return this; + } + } + [NUnit.Framework.Test] public virtual void CheckPoint_01_005_TextGlyphLineContentIsArtifact() { String outPdf = DESTINATION_FOLDER + "01_005_TextGlyphLineContentIsArtifact.pdf"; diff --git a/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUACanvasXObjectTest.cs b/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUACanvasXObjectTest.cs new file mode 100644 index 0000000000..79d836d110 --- /dev/null +++ b/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUACanvasXObjectTest.cs @@ -0,0 +1,505 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using System.IO; +using iText.IO.Font; +using iText.IO.Image; +using iText.Kernel.Colors; +using iText.Kernel.Font; +using iText.Kernel.Geom; +using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Canvas; +using iText.Kernel.Pdf.Tagging; +using iText.Kernel.Pdf.Tagutils; +using iText.Kernel.Pdf.Xobject; +using iText.Kernel.Utils; +using iText.Layout; +using iText.Layout.Borders; +using iText.Layout.Element; +using iText.Layout.Logs; +using iText.Pdfua; +using iText.Pdfua.Exceptions; +using iText.Test; +using iText.Test.Attributes; +using iText.Test.Pdfa; + +namespace iText.Pdfua.Checkers { + // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf/ua validation on Android) + [NUnit.Framework.Category("IntegrationTest")] + public class PdfUACanvasXObjectTest : ExtendedITextTest { + private static readonly String DESTINATION_FOLDER = NUnit.Framework.TestContext.CurrentContext.TestDirectory + + "/test/itext/pdfua/PdfUACanvasXObjectTest/"; + + private static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + .CurrentContext.TestDirectory) + "/resources/itext/pdfua/PdfUACanvasXObjectTest/"; + + private static readonly String DOG = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + .CurrentContext.TestDirectory) + "/resources/itext/pdfua/img/DOG.bmp"; + + private static readonly String FONT = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + .CurrentContext.TestDirectory) + "/resources/itext/pdfua/font/FreeSans.ttf"; + + private UaValidationTestFramework framework; + + [NUnit.Framework.OneTimeSetUp] + public static void Before() { + CreateOrClearDestinationFolder(DESTINATION_FOLDER); + } + + [NUnit.Framework.SetUp] + public virtual void InitializeFramework() { + framework = new UaValidationTestFramework(DESTINATION_FOLDER); + } + + [NUnit.Framework.Test] + [LogMessage(LayoutLogMessageConstant.ELEMENT_DOES_NOT_FIT_AREA, Count = 1)] + public virtual void CopyPageAsFormXobjectWithTaggedPdf() { + String outPdf = DESTINATION_FOLDER + "xobjectTesting.pdf"; + String inputPdf = SOURCE_FOLDER + "cmp_manualPdfUaCreation.pdf"; + String cmpFIle = SOURCE_FOLDER + "cmp_xobjectTesting.pdf"; + PdfUATestPdfDocument doc = new PdfUATestPdfDocument(new PdfWriter(outPdf)); + PdfDocument inputDoc = new PdfDocument(new PdfReader(inputPdf)); + PdfFormXObject xObject = inputDoc.GetFirstPage().CopyAsFormXObject(doc); + Document document = new Document(doc); + Image img = new Image(xObject); + img.GetAccessibilityProperties().SetAlternateDescription("Some description"); + document.Add(img); + document.Close(); + doc.Close(); + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpFIle, DESTINATION_FOLDER, "diff_" + )); + VeraPdfValidator validator = new VeraPdfValidator(); + // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf/ua validation on Android) + // We expect verapdf to fail because we are embedding tagged content which contains artifacts + NUnit.Framework.Assert.IsNotNull("We expect vera pdf to fail, because we are embedding tagged content which contains artifacts into a tagged item" + , validator.Validate(outPdf)); + } + + // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf/ua validation on Android) + [NUnit.Framework.Test] + [LogMessage(LayoutLogMessageConstant.ELEMENT_DOES_NOT_FIT_AREA, Count = 1)] + public virtual void CopyPageAsFormXobjectWithUnTaggedContentButInvalidBecauseOfFont() { + //itext should thrown an exception here but it does not. + // because even if it's not tagged the inner content stream is not compliant as the font is not embeded + String outputPdf = DESTINATION_FOLDER + "copyPageAsFormXobjectWithUnTaggedPdf.pdf"; + String cmpFile = SOURCE_FOLDER + "cmp_copyPageAsFormXobjectWithUnTaggedPdf.pdf"; + MemoryStream os = new MemoryStream(); + PdfDocument dummyDoc = new PdfDocument(new PdfWriter(os)); + Document document = new Document(dummyDoc); + document.Add(new Paragraph("Hello World!")); + document.Close(); + PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(outputPdf)); + PdfFormXObject xObject = new PdfDocument(new PdfReader(new MemoryStream(os.ToArray()))).GetFirstPage().CopyAsFormXObject + (pdfDoc); + Image img = new Image(xObject); + img.GetAccessibilityProperties().SetAlternateDescription("Some description"); + Document doc = new Document(pdfDoc); + doc.Add(img); + doc.Close(); + pdfDoc.Close(); + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outputPdf, cmpFile, DESTINATION_FOLDER, "diff_" + )); + VeraPdfValidator validator = new VeraPdfValidator(); + // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf/ua validation on Android) + NUnit.Framework.Assert.IsNotNull("Fails are expected because the content inside the xobject isn't valid because of not embedded font, and iText doesn't parse the content streams" + , validator.Validate(outputPdf)); + } + + // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf/ua validation on Android) + [LogMessage(LayoutLogMessageConstant.ELEMENT_DOES_NOT_FIT_AREA, Count = 1)] + [NUnit.Framework.Test] + public virtual void CopyPageAsFormWithUntaggedContentAndCorrectFont() { + String outputPdf = DESTINATION_FOLDER + "copyPageAsFormWithCorrectFontXobjectWithUnTaggedPdf.pdf"; + String cmpFile = SOURCE_FOLDER + "cmp_copyPageAsFormWithCorrectFontXobjectWithUnTaggedPdf.pdf"; + MemoryStream os = new MemoryStream(); + PdfDocument dummyDoc = new PdfDocument(new PdfWriter(os)); + Document document = new Document(dummyDoc); + PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.WINANSI, PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED + ); + document.Add(new Paragraph("Hello World!").SetFont(font)); + document.Close(); + PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(outputPdf)); + PdfFormXObject xObject = new PdfDocument(new PdfReader(new MemoryStream(os.ToArray()))).GetFirstPage().CopyAsFormXObject + (pdfDoc); + Image img = new Image(xObject); + img.GetAccessibilityProperties().SetAlternateDescription("Some description"); + Document doc = new Document(pdfDoc); + doc.Add(img); + doc.Close(); + pdfDoc.Close(); + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outputPdf, cmpFile, DESTINATION_FOLDER, "diff_" + )); + VeraPdfValidator validator = new VeraPdfValidator(); + // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf/ua validation on Android) + NUnit.Framework.Assert.IsNull(validator.Validate(outputPdf)); + } + + // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf/ua validation on Android) + [NUnit.Framework.Test] + public virtual void ManuallyAddToCanvasWithUnTaggedContentButBadFont() { + String outputPdf = DESTINATION_FOLDER + "manuallyAddToCanvasWithUnTaggedPdf.pdf"; + String cmpFile = SOURCE_FOLDER + "cmp_manuallyAddToCanvasWithUnTaggedPdf.pdf"; + MemoryStream os = new MemoryStream(); + PdfDocument dummyDoc = new PdfDocument(new PdfWriter(os)); + Document document = new Document(dummyDoc); + document.Add(new Paragraph("Hello World!")); + document.Close(); + PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(outputPdf)); + PdfFormXObject xObject = new PdfDocument(new PdfReader(new MemoryStream(os.ToArray()))).GetFirstPage().CopyAsFormXObject + (pdfDoc); + PdfCanvas canvas = new PdfCanvas(pdfDoc.AddNewPage()); + canvas.BeginMarkedContent(PdfName.Artifact); + canvas.AddXObject(xObject); + canvas.EndMarkedContent(); + pdfDoc.Close(); + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outputPdf, cmpFile, DESTINATION_FOLDER, "diff_" + )); + VeraPdfValidator validator = new VeraPdfValidator(); + // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf/ua validation on Android) + NUnit.Framework.Assert.IsNotNull("Content of the xobject is not valid causing it to be an non compliant", + validator.Validate(outputPdf)); + } + + // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf/ua validation on Android) + [NUnit.Framework.Test] + public virtual void ManuallyAddToCanvasCorrectFontAndUnTaggedContent() { + framework.AddBeforeGenerationHook((pdfDoc) => { + try { + MemoryStream os = new MemoryStream(); + PdfDocument dummyDoc = new PdfDocument(new PdfWriter(os)); + Document document = new Document(dummyDoc); + PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.WINANSI, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED + ); + document.Add(new Paragraph("Hello World!").SetFont(font)); + document.Close(); + PdfFormXObject xObject = null; + xObject = new PdfDocument(new PdfReader(new MemoryStream(os.ToArray()))).GetFirstPage().CopyAsFormXObject( + pdfDoc); + PdfCanvas canvas = new PdfCanvas(pdfDoc.AddNewPage()); + TagTreePointer tagPointer = pdfDoc.GetTagStructureContext().GetAutoTaggingPointer().AddTag(StandardRoles.DIV + ); + tagPointer.SetPageForTagging(pdfDoc.GetPage(1)); + canvas.OpenTag(tagPointer.GetTagReference()); + canvas.AddXObject(xObject); + canvas.CloseTag(); + } + catch (System.IO.IOException) { + throw new Exception(); + } + } + ); + framework.AssertBothValid("manuallyAddToCanvasCorrectFontAndUnTaggedContent"); + } + + [NUnit.Framework.Test] + public virtual void ManuallyAddToCanvasAndCorrectFontAndArtifactUnTaggedContent() { + //Now we are again adding untagged content with some artifacts and embedded font's so we should also be fine + framework.AddBeforeGenerationHook((pdfDocument) => { + MemoryStream os = new MemoryStream(); + PdfDocument dummyDoc = new PdfDocument(new PdfWriter(os)); + Document document = new Document(dummyDoc); + try { + PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.WINANSI, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED + ); + document.Add(new Paragraph("Hello World!").SetFont(font).SetBorder(new SolidBorder(ColorConstants.CYAN, 2) + )); + document.Close(); + PdfFormXObject xObject = new PdfDocument(new PdfReader(new MemoryStream(os.ToArray()))).GetFirstPage().CopyAsFormXObject + (pdfDocument); + PdfCanvas canvas = new PdfCanvas(pdfDocument.AddNewPage()); + TagTreePointer tagPointer = pdfDocument.GetTagStructureContext().GetAutoTaggingPointer().AddTag(StandardRoles + .DIV); + tagPointer.SetPageForTagging(pdfDocument.GetPage(1)); + canvas.OpenTag(tagPointer.GetTagReference()); + canvas.AddXObject(xObject); + canvas.CloseTag(); + } + catch (System.IO.IOException) { + throw new Exception(); + } + } + ); + framework.AssertBothValid("manuallyAddToCanvasAndCorrectFontAndArtifactUnTaggedContent"); + } + + [NUnit.Framework.Test] + public virtual void ManuallyAddToCanvasAndCorrectFontAndArtifactTaggedContent() { + String outputPdf = DESTINATION_FOLDER + "manuallyAddToCanvasWithUnAndCorrectFontAndArtifactUnPdf.pdf"; + String cmpFile = SOURCE_FOLDER + "cmp_manuallyAddToCanvasWithUnAndCorrectFontUnAndArtifactPdf.pdf"; + MemoryStream os = new MemoryStream(); + PdfDocument dummyDoc = new PdfDocument(new PdfWriter(os)); + dummyDoc.SetTagged(); + Document document = new Document(dummyDoc); + PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.WINANSI, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED + ); + document.Add(new Paragraph("Hello World!").SetFont(font).SetBorder(new SolidBorder(ColorConstants.CYAN, 2) + )); + document.Close(); + PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(outputPdf)); + PdfFormXObject xObject = new PdfDocument(new PdfReader(new MemoryStream(os.ToArray()))).GetFirstPage().CopyAsFormXObject + (pdfDoc); + PdfCanvas canvas = new PdfCanvas(pdfDoc.AddNewPage()); + TagTreePointer tagPointer = pdfDoc.GetTagStructureContext().GetAutoTaggingPointer().AddTag(StandardRoles.DIV + ); + tagPointer.SetPageForTagging(pdfDoc.GetPage(1)); + canvas.OpenTag(tagPointer.GetTagReference()); + canvas.AddXObject(xObject); + canvas.CloseTag(); + pdfDoc.Close(); + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outputPdf, cmpFile, DESTINATION_FOLDER, "diff_" + )); + VeraPdfValidator validator = new VeraPdfValidator(); + // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf/ua validation on Android) + NUnit.Framework.Assert.IsNotNull("The content is non compliant because it contains both artifacts, and real content" + , validator.Validate(outputPdf)); + } + + // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf/ua validation on Android) + [NUnit.Framework.Test] + public virtual void ManuallyAddToCanvasAndCorrectFontAndArtifactTaggedContentInsideArtifact() { + // We are adding tagged content to an artifact. Looks like Verapdf doesn't check xobject stream at all because + // page content is marked as artifact. We think it's wrong though. + framework.AddBeforeGenerationHook((pdfDoc) => { + try { + MemoryStream os = new MemoryStream(); + PdfDocument dummyDoc = new PdfDocument(new PdfWriter(os)); + dummyDoc.SetTagged(); + Document document = new Document(dummyDoc); + PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.WINANSI, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED + ); + document.Add(new Paragraph("Hello World!").SetFont(font).SetBorder(new SolidBorder(ColorConstants.CYAN, 2) + )); + document.Close(); + PdfFormXObject xObject = new PdfDocument(new PdfReader(new MemoryStream(os.ToArray()))).GetFirstPage().CopyAsFormXObject + (pdfDoc); + PdfCanvas canvas = new PdfCanvas(pdfDoc.AddNewPage()); + canvas.OpenTag(new CanvasArtifact()); + canvas.AddXObject(xObject); + canvas.CloseTag(); + } + catch (System.IO.IOException) { + throw new Exception(); + } + } + ); + framework.AssertBothValid("manuallyAddToCanvasAndCorrectFontInsideArtifact"); + } + + [NUnit.Framework.Test] + public virtual void ManuallyAddToCanvasAndCorrectFontAndArtifactTaggedContentInsideUntaggedPageContent() { + MemoryStream os = new MemoryStream(); + PdfDocument dummyDoc = new PdfDocument(new PdfWriter(os)); + dummyDoc.SetTagged(); + Document document = new Document(dummyDoc); + PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.WINANSI, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED + ); + document.Add(new Paragraph("Hello World!").SetFont(font).SetBorder(new SolidBorder(ColorConstants.CYAN, 2) + )); + document.Close(); + dummyDoc.Close(); + framework.AddBeforeGenerationHook((pdfDocument) => { + PdfCanvas canvas = new PdfCanvas(pdfDocument.AddNewPage()); + PdfFormXObject xObject = null; + try { + xObject = new PdfDocument(new PdfReader(new MemoryStream(os.ToArray()))).GetFirstPage().CopyAsFormXObject( + pdfDocument); + } + catch (System.IO.IOException) { + throw new Exception(); + } + canvas.AddXObject(xObject); + } + ); + framework.AssertBothFail("untaggedAddXobject", PdfUAExceptionMessageConstants.TAG_HASNT_BEEN_ADDED_BEFORE_CONTENT_ADDING + , false); + } + + [NUnit.Framework.Test] + public virtual void ManuallyAddToCanvasAtLocationAndCorrectFontAndArtifactTaggedContentInsideUntaggedPageContent + () { + //We are adding untagged content we should throw an exception + MemoryStream os = new MemoryStream(); + PdfDocument dummyDoc = new PdfDocument(new PdfWriter(os)); + dummyDoc.SetTagged(); + Document document = new Document(dummyDoc); + PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.WINANSI, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED + ); + document.Add(new Paragraph("Hello World!").SetFont(font).SetBorder(new SolidBorder(ColorConstants.CYAN, 2) + )); + document.Close(); + dummyDoc.Close(); + framework.AddBeforeGenerationHook((pdfDocument) => { + PdfCanvas canvas = new PdfCanvas(pdfDocument.AddNewPage()); + PdfFormXObject xObject = null; + try { + xObject = new PdfDocument(new PdfReader(new MemoryStream(os.ToArray()))).GetFirstPage().CopyAsFormXObject( + pdfDocument); + } + catch (System.IO.IOException) { + throw new Exception(); + } + canvas.AddXObjectAt(xObject, 200f, 200f); + } + ); + framework.AssertBothFail("untaggedAddXobjectAt", PdfUAExceptionMessageConstants.TAG_HASNT_BEEN_ADDED_BEFORE_CONTENT_ADDING + , false); + } + + [NUnit.Framework.Test] + public virtual void ManuallyAddToCanvasAtLocationAndCorrectFontAndArtifactTaggedContentInsideUntaggedPageContenta + () { + //We are adding untagged content we should throw an exception + UaValidationTestFramework framework = new UaValidationTestFramework(DESTINATION_FOLDER); + MemoryStream os = new MemoryStream(); + PdfDocument dummyDoc = new PdfDocument(new PdfWriter(os)); + Document document = new Document(dummyDoc); + PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.WINANSI, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED + ); + document.Add(new Paragraph("Hello World!").SetFont(font).SetBorder(new SolidBorder(ColorConstants.CYAN, 2) + )); + document.Close(); + dummyDoc.Close(); + framework.AddBeforeGenerationHook((pdfDocument) => { + PdfCanvas canvas = new PdfCanvas(pdfDocument.AddNewPage()); + PdfFormXObject xObject = null; + try { + xObject = new PdfDocument(new PdfReader(new MemoryStream(os.ToArray()))).GetFirstPage().CopyAsFormXObject( + pdfDocument); + } + catch (System.IO.IOException) { + throw new Exception(); + } + canvas.AddXObjectFittedIntoRectangle(xObject, new Rectangle(200, 200, 200, 200)); + } + ); + framework.AssertBothFail("addXObjectFitted", PdfUAExceptionMessageConstants.TAG_HASNT_BEEN_ADDED_BEFORE_CONTENT_ADDING + , false); + } + + [NUnit.Framework.Test] + public virtual void ManuallyAddToCanvasAtLocationAndCorrectFontAndArtifactTaggedContentInsideUntaggedPageContentab + () { + //We are adding untagged content we should throw an exception + MemoryStream os = new MemoryStream(); + PdfDocument dummyDoc = new PdfDocument(new PdfWriter(os)); + Document document = new Document(dummyDoc); + PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.WINANSI, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED + ); + document.Add(new Paragraph("Hello World!").SetFont(font).SetBorder(new SolidBorder(ColorConstants.CYAN, 2) + )); + document.Close(); + dummyDoc.Close(); + framework.AddBeforeGenerationHook((pdfDocument) => { + PdfCanvas canvas = new PdfCanvas(pdfDocument.AddNewPage()); + PdfFormXObject xObject = null; + try { + xObject = new PdfDocument(new PdfReader(new MemoryStream(os.ToArray()))).GetFirstPage().CopyAsFormXObject( + pdfDocument); + } + catch (System.IO.IOException) { + throw new Exception(); + } + canvas.AddXObjectWithTransformationMatrix(xObject, 1, 1, 1, 1, 1, 1); + } + ); + framework.AssertBothFail("addXObjectWithTransfoMatrix", PdfUAExceptionMessageConstants.TAG_HASNT_BEEN_ADDED_BEFORE_CONTENT_ADDING + , false); + } + + [NUnit.Framework.Test] + public virtual void AddImageObjectNotInline() { + //We are adding untagged content we should throw an exception + framework.AddBeforeGenerationHook((pdfDocument) => { + PdfCanvas canvas = new PdfCanvas(pdfDocument.AddNewPage()); + ImageData imd = null; + try { + imd = ImageDataFactory.Create(DOG); + } + catch (System.IO.IOException) { + throw new Exception(); + } + canvas.AddImageAt(imd, 200, 200, false); + } + ); + framework.AssertBothFail("addIMageObjectNotInline", PdfUAExceptionMessageConstants.TAG_HASNT_BEEN_ADDED_BEFORE_CONTENT_ADDING + , false); + } + + [NUnit.Framework.Test] + public virtual void AddImageObjectInline() { + //We are adding untagged content we should throw an exception + framework.AddBeforeGenerationHook((pdfDocument) => { + PdfCanvas canvas = new PdfCanvas(pdfDocument.AddNewPage()); + ImageData imd = null; + try { + imd = ImageDataFactory.Create(DOG); + } + catch (System.IO.IOException) { + throw new Exception(); + } + canvas.AddImageAt(imd, 200, 200, false); + } + ); + framework.AssertBothFail("addIMageObjectInline", PdfUAExceptionMessageConstants.TAG_HASNT_BEEN_ADDED_BEFORE_CONTENT_ADDING + , false); + } + + [NUnit.Framework.Test] + public virtual void AddImageTranformationMatrix() { + //We are adding untagged content we should throw an exception + framework.AddBeforeGenerationHook((pdfDocument) => { + PdfCanvas canvas = new PdfCanvas(pdfDocument.AddNewPage()); + ImageData imd = null; + try { + imd = ImageDataFactory.Create(DOG); + } + catch (System.IO.IOException) { + throw new Exception(); + } + canvas.AddImageWithTransformationMatrix(imd, 1, 1, 1, 1, 1, 1, false); + } + ); + framework.AssertBothFail("addIMageObjectTransfo", PdfUAExceptionMessageConstants.TAG_HASNT_BEEN_ADDED_BEFORE_CONTENT_ADDING + , false); + } + + [NUnit.Framework.Test] + public virtual void AddImageFittedIntoRectangle() { + //We are adding untagged content we should throw an exception + framework.AddBeforeGenerationHook((pdfDocument) => { + PdfCanvas canvas = new PdfCanvas(pdfDocument.AddNewPage()); + ImageData imd = null; + try { + imd = ImageDataFactory.Create(DOG); + } + catch (System.IO.IOException) { + throw new Exception(); + } + canvas.AddImageFittedIntoRectangle(imd, new Rectangle(200, 200, 200, 200), false); + } + ); + framework.AssertBothFail("addImageFittedIntoRectangle", PdfUAExceptionMessageConstants.TAG_HASNT_BEEN_ADDED_BEFORE_CONTENT_ADDING + , false); + } + } +} diff --git a/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUAFormFieldsTest.cs b/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUAFormFieldsTest.cs index a93ec4c6dc..2a00492819 100644 --- a/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUAFormFieldsTest.cs +++ b/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUAFormFieldsTest.cs @@ -61,12 +61,12 @@ public virtual void SetUp() { [NUnit.Framework.Test] public virtual void TestCheckBox() { - framework.AddSuppliers(new _Generator_84()); + framework.AddSuppliers(new _Generator_95()); framework.AssertBothValid("testCheckBox.pdf"); } - private sealed class _Generator_84 : UaValidationTestFramework.Generator { - public _Generator_84() { + private sealed class _Generator_95 : UaValidationTestFramework.Generator { + public _Generator_95() { } public IBlockElement Generate() { @@ -76,17 +76,17 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestCheckBoxWithCustomAppearance() { - framework.AddSuppliers(new _Generator_95()); + framework.AddSuppliers(new _Generator_106()); framework.AssertBothValid("testCheckBoxWithCustomAppearance.pdf"); } - private sealed class _Generator_95 : UaValidationTestFramework.Generator { - public _Generator_95() { + private sealed class _Generator_106 : UaValidationTestFramework.Generator { + public _Generator_106() { } public IBlockElement Generate() { CheckBox cb = new CheckBox("name"); - cb.SetPdfConformanceLevel(PdfUAConformanceLevel.PDFUA_1); + cb.SetPdfConformance(PdfConformance.PDF_UA_1); cb.SetBorder(new SolidBorder(ColorConstants.MAGENTA, 2)); cb.SetBackgroundColor(ColorConstants.YELLOW); return cb; @@ -95,17 +95,17 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestCheckBoxChecked() { - framework.AddSuppliers(new _Generator_110()); + framework.AddSuppliers(new _Generator_121()); framework.AssertBothValid("testCheckBox"); } - private sealed class _Generator_110 : UaValidationTestFramework.Generator { - public _Generator_110() { + private sealed class _Generator_121 : UaValidationTestFramework.Generator { + public _Generator_121() { } public IBlockElement Generate() { CheckBox cb = new CheckBox("name"); - cb.SetPdfConformanceLevel(PdfUAConformanceLevel.PDFUA_1); + cb.SetPdfConformance(PdfConformance.PDF_UA_1); cb.SetChecked(true); return cb; } @@ -113,17 +113,17 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestCheckBoxCheckedAlternativeDescription() { - framework.AddSuppliers(new _Generator_124()); + framework.AddSuppliers(new _Generator_135()); framework.AssertBothValid("testCheckBoxCheckedAlternativeDescription"); } - private sealed class _Generator_124 : UaValidationTestFramework.Generator { - public _Generator_124() { + private sealed class _Generator_135 : UaValidationTestFramework.Generator { + public _Generator_135() { } public IBlockElement Generate() { CheckBox cb = new CheckBox("name"); - cb.SetPdfConformanceLevel(PdfUAConformanceLevel.PDFUA_1); + cb.SetPdfConformance(PdfConformance.PDF_UA_1); cb.GetAccessibilityProperties().SetAlternateDescription("Yello"); cb.SetChecked(true); return cb; @@ -132,17 +132,17 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestCheckBoxCheckedCustomAppearance() { - framework.AddSuppliers(new _Generator_139()); + framework.AddSuppliers(new _Generator_150()); framework.AssertBothValid("testCheckBoxCheckedCustomAppearance"); } - private sealed class _Generator_139 : UaValidationTestFramework.Generator { - public _Generator_139() { + private sealed class _Generator_150 : UaValidationTestFramework.Generator { + public _Generator_150() { } public IBlockElement Generate() { CheckBox cb = new CheckBox("name"); - cb.SetPdfConformanceLevel(PdfUAConformanceLevel.PDFUA_1); + cb.SetPdfConformance(PdfConformance.PDF_UA_1); cb.SetChecked(true); cb.SetBorder(new SolidBorder(ColorConstants.CYAN, 2)); cb.SetBackgroundColor(ColorConstants.GREEN); @@ -154,17 +154,17 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestCheckBoxInteractive() { - framework.AddSuppliers(new _Generator_157()); + framework.AddSuppliers(new _Generator_168()); framework.AssertBothValid("testCheckBoxInteractive"); } - private sealed class _Generator_157 : UaValidationTestFramework.Generator { - public _Generator_157() { + private sealed class _Generator_168 : UaValidationTestFramework.Generator { + public _Generator_168() { } public IBlockElement Generate() { CheckBox checkBox = (CheckBox)new CheckBox("name").SetInteractive(true); - checkBox.SetPdfConformanceLevel(PdfUAConformanceLevel.PDFUA_1); + checkBox.SetPdfConformance(PdfConformance.PDF_UA_1); checkBox.GetAccessibilityProperties().SetAlternateDescription("Alternative description"); return checkBox; } @@ -172,17 +172,17 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestCheckBoxInteractiveCustomAppearance() { - framework.AddSuppliers(new _Generator_171()); + framework.AddSuppliers(new _Generator_182()); framework.AssertBothValid("testCheckBoxInteractiveCustomAppearance"); } - private sealed class _Generator_171 : UaValidationTestFramework.Generator { - public _Generator_171() { + private sealed class _Generator_182 : UaValidationTestFramework.Generator { + public _Generator_182() { } public IBlockElement Generate() { CheckBox checkBox = (CheckBox)new CheckBox("name").SetInteractive(true); - checkBox.SetPdfConformanceLevel(PdfUAConformanceLevel.PDFUA_1); + checkBox.SetPdfConformance(PdfConformance.PDF_UA_1); checkBox.GetAccessibilityProperties().SetAlternateDescription("Alternative description"); checkBox.SetBorder(new SolidBorder(ColorConstants.CYAN, 2)); checkBox.SetBackgroundColor(ColorConstants.GREEN); @@ -194,17 +194,17 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestCheckBoxInteractiveCustomAppearanceChecked() { - framework.AddSuppliers(new _Generator_189()); + framework.AddSuppliers(new _Generator_200()); framework.AssertBothValid("testCheckBoxInteractiveCustomAppearanceChecked"); } - private sealed class _Generator_189 : UaValidationTestFramework.Generator { - public _Generator_189() { + private sealed class _Generator_200 : UaValidationTestFramework.Generator { + public _Generator_200() { } public IBlockElement Generate() { CheckBox checkBox = (CheckBox)new CheckBox("name").SetInteractive(true); - checkBox.SetPdfConformanceLevel(PdfUAConformanceLevel.PDFUA_1); + checkBox.SetPdfConformance(PdfConformance.PDF_UA_1); checkBox.GetAccessibilityProperties().SetAlternateDescription("Alternative description"); checkBox.SetBorder(new SolidBorder(ColorConstants.CYAN, 2)); checkBox.SetBackgroundColor(ColorConstants.GREEN); @@ -217,12 +217,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestRadioButton() { - framework.AddSuppliers(new _Generator_208()); + framework.AddSuppliers(new _Generator_219()); framework.AssertBothValid("testRadioButton"); } - private sealed class _Generator_208 : UaValidationTestFramework.Generator { - public _Generator_208() { + private sealed class _Generator_219 : UaValidationTestFramework.Generator { + public _Generator_219() { } public IBlockElement Generate() { @@ -232,12 +232,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestRadioButtonChecked() { - framework.AddSuppliers(new _Generator_219()); + framework.AddSuppliers(new _Generator_230()); framework.AssertBothValid("testRadioButtonChecked"); } - private sealed class _Generator_219 : UaValidationTestFramework.Generator { - public _Generator_219() { + private sealed class _Generator_230 : UaValidationTestFramework.Generator { + public _Generator_230() { } public IBlockElement Generate() { @@ -249,12 +249,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestRadioButtonCustomAppearance() { - framework.AddSuppliers(new _Generator_232()); + framework.AddSuppliers(new _Generator_243()); framework.AssertBothValid("testRadioButtonCustomAppearance"); } - private sealed class _Generator_232 : UaValidationTestFramework.Generator { - public _Generator_232() { + private sealed class _Generator_243 : UaValidationTestFramework.Generator { + public _Generator_243() { } public IBlockElement Generate() { @@ -268,12 +268,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestRadioButtonCustomAppearanceChecked() { - framework.AddSuppliers(new _Generator_247()); + framework.AddSuppliers(new _Generator_258()); framework.AssertBothValid("testRadioButtonCustomAppearanceChecked"); } - private sealed class _Generator_247 : UaValidationTestFramework.Generator { - public _Generator_247() { + private sealed class _Generator_258 : UaValidationTestFramework.Generator { + public _Generator_258() { } public IBlockElement Generate() { @@ -288,13 +288,13 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestRadioButtonGroup() { - framework.AddSuppliers(new _Generator_263()); - framework.AddSuppliers(new _Generator_269()); + framework.AddSuppliers(new _Generator_274()); + framework.AddSuppliers(new _Generator_280()); framework.AssertBothValid("testRadioButtonGroup"); } - private sealed class _Generator_263 : UaValidationTestFramework.Generator { - public _Generator_263() { + private sealed class _Generator_274 : UaValidationTestFramework.Generator { + public _Generator_274() { } public IBlockElement Generate() { @@ -302,8 +302,8 @@ public IBlockElement Generate() { } } - private sealed class _Generator_269 : UaValidationTestFramework.Generator { - public _Generator_269() { + private sealed class _Generator_280 : UaValidationTestFramework.Generator { + public _Generator_280() { } public IBlockElement Generate() { @@ -313,13 +313,13 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestRadioButtonGroupCustomAppearance() { - framework.AddSuppliers(new _Generator_281()); - framework.AddSuppliers(new _Generator_291()); + framework.AddSuppliers(new _Generator_292()); + framework.AddSuppliers(new _Generator_302()); framework.AssertBothValid("testRadioButtonGroup"); } - private sealed class _Generator_281 : UaValidationTestFramework.Generator { - public _Generator_281() { + private sealed class _Generator_292 : UaValidationTestFramework.Generator { + public _Generator_292() { } public IBlockElement Generate() { @@ -331,8 +331,8 @@ public IBlockElement Generate() { } } - private sealed class _Generator_291 : UaValidationTestFramework.Generator { - public _Generator_291() { + private sealed class _Generator_302 : UaValidationTestFramework.Generator { + public _Generator_302() { } public IBlockElement Generate() { @@ -346,13 +346,13 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestRadioButtonGroupCustomAppearanceChecked() { - framework.AddSuppliers(new _Generator_306()); - framework.AddSuppliers(new _Generator_316()); + framework.AddSuppliers(new _Generator_317()); + framework.AddSuppliers(new _Generator_327()); framework.AssertBothValid("testRadioButtonGroupCustomAppearanceChecked"); } - private sealed class _Generator_306 : UaValidationTestFramework.Generator { - public _Generator_306() { + private sealed class _Generator_317 : UaValidationTestFramework.Generator { + public _Generator_317() { } public IBlockElement Generate() { @@ -364,8 +364,8 @@ public IBlockElement Generate() { } } - private sealed class _Generator_316 : UaValidationTestFramework.Generator { - public _Generator_316() { + private sealed class _Generator_327 : UaValidationTestFramework.Generator { + public _Generator_327() { } public IBlockElement Generate() { @@ -380,12 +380,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestRadioButtonInteractive() { - framework.AddSuppliers(new _Generator_333()); + framework.AddSuppliers(new _Generator_344()); framework.AssertBothValid("testRadioButtonInteractive"); } - private sealed class _Generator_333 : UaValidationTestFramework.Generator { - public _Generator_333() { + private sealed class _Generator_344 : UaValidationTestFramework.Generator { + public _Generator_344() { } public IBlockElement Generate() { @@ -398,12 +398,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestRadioButtonCheckedInteractive() { - framework.AddSuppliers(new _Generator_347()); + framework.AddSuppliers(new _Generator_358()); framework.AssertBothValid("testRadioButtonChecked"); } - private sealed class _Generator_347 : UaValidationTestFramework.Generator { - public _Generator_347() { + private sealed class _Generator_358 : UaValidationTestFramework.Generator { + public _Generator_358() { } public IBlockElement Generate() { @@ -417,12 +417,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestRadioButtonCustomAppearanceInteractive() { - framework.AddSuppliers(new _Generator_362()); + framework.AddSuppliers(new _Generator_373()); framework.AssertBothValid("testRadioButtonCustomAppearance"); } - private sealed class _Generator_362 : UaValidationTestFramework.Generator { - public _Generator_362() { + private sealed class _Generator_373 : UaValidationTestFramework.Generator { + public _Generator_373() { } public IBlockElement Generate() { @@ -438,12 +438,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestRadioButtonCustomAppearanceCheckedInteractive() { - framework.AddSuppliers(new _Generator_379()); + framework.AddSuppliers(new _Generator_390()); framework.AssertBothValid("testRadioButtonCustomAppearanceCheckedInteractive"); } - private sealed class _Generator_379 : UaValidationTestFramework.Generator { - public _Generator_379() { + private sealed class _Generator_390 : UaValidationTestFramework.Generator { + public _Generator_390() { } public IBlockElement Generate() { @@ -460,13 +460,13 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestRadioButtonGroupInteractive() { - framework.AddSuppliers(new _Generator_397()); - framework.AddSuppliers(new _Generator_406()); + framework.AddSuppliers(new _Generator_408()); + framework.AddSuppliers(new _Generator_417()); framework.AssertBothValid("testRadioButtonGroupInteractive"); } - private sealed class _Generator_397 : UaValidationTestFramework.Generator { - public _Generator_397() { + private sealed class _Generator_408 : UaValidationTestFramework.Generator { + public _Generator_408() { } public IBlockElement Generate() { @@ -477,8 +477,8 @@ public IBlockElement Generate() { } } - private sealed class _Generator_406 : UaValidationTestFramework.Generator { - public _Generator_406() { + private sealed class _Generator_417 : UaValidationTestFramework.Generator { + public _Generator_417() { } public IBlockElement Generate() { @@ -491,13 +491,13 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestRadioButtonGroupCustomAppearanceInteractive() { - framework.AddSuppliers(new _Generator_421()); - framework.AddSuppliers(new _Generator_433()); + framework.AddSuppliers(new _Generator_432()); + framework.AddSuppliers(new _Generator_444()); framework.AssertBothValid("testRadioButtonGroupInteractive"); } - private sealed class _Generator_421 : UaValidationTestFramework.Generator { - public _Generator_421() { + private sealed class _Generator_432 : UaValidationTestFramework.Generator { + public _Generator_432() { } public IBlockElement Generate() { @@ -511,8 +511,8 @@ public IBlockElement Generate() { } } - private sealed class _Generator_433 : UaValidationTestFramework.Generator { - public _Generator_433() { + private sealed class _Generator_444 : UaValidationTestFramework.Generator { + public _Generator_444() { } public IBlockElement Generate() { @@ -528,13 +528,13 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestRadioButtonGroupCustomAppearanceCheckedInteractive() { - framework.AddSuppliers(new _Generator_450()); - framework.AddSuppliers(new _Generator_462()); + framework.AddSuppliers(new _Generator_461()); + framework.AddSuppliers(new _Generator_473()); framework.AssertBothValid("testRadioButtonGroupCustomAppearanceCheckedInteractive"); } - private sealed class _Generator_450 : UaValidationTestFramework.Generator { - public _Generator_450() { + private sealed class _Generator_461 : UaValidationTestFramework.Generator { + public _Generator_461() { } public IBlockElement Generate() { @@ -548,8 +548,8 @@ public IBlockElement Generate() { } } - private sealed class _Generator_462 : UaValidationTestFramework.Generator { - public _Generator_462() { + private sealed class _Generator_473 : UaValidationTestFramework.Generator { + public _Generator_473() { } public IBlockElement Generate() { @@ -566,12 +566,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestButton() { - framework.AddSuppliers(new _Generator_481(this)); + framework.AddSuppliers(new _Generator_492(this)); framework.AssertBothValid("testButton"); } - private sealed class _Generator_481 : UaValidationTestFramework.Generator { - public _Generator_481(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_492 : UaValidationTestFramework.Generator { + public _Generator_492(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -587,12 +587,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestButtonCustomAppearance() { - framework.AddSuppliers(new _Generator_495(this)); + framework.AddSuppliers(new _Generator_506(this)); framework.AssertBothValid("testButtonCustomAppearance"); } - private sealed class _Generator_495 : UaValidationTestFramework.Generator { - public _Generator_495(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_506 : UaValidationTestFramework.Generator { + public _Generator_506(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -610,12 +610,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestButtonSingleLine() { - framework.AddSuppliers(new _Generator_511(this)); + framework.AddSuppliers(new _Generator_522(this)); framework.AssertBothValid("testButtonSingleLine"); } - private sealed class _Generator_511 : UaValidationTestFramework.Generator { - public _Generator_511(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_522 : UaValidationTestFramework.Generator { + public _Generator_522(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -631,12 +631,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestButtonCustomContent() { - framework.AddSuppliers(new _Generator_525(this)); + framework.AddSuppliers(new _Generator_536(this)); framework.AssertBothValid("testButtonSingleLine"); } - private sealed class _Generator_525 : UaValidationTestFramework.Generator { - public _Generator_525(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_536 : UaValidationTestFramework.Generator { + public _Generator_536(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -653,12 +653,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestButtonCustomContentIsAlsoForm() { - framework.AddSuppliers(new _Generator_540()); + framework.AddSuppliers(new _Generator_551()); framework.AssertBothValid("testButtonSingleLine"); } - private sealed class _Generator_540 : UaValidationTestFramework.Generator { - public _Generator_540() { + private sealed class _Generator_551 : UaValidationTestFramework.Generator { + public _Generator_551() { } public IBlockElement Generate() { @@ -672,12 +672,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestButtonInteractive() { - framework.AddSuppliers(new _Generator_555(this)); + framework.AddSuppliers(new _Generator_566(this)); framework.AssertBothValid("testButtonInteractive"); } - private sealed class _Generator_555 : UaValidationTestFramework.Generator { - public _Generator_555(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_566 : UaValidationTestFramework.Generator { + public _Generator_566(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -695,12 +695,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestButtonCustomAppearanceInteractive() { - framework.AddSuppliers(new _Generator_572(this)); + framework.AddSuppliers(new _Generator_583(this)); framework.AssertBothValid("testButtonCustomAppearanceInteractive"); } - private sealed class _Generator_572 : UaValidationTestFramework.Generator { - public _Generator_572(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_583 : UaValidationTestFramework.Generator { + public _Generator_583(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -720,12 +720,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestButtonSingleLineInteractive() { - framework.AddSuppliers(new _Generator_591(this)); + framework.AddSuppliers(new _Generator_602(this)); framework.AssertBothValid("testButtonSingleLineInteractive"); } - private sealed class _Generator_591 : UaValidationTestFramework.Generator { - public _Generator_591(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_602 : UaValidationTestFramework.Generator { + public _Generator_602(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -743,12 +743,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestButtonCustomContentInteractive() { - framework.AddSuppliers(new _Generator_608(this)); + framework.AddSuppliers(new _Generator_619(this)); framework.AssertBothValid("testButtonSingleLineInteractive"); } - private sealed class _Generator_608 : UaValidationTestFramework.Generator { - public _Generator_608(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_619 : UaValidationTestFramework.Generator { + public _Generator_619(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -768,12 +768,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestButtonCustomContentIsAlsoFormInteractive() { - framework.AddSuppliers(new _Generator_626(this)); + framework.AddSuppliers(new _Generator_637(this)); framework.AssertBothValid("testButtonSingleLineInteractive"); } - private sealed class _Generator_626 : UaValidationTestFramework.Generator { - public _Generator_626(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_637 : UaValidationTestFramework.Generator { + public _Generator_637(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -795,12 +795,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestInputField() { - framework.AddSuppliers(new _Generator_646(this)); + framework.AddSuppliers(new _Generator_657(this)); framework.AssertBothValid("testInputField"); } - private sealed class _Generator_646 : UaValidationTestFramework.Generator { - public _Generator_646(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_657 : UaValidationTestFramework.Generator { + public _Generator_657(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -815,12 +815,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestInputFieldWithValue() { - framework.AddSuppliers(new _Generator_659(this)); + framework.AddSuppliers(new _Generator_670(this)); framework.AssertBothValid("testInputFieldWithValue"); } - private sealed class _Generator_659 : UaValidationTestFramework.Generator { - public _Generator_659(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_670 : UaValidationTestFramework.Generator { + public _Generator_670(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -836,12 +836,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestInputFieldWithCustomAppearance() { - framework.AddSuppliers(new _Generator_673(this)); + framework.AddSuppliers(new _Generator_684(this)); framework.AssertBothValid("testInputFieldWithCustomAppearance"); } - private sealed class _Generator_673 : UaValidationTestFramework.Generator { - public _Generator_673(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_684 : UaValidationTestFramework.Generator { + public _Generator_684(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -858,12 +858,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestInputFieldWithCustomAppearanceAndValue() { - framework.AddSuppliers(new _Generator_688(this)); + framework.AddSuppliers(new _Generator_699(this)); framework.AssertBothValid("testInputFieldWithCustomAppearanceAndValue"); } - private sealed class _Generator_688 : UaValidationTestFramework.Generator { - public _Generator_688(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_699 : UaValidationTestFramework.Generator { + public _Generator_699(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -881,12 +881,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestInputFieldWithCustomAppearanceAndPlaceHolder() { - framework.AddSuppliers(new _Generator_704(this)); + framework.AddSuppliers(new _Generator_715(this)); framework.AssertBothValid("testInputFieldWithCustomAppearanceAndValue"); } - private sealed class _Generator_704 : UaValidationTestFramework.Generator { - public _Generator_704(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_715 : UaValidationTestFramework.Generator { + public _Generator_715(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -904,12 +904,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestInputFieldInteractive() { - framework.AddSuppliers(new _Generator_720(this)); + framework.AddSuppliers(new _Generator_731(this)); framework.AssertBothValid("testInputFieldInteractive"); } - private sealed class _Generator_720 : UaValidationTestFramework.Generator { - public _Generator_720(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_731 : UaValidationTestFramework.Generator { + public _Generator_731(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -926,12 +926,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestInputFieldWithValueInteractive() { - framework.AddSuppliers(new _Generator_735(this)); + framework.AddSuppliers(new _Generator_746(this)); framework.AssertBothValid("testInputFieldWithValueInteractive"); } - private sealed class _Generator_735 : UaValidationTestFramework.Generator { - public _Generator_735(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_746 : UaValidationTestFramework.Generator { + public _Generator_746(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -949,12 +949,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestInputFieldWithCustomAppearanceInteractive() { - framework.AddSuppliers(new _Generator_751(this)); + framework.AddSuppliers(new _Generator_762(this)); framework.AssertBothValid("testInputFieldWithCustomAppearanceInteractive"); } - private sealed class _Generator_751 : UaValidationTestFramework.Generator { - public _Generator_751(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_762 : UaValidationTestFramework.Generator { + public _Generator_762(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -973,12 +973,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestInputFieldWithCustomAppearanceAndValueInteractive() { - framework.AddSuppliers(new _Generator_768(this)); + framework.AddSuppliers(new _Generator_779(this)); framework.AssertBothValid("testInputFieldWithCustomAppearanceAndValueInteractive"); } - private sealed class _Generator_768 : UaValidationTestFramework.Generator { - public _Generator_768(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_779 : UaValidationTestFramework.Generator { + public _Generator_779(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -998,12 +998,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestInputFieldWithCustomAppearanceAndPlaceHolderInteractive() { - framework.AddSuppliers(new _Generator_786(this)); + framework.AddSuppliers(new _Generator_797(this)); framework.AssertBothValid("testInputFieldWithCustomAppearanceAndPlaceHolderInteractive"); } - private sealed class _Generator_786 : UaValidationTestFramework.Generator { - public _Generator_786(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_797 : UaValidationTestFramework.Generator { + public _Generator_797(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1023,12 +1023,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestTextArea() { - framework.AddSuppliers(new _Generator_804(this)); + framework.AddSuppliers(new _Generator_815(this)); framework.AssertBothValid("testTextArea"); } - private sealed class _Generator_804 : UaValidationTestFramework.Generator { - public _Generator_804(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_815 : UaValidationTestFramework.Generator { + public _Generator_815(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1043,12 +1043,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestTextAreaWithValue() { - framework.AddSuppliers(new _Generator_817(this)); + framework.AddSuppliers(new _Generator_828(this)); framework.AssertBothValid("testTextAreaWithValue"); } - private sealed class _Generator_817 : UaValidationTestFramework.Generator { - public _Generator_817(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_828 : UaValidationTestFramework.Generator { + public _Generator_828(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1064,12 +1064,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestTextAreaWithCustomAppearance() { - framework.AddSuppliers(new _Generator_831(this)); + framework.AddSuppliers(new _Generator_842(this)); framework.AssertBothValid("testTextAreaWithCustomAppearance"); } - private sealed class _Generator_831 : UaValidationTestFramework.Generator { - public _Generator_831(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_842 : UaValidationTestFramework.Generator { + public _Generator_842(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1086,12 +1086,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestTextAreaWithCustomAppearanceAndValue() { - framework.AddSuppliers(new _Generator_846(this)); + framework.AddSuppliers(new _Generator_857(this)); framework.AssertBothValid("testTextAreaWithCustomAppearanceAndValue"); } - private sealed class _Generator_846 : UaValidationTestFramework.Generator { - public _Generator_846(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_857 : UaValidationTestFramework.Generator { + public _Generator_857(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1109,12 +1109,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestTextAreaWithCustomAppearanceAndPlaceHolder() { - framework.AddSuppliers(new _Generator_862(this)); + framework.AddSuppliers(new _Generator_873(this)); framework.AssertBothValid("testTextAreaWithCustomAppearanceAndValue"); } - private sealed class _Generator_862 : UaValidationTestFramework.Generator { - public _Generator_862(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_873 : UaValidationTestFramework.Generator { + public _Generator_873(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1132,12 +1132,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestTextAreaInteractive() { - framework.AddSuppliers(new _Generator_878(this)); + framework.AddSuppliers(new _Generator_889(this)); framework.AssertBothValid("testTextAreaInteractive"); } - private sealed class _Generator_878 : UaValidationTestFramework.Generator { - public _Generator_878(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_889 : UaValidationTestFramework.Generator { + public _Generator_889(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1154,12 +1154,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestTextAreaWithValueInteractive() { - framework.AddSuppliers(new _Generator_893(this)); + framework.AddSuppliers(new _Generator_904(this)); framework.AssertBothValid("testTextAreaWithValueInteractive"); } - private sealed class _Generator_893 : UaValidationTestFramework.Generator { - public _Generator_893(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_904 : UaValidationTestFramework.Generator { + public _Generator_904(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1177,12 +1177,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestTextAreaWithCustomAppearanceInteractive() { - framework.AddSuppliers(new _Generator_909(this)); + framework.AddSuppliers(new _Generator_920(this)); framework.AssertBothValid("testTextAreaWithCustomAppearanceInteractive"); } - private sealed class _Generator_909 : UaValidationTestFramework.Generator { - public _Generator_909(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_920 : UaValidationTestFramework.Generator { + public _Generator_920(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1201,12 +1201,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestTextAreaWithCustomAppearanceAndValueInteractive() { - framework.AddSuppliers(new _Generator_926(this)); + framework.AddSuppliers(new _Generator_937(this)); framework.AssertBothValid("testTextAreaWithCustomAppearanceAndValueInteractive"); } - private sealed class _Generator_926 : UaValidationTestFramework.Generator { - public _Generator_926(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_937 : UaValidationTestFramework.Generator { + public _Generator_937(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1226,12 +1226,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestTextAreaWithCustomAppearanceAndPlaceHolderInteractive() { - framework.AddSuppliers(new _Generator_944(this)); + framework.AddSuppliers(new _Generator_955(this)); framework.AssertBothValid("testTextAreaWithCustomAppearanceAndPlaceHolderInteractive"); } - private sealed class _Generator_944 : UaValidationTestFramework.Generator { - public _Generator_944(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_955 : UaValidationTestFramework.Generator { + public _Generator_955(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1251,12 +1251,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestListBox() { - framework.AddSuppliers(new _Generator_962(this)); + framework.AddSuppliers(new _Generator_973(this)); framework.AssertBothValid("testListBox"); } - private sealed class _Generator_962 : UaValidationTestFramework.Generator { - public _Generator_962(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_973 : UaValidationTestFramework.Generator { + public _Generator_973(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1273,12 +1273,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestListBoxCustomAppearance() { - framework.AddSuppliers(new _Generator_977(this)); + framework.AddSuppliers(new _Generator_988(this)); framework.AssertBothValid("testListBoxCustomAppearance"); } - private sealed class _Generator_977 : UaValidationTestFramework.Generator { - public _Generator_977(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_988 : UaValidationTestFramework.Generator { + public _Generator_988(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1298,12 +1298,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestListBoxCustomAppearanceSelected() { - framework.AddSuppliers(new _Generator_995(this)); + framework.AddSuppliers(new _Generator_1006(this)); framework.AssertBothValid("testListBoxCustomAppearanceSelected"); } - private sealed class _Generator_995 : UaValidationTestFramework.Generator { - public _Generator_995(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1006 : UaValidationTestFramework.Generator { + public _Generator_1006(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1323,12 +1323,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestListBoxInteractive() { - framework.AddSuppliers(new _Generator_1013(this)); + framework.AddSuppliers(new _Generator_1024(this)); framework.AssertBothValid("testListBoxInteractive"); } - private sealed class _Generator_1013 : UaValidationTestFramework.Generator { - public _Generator_1013(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1024 : UaValidationTestFramework.Generator { + public _Generator_1024(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1347,12 +1347,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestListBoxCustomAppearanceInteractive() { - framework.AddSuppliers(new _Generator_1030(this)); + framework.AddSuppliers(new _Generator_1041(this)); framework.AssertBothValid("testListBoxCustomAppearanceInteractive"); } - private sealed class _Generator_1030 : UaValidationTestFramework.Generator { - public _Generator_1030(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1041 : UaValidationTestFramework.Generator { + public _Generator_1041(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1374,12 +1374,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestListBoxCustomAppearanceSelectedInteractive() { - framework.AddSuppliers(new _Generator_1050(this)); + framework.AddSuppliers(new _Generator_1061(this)); framework.AssertBothValid("testListBoxCustomAppearanceSelectedInteractive"); } - private sealed class _Generator_1050 : UaValidationTestFramework.Generator { - public _Generator_1050(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1061 : UaValidationTestFramework.Generator { + public _Generator_1061(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1401,12 +1401,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestComboBox() { - framework.AddSuppliers(new _Generator_1070(this)); + framework.AddSuppliers(new _Generator_1081(this)); framework.AssertBothValid("testComboBox"); } - private sealed class _Generator_1070 : UaValidationTestFramework.Generator { - public _Generator_1070(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1081 : UaValidationTestFramework.Generator { + public _Generator_1081(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1423,12 +1423,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestComboBoxCustomAppearance() { - framework.AddSuppliers(new _Generator_1085(this)); + framework.AddSuppliers(new _Generator_1096(this)); framework.AssertBothValid("testComboBoxCustomAppearance"); } - private sealed class _Generator_1085 : UaValidationTestFramework.Generator { - public _Generator_1085(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1096 : UaValidationTestFramework.Generator { + public _Generator_1096(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1448,12 +1448,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestComboBoxCustomAppearanceSelected() { - framework.AddSuppliers(new _Generator_1103(this)); + framework.AddSuppliers(new _Generator_1114(this)); framework.AssertBothValid("testListBoxCustomAppearanceSelected"); } - private sealed class _Generator_1103 : UaValidationTestFramework.Generator { - public _Generator_1103(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1114 : UaValidationTestFramework.Generator { + public _Generator_1114(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1473,12 +1473,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestComboBoxInteractive() { - framework.AddSuppliers(new _Generator_1121(this)); + framework.AddSuppliers(new _Generator_1132(this)); framework.AssertBothValid("testComboBoxInteractive"); } - private sealed class _Generator_1121 : UaValidationTestFramework.Generator { - public _Generator_1121(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1132 : UaValidationTestFramework.Generator { + public _Generator_1132(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1497,12 +1497,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestComboBoxCustomAppearanceInteractive() { - framework.AddSuppliers(new _Generator_1138(this)); + framework.AddSuppliers(new _Generator_1149(this)); framework.AssertBothValid("testComboBoxCustomAppearanceInteractive"); } - private sealed class _Generator_1138 : UaValidationTestFramework.Generator { - public _Generator_1138(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1149 : UaValidationTestFramework.Generator { + public _Generator_1149(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1524,12 +1524,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestComboBoxCustomAppearanceSelectedInteractive() { - framework.AddSuppliers(new _Generator_1158(this)); + framework.AddSuppliers(new _Generator_1169(this)); framework.AssertBothValid("testComboBoxCustomAppearanceSelectedInteractive"); } - private sealed class _Generator_1158 : UaValidationTestFramework.Generator { - public _Generator_1158(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1169 : UaValidationTestFramework.Generator { + public _Generator_1169(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1551,12 +1551,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestSignatureAppearance() { - framework.AddSuppliers(new _Generator_1178(this)); + framework.AddSuppliers(new _Generator_1189(this)); framework.AssertBothValid("testSignatureAppearance"); } - private sealed class _Generator_1178 : UaValidationTestFramework.Generator { - public _Generator_1178(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1189 : UaValidationTestFramework.Generator { + public _Generator_1189(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1572,12 +1572,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestSignatureAppearanceWithSignedAppearanceText() { - framework.AddSuppliers(new _Generator_1192(this)); + framework.AddSuppliers(new _Generator_1203(this)); framework.AssertBothValid("testSignatureAppearanceWithSignedAppearanceText"); } - private sealed class _Generator_1192 : UaValidationTestFramework.Generator { - public _Generator_1192(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1203 : UaValidationTestFramework.Generator { + public _Generator_1203(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1597,12 +1597,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestSignatureAppearanceWithCustomContent() { - framework.AddSuppliers(new _Generator_1210(this)); + framework.AddSuppliers(new _Generator_1221(this)); framework.AssertBothValid("testSignatureAppearanceWithSignedAppearanceText"); } - private sealed class _Generator_1210 : UaValidationTestFramework.Generator { - public _Generator_1210(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1221 : UaValidationTestFramework.Generator { + public _Generator_1221(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1620,12 +1620,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestSignatureAppearanceWithSignedAppearanceAndCustomAppearanceText() { - framework.AddSuppliers(new _Generator_1227(this)); + framework.AddSuppliers(new _Generator_1238(this)); framework.AssertBothValid("testSignatureAppearanceWithSignedAppearanceAndCustomAppearanceText"); } - private sealed class _Generator_1227 : UaValidationTestFramework.Generator { - public _Generator_1227(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1238 : UaValidationTestFramework.Generator { + public _Generator_1238(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1647,12 +1647,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestSignatureAppearanceInteractive() { - framework.AddSuppliers(new _Generator_1247(this)); + framework.AddSuppliers(new _Generator_1258(this)); framework.AssertBothValid("testSignatureAppearanceInteractive"); } - private sealed class _Generator_1247 : UaValidationTestFramework.Generator { - public _Generator_1247(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1258 : UaValidationTestFramework.Generator { + public _Generator_1258(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1670,12 +1670,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestSignatureAppearanceWithSignedAppearanceTextInteractive() { - framework.AddSuppliers(new _Generator_1263(this)); + framework.AddSuppliers(new _Generator_1274(this)); framework.AssertBothValid("testSignatureAppearanceWithSignedAppearanceTextInteractive"); } - private sealed class _Generator_1263 : UaValidationTestFramework.Generator { - public _Generator_1263(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1274 : UaValidationTestFramework.Generator { + public _Generator_1274(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1697,12 +1697,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestSignatureAppearanceWithCustomContentInteractive() { - framework.AddSuppliers(new _Generator_1284(this)); + framework.AddSuppliers(new _Generator_1295(this)); framework.AssertBothValid("testSignatureAppearanceWithSignedAppearanceTextInteractive"); } - private sealed class _Generator_1284 : UaValidationTestFramework.Generator { - public _Generator_1284(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1295 : UaValidationTestFramework.Generator { + public _Generator_1295(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1722,12 +1722,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestSignedAndCustomAppearanceTextInteractive() { - framework.AddSuppliers(new _Generator_1304(this)); + framework.AddSuppliers(new _Generator_1315(this)); framework.AssertBothValid("testSignedAndCustomAppearanceTextInteractive"); } - private sealed class _Generator_1304 : UaValidationTestFramework.Generator { - public _Generator_1304(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1315 : UaValidationTestFramework.Generator { + public _Generator_1315(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1751,18 +1751,18 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestInteractiveCheckBoxNoAlternativeDescription() { - framework.AddSuppliers(new _Generator_1326()); + framework.AddSuppliers(new _Generator_1337()); framework.AssertBothFail("testInteractiveCheckBoxNoAlternativeDescription", PdfUAExceptionMessageConstants .MISSING_FORM_FIELD_DESCRIPTION); } - private sealed class _Generator_1326 : UaValidationTestFramework.Generator { - public _Generator_1326() { + private sealed class _Generator_1337 : UaValidationTestFramework.Generator { + public _Generator_1337() { } public IBlockElement Generate() { CheckBox cb = new CheckBox("name"); - cb.SetPdfConformanceLevel(PdfUAConformanceLevel.PDFUA_1); + cb.SetPdfConformance(PdfConformance.PDF_UA_1); cb.SetInteractive(true); return cb; } @@ -1770,13 +1770,13 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestInteractiveRadioButtonNoAlternativeDescription() { - framework.AddSuppliers(new _Generator_1341()); + framework.AddSuppliers(new _Generator_1352()); framework.AssertBothFail("testInteractiveRadioButtonNoAlternativeDescription", PdfUAExceptionMessageConstants .MISSING_FORM_FIELD_DESCRIPTION); } - private sealed class _Generator_1341 : UaValidationTestFramework.Generator { - public _Generator_1341() { + private sealed class _Generator_1352 : UaValidationTestFramework.Generator { + public _Generator_1352() { } public IBlockElement Generate() { @@ -1788,13 +1788,13 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestInteractiveButtonNoAlternativeDescription() { - framework.AddSuppliers(new _Generator_1355(this)); + framework.AddSuppliers(new _Generator_1366(this)); framework.AssertBothFail("testInteractiveButtonNoAlternativeDescription", PdfUAExceptionMessageConstants.MISSING_FORM_FIELD_DESCRIPTION ); } - private sealed class _Generator_1355 : UaValidationTestFramework.Generator { - public _Generator_1355(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1366 : UaValidationTestFramework.Generator { + public _Generator_1366(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1810,13 +1810,13 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestInteractiveInputFieldNoAlternativeDescription() { - framework.AddSuppliers(new _Generator_1370(this)); + framework.AddSuppliers(new _Generator_1381(this)); framework.AssertBothFail("testInteractiveInputFieldNoAlternativeDescription", PdfUAExceptionMessageConstants .MISSING_FORM_FIELD_DESCRIPTION); } - private sealed class _Generator_1370 : UaValidationTestFramework.Generator { - public _Generator_1370(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1381 : UaValidationTestFramework.Generator { + public _Generator_1381(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1832,13 +1832,13 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestInteractiveTextAreaNoAlternativeDescription() { - framework.AddSuppliers(new _Generator_1385(this)); + framework.AddSuppliers(new _Generator_1396(this)); framework.AssertBothFail("testInteractiveTextAreaNoAlternativeDescription", PdfUAExceptionMessageConstants .MISSING_FORM_FIELD_DESCRIPTION); } - private sealed class _Generator_1385 : UaValidationTestFramework.Generator { - public _Generator_1385(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1396 : UaValidationTestFramework.Generator { + public _Generator_1396(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1854,13 +1854,13 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestInteractiveListBoxNoAlternativeDescription() { - framework.AddSuppliers(new _Generator_1400(this)); + framework.AddSuppliers(new _Generator_1411(this)); framework.AssertBothFail("testInteractiveListBoxNoAlternativeDescription", PdfUAExceptionMessageConstants. MISSING_FORM_FIELD_DESCRIPTION); } - private sealed class _Generator_1400 : UaValidationTestFramework.Generator { - public _Generator_1400(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1411 : UaValidationTestFramework.Generator { + public _Generator_1411(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1876,13 +1876,13 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestInteractiveComboBoxNoAlternativeDescription() { - framework.AddSuppliers(new _Generator_1415(this)); + framework.AddSuppliers(new _Generator_1426(this)); framework.AssertBothFail("testInteractiveComboBoxNoAlternativeDescription", PdfUAExceptionMessageConstants .MISSING_FORM_FIELD_DESCRIPTION); } - private sealed class _Generator_1415 : UaValidationTestFramework.Generator { - public _Generator_1415(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1426 : UaValidationTestFramework.Generator { + public _Generator_1426(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1898,13 +1898,13 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestInteractiveSignatureAppearanceNoAlternativeDescription() { - framework.AddSuppliers(new _Generator_1430(this)); + framework.AddSuppliers(new _Generator_1441(this)); framework.AssertBothFail("testInteractiveSignatureAppearanceNoAlternativeDescription", PdfUAExceptionMessageConstants .MISSING_FORM_FIELD_DESCRIPTION); } - private sealed class _Generator_1430 : UaValidationTestFramework.Generator { - public _Generator_1430(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1441 : UaValidationTestFramework.Generator { + public _Generator_1441(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -1920,31 +1920,31 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestCheckBoxDifferentRole() { - framework.AddSuppliers(new _Generator_1445()); - framework.AddSuppliers(new _Generator_1455()); + framework.AddSuppliers(new _Generator_1456()); + framework.AddSuppliers(new _Generator_1466()); framework.AssertBothValid("testCheckBoxDifferentRole"); } - private sealed class _Generator_1445 : UaValidationTestFramework.Generator { - public _Generator_1445() { + private sealed class _Generator_1456 : UaValidationTestFramework.Generator { + public _Generator_1456() { } public IBlockElement Generate() { CheckBox cb = new CheckBox("name"); - cb.SetPdfConformanceLevel(PdfUAConformanceLevel.PDFUA_1); + cb.SetPdfConformance(PdfConformance.PDF_UA_1); cb.GetAccessibilityProperties().SetRole(StandardRoles.FIGURE); cb.GetAccessibilityProperties().SetAlternateDescription("Hello"); return cb; } } - private sealed class _Generator_1455 : UaValidationTestFramework.Generator { - public _Generator_1455() { + private sealed class _Generator_1466 : UaValidationTestFramework.Generator { + public _Generator_1466() { } public IBlockElement Generate() { CheckBox cb = new CheckBox("name"); - cb.SetPdfConformanceLevel(PdfUAConformanceLevel.PDFUA_1); + cb.SetPdfConformance(PdfConformance.PDF_UA_1); cb.GetAccessibilityProperties().SetRole(StandardRoles.ARTIFACT); return cb; } @@ -1952,14 +1952,14 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestRadioButtonDifferentRole() { - framework.AddSuppliers(new _Generator_1469()); - framework.AddSuppliers(new _Generator_1479()); - framework.AddSuppliers(new _Generator_1489()); + framework.AddSuppliers(new _Generator_1480()); + framework.AddSuppliers(new _Generator_1490()); + framework.AddSuppliers(new _Generator_1500()); framework.AssertBothValid("testRadioButtonDifferentRole"); } - private sealed class _Generator_1469 : UaValidationTestFramework.Generator { - public _Generator_1469() { + private sealed class _Generator_1480 : UaValidationTestFramework.Generator { + public _Generator_1480() { } public IBlockElement Generate() { @@ -1971,8 +1971,8 @@ public IBlockElement Generate() { } } - private sealed class _Generator_1479 : UaValidationTestFramework.Generator { - public _Generator_1479() { + private sealed class _Generator_1490 : UaValidationTestFramework.Generator { + public _Generator_1490() { } public IBlockElement Generate() { @@ -1984,8 +1984,8 @@ public IBlockElement Generate() { } } - private sealed class _Generator_1489 : UaValidationTestFramework.Generator { - public _Generator_1489() { + private sealed class _Generator_1500 : UaValidationTestFramework.Generator { + public _Generator_1500() { } public IBlockElement Generate() { @@ -1997,13 +1997,13 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestButtonDifferentRole() { - framework.AddSuppliers(new _Generator_1502(this)); framework.AddSuppliers(new _Generator_1513(this)); + framework.AddSuppliers(new _Generator_1524(this)); framework.AssertBothValid("testButtonDifferentRole"); } - private sealed class _Generator_1502 : UaValidationTestFramework.Generator { - public _Generator_1502(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1513 : UaValidationTestFramework.Generator { + public _Generator_1513(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -2019,8 +2019,8 @@ public IBlockElement Generate() { private readonly PdfUAFormFieldsTest _enclosing; } - private sealed class _Generator_1513 : UaValidationTestFramework.Generator { - public _Generator_1513(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1524 : UaValidationTestFramework.Generator { + public _Generator_1524(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -2037,14 +2037,14 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestInputFieldDifferentRole() { - framework.AddSuppliers(new _Generator_1528(this)); framework.AddSuppliers(new _Generator_1539(this)); framework.AddSuppliers(new _Generator_1550(this)); + framework.AddSuppliers(new _Generator_1561(this)); framework.AssertBothValid("testInputFieldDifferentRole"); } - private sealed class _Generator_1528 : UaValidationTestFramework.Generator { - public _Generator_1528(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1539 : UaValidationTestFramework.Generator { + public _Generator_1539(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -2060,8 +2060,8 @@ public IBlockElement Generate() { private readonly PdfUAFormFieldsTest _enclosing; } - private sealed class _Generator_1539 : UaValidationTestFramework.Generator { - public _Generator_1539(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1550 : UaValidationTestFramework.Generator { + public _Generator_1550(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -2076,8 +2076,8 @@ public IBlockElement Generate() { private readonly PdfUAFormFieldsTest _enclosing; } - private sealed class _Generator_1550 : UaValidationTestFramework.Generator { - public _Generator_1550(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1561 : UaValidationTestFramework.Generator { + public _Generator_1561(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -2094,14 +2094,14 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestTextAreaDifferentRole() { - framework.AddSuppliers(new _Generator_1565(this)); - framework.AddSuppliers(new _Generator_1575(this)); - framework.AddSuppliers(new _Generator_1584(this)); + framework.AddSuppliers(new _Generator_1576(this)); + framework.AddSuppliers(new _Generator_1586(this)); + framework.AddSuppliers(new _Generator_1595(this)); framework.AssertBothValid("testTextAreaDifferentRole"); } - private sealed class _Generator_1565 : UaValidationTestFramework.Generator { - public _Generator_1565(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1576 : UaValidationTestFramework.Generator { + public _Generator_1576(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -2116,8 +2116,8 @@ public IBlockElement Generate() { private readonly PdfUAFormFieldsTest _enclosing; } - private sealed class _Generator_1575 : UaValidationTestFramework.Generator { - public _Generator_1575(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1586 : UaValidationTestFramework.Generator { + public _Generator_1586(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -2131,8 +2131,8 @@ public IBlockElement Generate() { private readonly PdfUAFormFieldsTest _enclosing; } - private sealed class _Generator_1584 : UaValidationTestFramework.Generator { - public _Generator_1584(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1595 : UaValidationTestFramework.Generator { + public _Generator_1595(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -2148,13 +2148,13 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestListBoxDifferentRole() { - framework.AddSuppliers(new _Generator_1599(this)); - framework.AddSuppliers(new _Generator_1609(this)); + framework.AddSuppliers(new _Generator_1610(this)); + framework.AddSuppliers(new _Generator_1620(this)); framework.AssertBothValid("testListBoxDifferentRole"); } - private sealed class _Generator_1599 : UaValidationTestFramework.Generator { - public _Generator_1599(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1610 : UaValidationTestFramework.Generator { + public _Generator_1610(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -2169,8 +2169,8 @@ public IBlockElement Generate() { private readonly PdfUAFormFieldsTest _enclosing; } - private sealed class _Generator_1609 : UaValidationTestFramework.Generator { - public _Generator_1609(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1620 : UaValidationTestFramework.Generator { + public _Generator_1620(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -2186,13 +2186,13 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestComboBoxDifferentRole() { - framework.AddSuppliers(new _Generator_1625(this)); - framework.AddSuppliers(new _Generator_1638(this)); + framework.AddSuppliers(new _Generator_1636(this)); + framework.AddSuppliers(new _Generator_1649(this)); framework.AssertBothValid("testComboBoxDifferentRole"); } - private sealed class _Generator_1625 : UaValidationTestFramework.Generator { - public _Generator_1625(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1636 : UaValidationTestFramework.Generator { + public _Generator_1636(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -2209,8 +2209,8 @@ public IBlockElement Generate() { private readonly PdfUAFormFieldsTest _enclosing; } - private sealed class _Generator_1638 : UaValidationTestFramework.Generator { - public _Generator_1638(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1649 : UaValidationTestFramework.Generator { + public _Generator_1649(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -2226,13 +2226,13 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void TestSignatureAppearanceDifferentRole() { - framework.AddSuppliers(new _Generator_1652(this)); - framework.AddSuppliers(new _Generator_1664(this)); + framework.AddSuppliers(new _Generator_1663(this)); + framework.AddSuppliers(new _Generator_1675(this)); framework.AssertBothValid("testSignatureAppearanceDifferentRole"); } - private sealed class _Generator_1652 : UaValidationTestFramework.Generator { - public _Generator_1652(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1663 : UaValidationTestFramework.Generator { + public _Generator_1663(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -2248,8 +2248,8 @@ public IBlockElement Generate() { private readonly PdfUAFormFieldsTest _enclosing; } - private sealed class _Generator_1664 : UaValidationTestFramework.Generator { - public _Generator_1664(PdfUAFormFieldsTest _enclosing) { + private sealed class _Generator_1675 : UaValidationTestFramework.Generator { + public _Generator_1675(PdfUAFormFieldsTest _enclosing) { this._enclosing = _enclosing; } @@ -2269,7 +2269,7 @@ public virtual void TestTextBuilderWithTu() { framework.AddBeforeGenerationHook((pdfDoc) => { PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true); PdfTextFormField field = new TextFormFieldBuilder(pdfDoc, "hello").SetWidgetRectangle(new Rectangle(100, 100 - , 100, 100)).SetFont(GetFont()).SetGenericConformanceLevel(PdfUAConformanceLevel.PDFUA_1).CreateText(); + , 100, 100)).SetFont(GetFont()).SetConformance(PdfConformance.PDF_UA_1).CreateText(); field.SetValue("Some value"); field.SetAlternativeName("Some tu entry value"); form.AddField(field); @@ -2283,7 +2283,7 @@ public virtual void TestTextBuilderNoTu() { framework.AddBeforeGenerationHook((pdfDoc) => { PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true); PdfTextFormField field = new TextFormFieldBuilder(pdfDoc, "hello").SetWidgetRectangle(new Rectangle(100, 100 - , 100, 100)).SetFont(GetFont()).SetGenericConformanceLevel(PdfUAConformanceLevel.PDFUA_1).CreateText(); + , 100, 100)).SetFont(GetFont()).SetConformance(PdfConformance.PDF_UA_1).CreateText(); field.SetValue("Some value"); form.AddField(field); } @@ -2297,8 +2297,7 @@ public virtual void TestChoiceBuilderWithTu() { framework.AddBeforeGenerationHook((pdfDoc) => { PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true); PdfChoiceFormField field = new ChoiceFormFieldBuilder(pdfDoc, "hello").SetWidgetRectangle(new Rectangle(100 - , 100, 100, 100)).SetFont(GetFont()).SetGenericConformanceLevel(PdfUAConformanceLevel.PDFUA_1).CreateComboBox - (); + , 100, 100, 100)).SetFont(GetFont()).SetConformance(PdfConformance.PDF_UA_1).CreateComboBox(); field.SetAlternativeName("Some tu entry value"); form.AddField(field); } @@ -2311,8 +2310,7 @@ public virtual void TestChoiceBuilderNoTu() { framework.AddBeforeGenerationHook((pdfDoc) => { PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true); PdfChoiceFormField field = new ChoiceFormFieldBuilder(pdfDoc, "hello").SetWidgetRectangle(new Rectangle(100 - , 100, 100, 100)).SetFont(GetFont()).SetGenericConformanceLevel(PdfUAConformanceLevel.PDFUA_1).CreateComboBox - (); + , 100, 100, 100)).SetFont(GetFont()).SetConformance(PdfConformance.PDF_UA_1).CreateComboBox(); form.AddField(field); } ); @@ -2325,8 +2323,7 @@ public virtual void TestButtonBuilderWithTu() { framework.AddBeforeGenerationHook((pdfDoc) => { PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true); PdfButtonFormField field = new PushButtonFormFieldBuilder(pdfDoc, "hello").SetWidgetRectangle(new Rectangle - (100, 100, 100, 100)).SetFont(GetFont()).SetGenericConformanceLevel(PdfUAConformanceLevel.PDFUA_1).CreatePushButton - (); + (100, 100, 100, 100)).SetFont(GetFont()).SetConformance(PdfConformance.PDF_UA_1).CreatePushButton(); field.SetAlternativeName("Some tu entry value"); form.AddField(field); } @@ -2339,8 +2336,7 @@ public virtual void TestButtonBuilderNoTu() { framework.AddBeforeGenerationHook((pdfDoc) => { PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true); PdfButtonFormField field = new PushButtonFormFieldBuilder(pdfDoc, "hello").SetWidgetRectangle(new Rectangle - (100, 100, 100, 100)).SetFont(GetFont()).SetGenericConformanceLevel(PdfUAConformanceLevel.PDFUA_1).CreatePushButton - (); + (100, 100, 100, 100)).SetFont(GetFont()).SetConformance(PdfConformance.PDF_UA_1).CreatePushButton(); form.AddField(field); } ); @@ -2353,8 +2349,7 @@ public virtual void TestButtonBuilderNoTuNotVisible() { framework.AddBeforeGenerationHook((pdfDoc) => { PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true); PdfButtonFormField field = new PushButtonFormFieldBuilder(pdfDoc, "hello").SetWidgetRectangle(new Rectangle - (100, 100, 100, 100)).SetFont(GetFont()).SetGenericConformanceLevel(PdfUAConformanceLevel.PDFUA_1).CreatePushButton - (); + (100, 100, 100, 100)).SetFont(GetFont()).SetConformance(PdfConformance.PDF_UA_1).CreatePushButton(); IList annList = field.GetChildFormAnnotations(); annList[0].SetVisibility(PdfFormAnnotation.HIDDEN); form.AddField(field); @@ -2402,8 +2397,7 @@ public virtual void TestSignatureBuilderWithTu() { framework.AddBeforeGenerationHook((pdfDoc) => { PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true); PdfSignatureFormField field = new SignatureFormFieldBuilder(pdfDoc, "hello").SetWidgetRectangle(new Rectangle - (100, 100, 100, 100)).SetFont(GetFont()).SetGenericConformanceLevel(PdfUAConformanceLevel.PDFUA_1).CreateSignature - (); + (100, 100, 100, 100)).SetFont(GetFont()).SetConformance(PdfConformance.PDF_UA_1).CreateSignature(); field.SetValue("some value"); field.SetAlternativeName("Some tu entry value"); form.AddField(field); @@ -2417,8 +2411,7 @@ public virtual void TestSignatureBuilderNoTu() { framework.AddBeforeGenerationHook((pdfDoc) => { PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true); PdfSignatureFormField field = new SignatureFormFieldBuilder(pdfDoc, "hello").SetWidgetRectangle(new Rectangle - (100, 100, 100, 100)).SetFont(GetFont()).SetGenericConformanceLevel(PdfUAConformanceLevel.PDFUA_1).CreateSignature - (); + (100, 100, 100, 100)).SetFont(GetFont()).SetConformance(PdfConformance.PDF_UA_1).CreateSignature(); field.SetValue("some value"); form.AddField(field); } @@ -2432,7 +2425,7 @@ public virtual void TestFormFieldWithAltEntry() { framework.AddBeforeGenerationHook((pdfDoc) => { PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true); PdfTextFormField field = new TextFormFieldBuilder(pdfDoc, "hello").SetWidgetRectangle(new Rectangle(100, 100 - , 100, 100)).SetFont(GetFont()).SetGenericConformanceLevel(PdfUAConformanceLevel.PDFUA_1).CreateText(); + , 100, 100)).SetFont(GetFont()).SetConformance(PdfConformance.PDF_UA_1).CreateText(); field.SetValue("Some value"); pdfDoc.GetTagStructureContext().GetAutoTaggingPointer().AddTag(new DefaultAccessibilityProperties(StandardRoles .FORM).SetAlternateDescription("alternate description")); diff --git a/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUAFormulaTest.cs b/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUAFormulaTest.cs index 162c77698a..d247baee69 100644 --- a/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUAFormulaTest.cs +++ b/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUAFormulaTest.cs @@ -56,12 +56,12 @@ public virtual void InitializeFramework() { [NUnit.Framework.Test] public virtual void LayoutTest01() { - framework.AddSuppliers(new _Generator_74()); + framework.AddSuppliers(new _Generator_73()); framework.AssertBothFail("layout01"); } - private sealed class _Generator_74 : UaValidationTestFramework.Generator { - public _Generator_74() { + private sealed class _Generator_73 : UaValidationTestFramework.Generator { + public _Generator_73() { } public IBlockElement Generate() { @@ -73,12 +73,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void LayoutTest02() { - framework.AddSuppliers(new _Generator_87()); + framework.AddSuppliers(new _Generator_86()); framework.AssertBothValid("layout02"); } - private sealed class _Generator_87 : UaValidationTestFramework.Generator { - public _Generator_87() { + private sealed class _Generator_86 : UaValidationTestFramework.Generator { + public _Generator_86() { } public IBlockElement Generate() { @@ -91,12 +91,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void LayoutTest03() { - framework.AddSuppliers(new _Generator_102()); + framework.AddSuppliers(new _Generator_101()); framework.AssertBothValid("layout03"); } - private sealed class _Generator_102 : UaValidationTestFramework.Generator { - public _Generator_102() { + private sealed class _Generator_101 : UaValidationTestFramework.Generator { + public _Generator_101() { } public IBlockElement Generate() { @@ -109,12 +109,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void LayoutTest04() { - framework.AddSuppliers(new _Generator_117()); + framework.AddSuppliers(new _Generator_116()); framework.AssertBothFail("layout04"); } - private sealed class _Generator_117 : UaValidationTestFramework.Generator { - public _Generator_117() { + private sealed class _Generator_116 : UaValidationTestFramework.Generator { + public _Generator_116() { } public IBlockElement Generate() { @@ -127,12 +127,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void LayoutTest05() { - framework.AddSuppliers(new _Generator_131()); + framework.AddSuppliers(new _Generator_130()); framework.AssertBothValid("layout05"); } - private sealed class _Generator_131 : UaValidationTestFramework.Generator { - public _Generator_131() { + private sealed class _Generator_130 : UaValidationTestFramework.Generator { + public _Generator_130() { } public IBlockElement Generate() { @@ -145,13 +145,13 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void LayoutTest06() { - framework.AddSuppliers(new _Generator_145()); + framework.AddSuppliers(new _Generator_144()); framework.AssertBothFail("layout06", MessageFormatUtil.Format(PdfUAExceptionMessageConstants.GLYPH_IS_NOT_DEFINED_OR_WITHOUT_UNICODE , "⫊"), false); } - private sealed class _Generator_145 : UaValidationTestFramework.Generator { - public _Generator_145() { + private sealed class _Generator_144 : UaValidationTestFramework.Generator { + public _Generator_144() { } public IBlockElement Generate() { @@ -164,13 +164,13 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void LayoutTest07() { - framework.AddSuppliers(new _Generator_160()); + framework.AddSuppliers(new _Generator_159()); framework.AssertBothFail("layout07", MessageFormatUtil.Format(PdfUAExceptionMessageConstants.GLYPH_IS_NOT_DEFINED_OR_WITHOUT_UNICODE , "⫊"), false); } - private sealed class _Generator_160 : UaValidationTestFramework.Generator { - public _Generator_160() { + private sealed class _Generator_159 : UaValidationTestFramework.Generator { + public _Generator_159() { } public IBlockElement Generate() { @@ -183,7 +183,7 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void LayoutWithValidRole() { - framework.AddSuppliers(new _Generator_175()); + framework.AddSuppliers(new _Generator_174()); framework.AddBeforeGenerationHook((pdfDocument) => { PdfStructTreeRoot tagStructureContext = pdfDocument.GetStructTreeRoot(); tagStructureContext.AddRoleMapping("BING", StandardRoles.FORMULA); @@ -192,8 +192,8 @@ public virtual void LayoutWithValidRole() { framework.AssertBothValid("layoutWithValidRole"); } - private sealed class _Generator_175 : UaValidationTestFramework.Generator { - public _Generator_175() { + private sealed class _Generator_174 : UaValidationTestFramework.Generator { + public _Generator_174() { } public IBlockElement Generate() { @@ -206,7 +206,7 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void LayoutWithValidRoleButNoAlternateDescription() { - framework.AddSuppliers(new _Generator_194()); + framework.AddSuppliers(new _Generator_193()); framework.AddBeforeGenerationHook((pdfDocument) => { PdfStructTreeRoot tagStructureContext = pdfDocument.GetStructTreeRoot(); tagStructureContext.AddRoleMapping("BING", StandardRoles.FORMULA); @@ -215,8 +215,8 @@ public virtual void LayoutWithValidRoleButNoAlternateDescription() { framework.AssertBothFail("layoutWithValidRoleButNoDescription"); } - private sealed class _Generator_194 : UaValidationTestFramework.Generator { - public _Generator_194() { + private sealed class _Generator_193 : UaValidationTestFramework.Generator { + public _Generator_193() { } public IBlockElement Generate() { diff --git a/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUAGraphicsTest.cs b/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUAGraphicsTest.cs index 7c2ca8a919..4de3074705 100644 --- a/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUAGraphicsTest.cs +++ b/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUAGraphicsTest.cs @@ -68,8 +68,7 @@ public virtual void InitializeFramework() { [NUnit.Framework.Test] public virtual void ImageWithoutAlternativeDescription_ThrowsInLayout() { - PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(new MemoryStream(), new WriterProperties().AddUAXmpMetadata - ().SetPdfVersion(PdfVersion.PDF_1_7))); + PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(new MemoryStream())); Document document = new Document(pdfDoc); iText.Layout.Element.Image img = new Image(ImageDataFactory.Create(DOG)); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfUAConformanceException), () => { @@ -86,8 +85,7 @@ public virtual void LayoutCheckUtilTest() { [NUnit.Framework.Test] public virtual void ImageWithEmptyAlternativeDescription_ThrowsInLayout() { - PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(new MemoryStream(), new WriterProperties().AddUAXmpMetadata - ().SetPdfVersion(PdfVersion.PDF_1_7))); + PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(new MemoryStream())); Document document = new Document(pdfDoc); iText.Layout.Element.Image img = new iText.Layout.Element.Image(ImageDataFactory.Create(DOG)); img.GetAccessibilityProperties().SetAlternateDescription(""); @@ -105,12 +103,12 @@ public virtual void ImageCustomRole_Ok() { root.AddRoleMapping("CustomImage", StandardRoles.FIGURE); } ); - framework.AddSuppliers(new _Generator_127()); + framework.AddSuppliers(new _Generator_121()); framework.AssertBothValid("imageWithCustomRoleOk"); } - private sealed class _Generator_127 : UaValidationTestFramework.Generator { - public _Generator_127() { + private sealed class _Generator_121 : UaValidationTestFramework.Generator { + public _Generator_121() { } public IBlockElement Generate() { @@ -135,12 +133,12 @@ public virtual void ImageCustomDoubleMapping_Ok() { root.AddRoleMapping("CustomImage2", "CustomImage"); } ); - framework.AddSuppliers(new _Generator_151()); + framework.AddSuppliers(new _Generator_145()); framework.AssertBothValid("imageWithDoubleMapping"); } - private sealed class _Generator_151 : UaValidationTestFramework.Generator { - public _Generator_151() { + private sealed class _Generator_145 : UaValidationTestFramework.Generator { + public _Generator_145() { } public IBlockElement Generate() { @@ -164,12 +162,12 @@ public virtual void ImageCustomRoleNoAlternateDescription_Throws() { root.AddRoleMapping("CustomImage", StandardRoles.FIGURE); } ); - framework.AddSuppliers(new _Generator_174()); + framework.AddSuppliers(new _Generator_168()); framework.AssertBothFail("imageWithCustomRoleAndNoDescription"); } - private sealed class _Generator_174 : UaValidationTestFramework.Generator { - public _Generator_174() { + private sealed class _Generator_168 : UaValidationTestFramework.Generator { + public _Generator_168() { } public IBlockElement Generate() { @@ -193,12 +191,12 @@ public virtual void ImageCustomDoubleMapping_Throws() { root.AddRoleMapping("CustomImage2", "CustomImage"); } ); - framework.AddSuppliers(new _Generator_197()); + framework.AddSuppliers(new _Generator_191()); framework.AssertBothFail("imageCustomDoubleMapping_Throws"); } - private sealed class _Generator_197 : UaValidationTestFramework.Generator { - public _Generator_197() { + private sealed class _Generator_191 : UaValidationTestFramework.Generator { + public _Generator_191() { } public IBlockElement Generate() { @@ -217,8 +215,7 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void ImageWithValidAlternativeDescription_OK() { String OUTPUT_FILE = DESTINATION_FOLDER + "imageWithValidAlternativeDescription_OK.pdf"; - PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(OUTPUT_FILE, new WriterProperties().AddUAXmpMetadata - ().SetPdfVersion(PdfVersion.PDF_1_7))); + PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(OUTPUT_FILE)); Document document = new Document(pdfDoc); iText.Layout.Element.Image img = new iText.Layout.Element.Image(ImageDataFactory.Create(DOG)); img.GetAccessibilityProperties().SetAlternateDescription("Alternative description"); @@ -233,8 +230,7 @@ public virtual void ImageWithValidAlternativeDescription_OK() { [NUnit.Framework.Test] public virtual void ImageWithValidActualText_OK() { String OUTPUT_FILE = DESTINATION_FOLDER + "imageWithValidActualText_OK.pdf"; - PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(OUTPUT_FILE, new WriterProperties().AddUAXmpMetadata - ().SetPdfVersion(PdfVersion.PDF_1_7))); + PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(OUTPUT_FILE)); Document document = new Document(pdfDoc); iText.Layout.Element.Image img = new iText.Layout.Element.Image(ImageDataFactory.Create(DOG)); img.GetAccessibilityProperties().SetActualText("Actual text"); @@ -249,8 +245,7 @@ public virtual void ImageWithValidActualText_OK() { [NUnit.Framework.Test] public virtual void ImageWithCaption_OK() { String OUTPUT_FILE = DESTINATION_FOLDER + "imageWithCaption_OK.pdf"; - PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(OUTPUT_FILE, new WriterProperties().AddUAXmpMetadata - ().SetPdfVersion(PdfVersion.PDF_1_7))); + PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(OUTPUT_FILE)); Document document = new Document(pdfDoc); Div imgWithCaption = new Div(); imgWithCaption.GetAccessibilityProperties().SetRole(StandardRoles.FIGURE); @@ -272,8 +267,7 @@ public virtual void ImageWithCaption_OK() { [NUnit.Framework.Test] public virtual void ImageWithCaptionWithoutAlternateDescription_Throws() { - PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(new MemoryStream(), new WriterProperties().AddUAXmpMetadata - ().SetPdfVersion(PdfVersion.PDF_1_7))); + PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(new MemoryStream())); Document document = new Document(pdfDoc); Div imgWithCaption = new Div(); imgWithCaption.GetAccessibilityProperties().SetRole(StandardRoles.FIGURE); @@ -295,8 +289,7 @@ public virtual void ImageWithCaptionWithoutAlternateDescription_Throws() { [NUnit.Framework.Test] public virtual void ImageWithoutActualText_ThrowsInLayout() { - PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(new MemoryStream(), new WriterProperties().AddUAXmpMetadata - ().SetPdfVersion(PdfVersion.PDF_1_7))); + PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(new MemoryStream())); Document document = new Document(pdfDoc); iText.Layout.Element.Image img = new iText.Layout.Element.Image(ImageDataFactory.Create(DOG)); img.GetAccessibilityProperties().SetActualText(null); @@ -309,8 +302,7 @@ public virtual void ImageWithoutActualText_ThrowsInLayout() { [NUnit.Framework.Test] public virtual void ImageWithEmptyActualText_ThrowsInLayout() { - PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(new MemoryStream(), new WriterProperties().AddUAXmpMetadata - ().SetPdfVersion(PdfVersion.PDF_1_7))); + PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(new MemoryStream())); Document document = new Document(pdfDoc); iText.Layout.Element.Image img = new iText.Layout.Element.Image(ImageDataFactory.Create(DOG)); img.GetAccessibilityProperties().SetActualText(""); @@ -320,8 +312,7 @@ public virtual void ImageWithEmptyActualText_ThrowsInLayout() { [NUnit.Framework.Test] public virtual void ImageDirectlyOnCanvas_OK() { String OUTPUT_FILE = DESTINATION_FOLDER + "imageDirectlyOnCanvas_OK.pdf"; - PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(OUTPUT_FILE, new WriterProperties().AddUAXmpMetadata - ().SetPdfVersion(PdfVersion.PDF_1_7))); + PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(OUTPUT_FILE)); Document document = new Document(pdfDoc); iText.Layout.Element.Image img = new iText.Layout.Element.Image(ImageDataFactory.Create(DOG)); img.GetAccessibilityProperties().SetAlternateDescription("Hello"); @@ -352,8 +343,7 @@ public virtual void ImageDirectlyOnCanvas_OK() { [NUnit.Framework.Test] public virtual void ImageDirectlyOnCanvasWithoutAlternateDescription_ThrowsOnClose() { - PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(new MemoryStream(), new WriterProperties().AddUAXmpMetadata - ().SetPdfVersion(PdfVersion.PDF_1_7))); + PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(new MemoryStream())); TagTreePointer pointerForImage = new TagTreePointer(pdfDoc); PdfPage page = pdfDoc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(page); @@ -371,8 +361,7 @@ public virtual void ImageDirectlyOnCanvasWithoutAlternateDescription_ThrowsOnClo [NUnit.Framework.Test] public virtual void ImageDirectlyOnCanvasWithEmptyActualText_OK() { - PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(new MemoryStream(), new WriterProperties().AddUAXmpMetadata - ().SetPdfVersion(PdfVersion.PDF_1_7))); + PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(new MemoryStream())); TagTreePointer pointerForImage = new TagTreePointer(pdfDoc); PdfPage page = pdfDoc.AddNewPage(); PdfCanvas canvas = new PdfCanvas(page); @@ -387,8 +376,7 @@ public virtual void ImageDirectlyOnCanvasWithEmptyActualText_OK() { [NUnit.Framework.Test] public virtual void TestOverflowImage() { - PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(new MemoryStream(), new WriterProperties().AddUAXmpMetadata - ().SetPdfVersion(PdfVersion.PDF_1_7))); + PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(new MemoryStream())); iText.Layout.Element.Image img = new iText.Layout.Element.Image(ImageDataFactory.Create(DOG)); Document document = new Document(pdfDoc); document.Add(new Div().SetHeight(730).SetBackgroundColor(ColorConstants.CYAN)); @@ -400,8 +388,7 @@ public virtual void TestOverflowImage() { [NUnit.Framework.Test] public virtual void TestEmbeddedImageInTable() { - PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(new MemoryStream(), new WriterProperties().AddUAXmpMetadata - ().SetPdfVersion(PdfVersion.PDF_1_7))); + PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(new MemoryStream())); iText.Layout.Element.Image img = new iText.Layout.Element.Image(ImageDataFactory.Create(DOG)); Document document = new Document(pdfDoc); Table table = new Table(2); @@ -417,8 +404,7 @@ public virtual void TestEmbeddedImageInTable() { [NUnit.Framework.Test] public virtual void TestEmbeddedImageInDiv() { - PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(new MemoryStream(), new WriterProperties().AddUAXmpMetadata - ().SetPdfVersion(PdfVersion.PDF_1_7))); + PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(new MemoryStream())); iText.Layout.Element.Image img = new iText.Layout.Element.Image(ImageDataFactory.Create(DOG)); Document document = new Document(pdfDoc); Div div = new Div(); @@ -431,8 +417,7 @@ public virtual void TestEmbeddedImageInDiv() { [NUnit.Framework.Test] public virtual void TestEmbeddedImageInParagraph() { - PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(new MemoryStream(), new WriterProperties().AddUAXmpMetadata - ().SetPdfVersion(PdfVersion.PDF_1_7))); + PdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(new MemoryStream())); iText.Layout.Element.Image img = new iText.Layout.Element.Image(ImageDataFactory.Create(DOG)); Document document = new Document(pdfDoc); Div div = new Div(); diff --git a/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUAHeadingsTest.cs b/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUAHeadingsTest.cs index 4f89f630d1..680dbbd8b8 100644 --- a/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUAHeadingsTest.cs +++ b/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUAHeadingsTest.cs @@ -34,6 +34,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Layout.Element; using iText.Pdfua; using iText.Pdfua.Exceptions; +using iText.Pdfua.Logs; using iText.Test; using iText.Test.Attributes; using iText.Test.Pdfa; @@ -66,12 +67,12 @@ public virtual void InitializeFramework() { // -------- Negative tests -------- [NUnit.Framework.Test] public virtual void AddH2AsFirstHeaderTest() { - framework.AddSuppliers(new _Generator_83()); + framework.AddSuppliers(new _Generator_81()); framework.AssertBothFail("addH2FirstHeaderTest", PdfUAExceptionMessageConstants.H1_IS_SKIPPED); } - private sealed class _Generator_83 : UaValidationTestFramework.Generator { - public _Generator_83() { + private sealed class _Generator_81 : UaValidationTestFramework.Generator { + public _Generator_81() { } public IBlockElement Generate() { @@ -84,14 +85,14 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void BrokenHnParallelSequenceTest() { - framework.AddSuppliers(new _Generator_99()); - framework.AddSuppliers(new _Generator_108()); + framework.AddSuppliers(new _Generator_97()); + framework.AddSuppliers(new _Generator_106()); framework.AssertBothFail("brokenHnParallelSequenceTest", MessageFormatUtil.Format(PdfUAExceptionMessageConstants .HN_IS_SKIPPED, 2)); } - private sealed class _Generator_99 : UaValidationTestFramework.Generator { - public _Generator_99() { + private sealed class _Generator_97 : UaValidationTestFramework.Generator { + public _Generator_97() { } public IBlockElement Generate() { @@ -102,8 +103,8 @@ public IBlockElement Generate() { } } - private sealed class _Generator_108 : UaValidationTestFramework.Generator { - public _Generator_108() { + private sealed class _Generator_106 : UaValidationTestFramework.Generator { + public _Generator_106() { } public IBlockElement Generate() { @@ -116,13 +117,13 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void BrokenHnInheritedSequenceTest1() { - framework.AddSuppliers(new _Generator_123()); + framework.AddSuppliers(new _Generator_121()); framework.AssertBothFail("brokenHnInheritedSequenceTest1", MessageFormatUtil.Format(PdfUAExceptionMessageConstants .HN_IS_SKIPPED, 2)); } - private sealed class _Generator_123 : UaValidationTestFramework.Generator { - public _Generator_123() { + private sealed class _Generator_121 : UaValidationTestFramework.Generator { + public _Generator_121() { } public IBlockElement Generate() { @@ -139,13 +140,13 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void BrokenHnMixedSequenceTest() { - framework.AddSuppliers(new _Generator_143()); + framework.AddSuppliers(new _Generator_141()); framework.AssertBothFail("brokenHnMixedSequenceTest", MessageFormatUtil.Format(PdfUAExceptionMessageConstants .HN_IS_SKIPPED, 3)); } - private sealed class _Generator_143 : UaValidationTestFramework.Generator { - public _Generator_143() { + private sealed class _Generator_141 : UaValidationTestFramework.Generator { + public _Generator_141() { } public IBlockElement Generate() { @@ -166,13 +167,13 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void BrokenHnMixedSequenceTest2() { - framework.AddSuppliers(new _Generator_168()); + framework.AddSuppliers(new _Generator_166()); framework.AssertBothFail("brokenHnMixedSequenceTest2", MessageFormatUtil.Format(PdfUAExceptionMessageConstants .HN_IS_SKIPPED, 3)); } - private sealed class _Generator_168 : UaValidationTestFramework.Generator { - public _Generator_168() { + private sealed class _Generator_166 : UaValidationTestFramework.Generator { + public _Generator_166() { } public IBlockElement Generate() { @@ -196,12 +197,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void FewHInOneNodeTest() { - framework.AddSuppliers(new _Generator_197()); + framework.AddSuppliers(new _Generator_195()); framework.AssertBothFail("fewHInOneNodeTest", PdfUAExceptionMessageConstants.MORE_THAN_ONE_H_TAG); } - private sealed class _Generator_197 : UaValidationTestFramework.Generator { - public _Generator_197() { + private sealed class _Generator_195 : UaValidationTestFramework.Generator { + public _Generator_195() { } public IBlockElement Generate() { @@ -221,13 +222,13 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void FewHInDocumentTest() { - framework.AddSuppliers(new _Generator_222()); - framework.AddSuppliers(new _Generator_231()); + framework.AddSuppliers(new _Generator_220()); + framework.AddSuppliers(new _Generator_229()); framework.AssertBothFail("fewHInDocumentTest", PdfUAExceptionMessageConstants.MORE_THAN_ONE_H_TAG); } - private sealed class _Generator_222 : UaValidationTestFramework.Generator { - public _Generator_222() { + private sealed class _Generator_220 : UaValidationTestFramework.Generator { + public _Generator_220() { } public IBlockElement Generate() { @@ -238,8 +239,8 @@ public IBlockElement Generate() { } } - private sealed class _Generator_231 : UaValidationTestFramework.Generator { - public _Generator_231() { + private sealed class _Generator_229 : UaValidationTestFramework.Generator { + public _Generator_229() { } public IBlockElement Generate() { @@ -252,14 +253,14 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void HAndHnInDocumentTest1() { - framework.AddSuppliers(new _Generator_246()); - framework.AddSuppliers(new _Generator_255()); + framework.AddSuppliers(new _Generator_244()); + framework.AddSuppliers(new _Generator_253()); framework.AssertBothFail("hAndHnInDocumentTest1", PdfUAExceptionMessageConstants.DOCUMENT_USES_BOTH_H_AND_HN ); } - private sealed class _Generator_246 : UaValidationTestFramework.Generator { - public _Generator_246() { + private sealed class _Generator_244 : UaValidationTestFramework.Generator { + public _Generator_244() { } public IBlockElement Generate() { @@ -270,8 +271,8 @@ public IBlockElement Generate() { } } - private sealed class _Generator_255 : UaValidationTestFramework.Generator { - public _Generator_255() { + private sealed class _Generator_253 : UaValidationTestFramework.Generator { + public _Generator_253() { } public IBlockElement Generate() { @@ -284,14 +285,14 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void HAndHnInDocumentTest2() { - framework.AddSuppliers(new _Generator_270()); - framework.AddSuppliers(new _Generator_279()); + framework.AddSuppliers(new _Generator_268()); + framework.AddSuppliers(new _Generator_277()); framework.AssertBothFail("hAndHnInDocumentTest2", PdfUAExceptionMessageConstants.DOCUMENT_USES_BOTH_H_AND_HN ); } - private sealed class _Generator_270 : UaValidationTestFramework.Generator { - public _Generator_270() { + private sealed class _Generator_268 : UaValidationTestFramework.Generator { + public _Generator_268() { } public IBlockElement Generate() { @@ -302,8 +303,8 @@ public IBlockElement Generate() { } } - private sealed class _Generator_279 : UaValidationTestFramework.Generator { - public _Generator_279() { + private sealed class _Generator_277 : UaValidationTestFramework.Generator { + public _Generator_277() { } public IBlockElement Generate() { @@ -316,13 +317,13 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void HAndHnInDocumentTest3() { - framework.AddSuppliers(new _Generator_294()); + framework.AddSuppliers(new _Generator_292()); framework.AssertBothFail("hAndHnInDocumentTest3", PdfUAExceptionMessageConstants.DOCUMENT_USES_BOTH_H_AND_HN ); } - private sealed class _Generator_294 : UaValidationTestFramework.Generator { - public _Generator_294() { + private sealed class _Generator_292 : UaValidationTestFramework.Generator { + public _Generator_292() { } public IBlockElement Generate() { @@ -343,7 +344,7 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void RoleMappingTest() { - framework.AddSuppliers(new _Generator_319()); + framework.AddSuppliers(new _Generator_317()); framework.AddBeforeGenerationHook((pdfDocument) => { PdfStructTreeRoot root = pdfDocument.GetStructTreeRoot(); root.AddRoleMapping("header1", StandardRoles.H1); @@ -353,8 +354,8 @@ public virtual void RoleMappingTest() { framework.AssertBothFail("rolemappingTest"); } - private sealed class _Generator_319 : UaValidationTestFramework.Generator { - public _Generator_319() { + private sealed class _Generator_317 : UaValidationTestFramework.Generator { + public _Generator_317() { } public IBlockElement Generate() { @@ -371,7 +372,7 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void RoleMappingTestValid() { - framework.AddSuppliers(new _Generator_344()); + framework.AddSuppliers(new _Generator_342()); framework.AddBeforeGenerationHook((pdfDocument) => { PdfStructTreeRoot root = pdfDocument.GetStructTreeRoot(); root.AddRoleMapping("header1", StandardRoles.H1); @@ -381,8 +382,8 @@ public virtual void RoleMappingTestValid() { framework.AssertBothValid("rolemappingValid"); } - private sealed class _Generator_344 : UaValidationTestFramework.Generator { - public _Generator_344() { + private sealed class _Generator_342 : UaValidationTestFramework.Generator { + public _Generator_342() { } public IBlockElement Generate() { @@ -462,12 +463,12 @@ public virtual void FlushPreviousPageTest() { // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf/ua validation on Android) [NUnit.Framework.Test] public virtual void HnInheritedSequenceTest() { - framework.AddSuppliers(new _Generator_449()); + framework.AddSuppliers(new _Generator_447()); framework.AssertBothValid("hnInheritedSequenceTest"); } - private sealed class _Generator_449 : UaValidationTestFramework.Generator { - public _Generator_449() { + private sealed class _Generator_447 : UaValidationTestFramework.Generator { + public _Generator_447() { } public IBlockElement Generate() { @@ -488,13 +489,13 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void HnCompareWithLastFromAnotherBranchTest() { - framework.AddSuppliers(new _Generator_473()); - framework.AddSuppliers(new _Generator_497()); + framework.AddSuppliers(new _Generator_471()); + framework.AddSuppliers(new _Generator_495()); framework.AssertBothValid("hnInheritedSequenceTest"); } - private sealed class _Generator_473 : UaValidationTestFramework.Generator { - public _Generator_473() { + private sealed class _Generator_471 : UaValidationTestFramework.Generator { + public _Generator_471() { } public IBlockElement Generate() { @@ -517,8 +518,8 @@ public IBlockElement Generate() { } } - private sealed class _Generator_497 : UaValidationTestFramework.Generator { - public _Generator_497() { + private sealed class _Generator_495 : UaValidationTestFramework.Generator { + public _Generator_495() { } public IBlockElement Generate() { @@ -531,13 +532,13 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void HnCompareWithLastFromAnotherBranchTest2() { - framework.AddSuppliers(new _Generator_511()); - framework.AddSuppliers(new _Generator_535()); + framework.AddSuppliers(new _Generator_509()); + framework.AddSuppliers(new _Generator_533()); framework.AssertBothValid("hnCompareWithLastFromAnotherBranchTest2"); } - private sealed class _Generator_511 : UaValidationTestFramework.Generator { - public _Generator_511() { + private sealed class _Generator_509 : UaValidationTestFramework.Generator { + public _Generator_509() { } public IBlockElement Generate() { @@ -560,8 +561,8 @@ public IBlockElement Generate() { } } - private sealed class _Generator_535 : UaValidationTestFramework.Generator { - public _Generator_535() { + private sealed class _Generator_533 : UaValidationTestFramework.Generator { + public _Generator_533() { } public IBlockElement Generate() { @@ -574,12 +575,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void HnInheritedSequenceTest2() { - framework.AddSuppliers(new _Generator_549()); + framework.AddSuppliers(new _Generator_547()); framework.AssertBothValid("hnCompareWithLastFromAnotherBranchTest2"); } - private sealed class _Generator_549 : UaValidationTestFramework.Generator { - public _Generator_549() { + private sealed class _Generator_547 : UaValidationTestFramework.Generator { + public _Generator_547() { } public IBlockElement Generate() { @@ -604,14 +605,14 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void HnParallelSequenceTest() { - framework.AddSuppliers(new _Generator_578()); - framework.AddSuppliers(new _Generator_587()); - framework.AddSuppliers(new _Generator_596()); + framework.AddSuppliers(new _Generator_576()); + framework.AddSuppliers(new _Generator_585()); + framework.AddSuppliers(new _Generator_594()); framework.AssertBothValid("hnParallelSequenceTest"); } - private sealed class _Generator_578 : UaValidationTestFramework.Generator { - public _Generator_578() { + private sealed class _Generator_576 : UaValidationTestFramework.Generator { + public _Generator_576() { } public IBlockElement Generate() { @@ -622,8 +623,8 @@ public IBlockElement Generate() { } } - private sealed class _Generator_587 : UaValidationTestFramework.Generator { - public _Generator_587() { + private sealed class _Generator_585 : UaValidationTestFramework.Generator { + public _Generator_585() { } public IBlockElement Generate() { @@ -634,8 +635,8 @@ public IBlockElement Generate() { } } - private sealed class _Generator_596 : UaValidationTestFramework.Generator { - public _Generator_596() { + private sealed class _Generator_594 : UaValidationTestFramework.Generator { + public _Generator_594() { } public IBlockElement Generate() { @@ -675,15 +676,15 @@ public virtual void UsualHTest() { // with the same code, but div role is replaced by section role [NUnit.Framework.Test] public virtual void UsualHTest2() { - framework.AddSuppliers(new _Generator_644()); - framework.AddSuppliers(new _Generator_653()); + framework.AddSuppliers(new _Generator_642()); + framework.AddSuppliers(new _Generator_651()); // The test code is the same as in usualHTest with one exception: // the next line where another grouping element is defined. framework.AssertBothValid("hnParallelSequenceTest"); } - private sealed class _Generator_644 : UaValidationTestFramework.Generator { - public _Generator_644() { + private sealed class _Generator_642 : UaValidationTestFramework.Generator { + public _Generator_642() { } public IBlockElement Generate() { @@ -694,8 +695,8 @@ public IBlockElement Generate() { } } - private sealed class _Generator_653 : UaValidationTestFramework.Generator { - public _Generator_653() { + private sealed class _Generator_651 : UaValidationTestFramework.Generator { + public _Generator_651() { } public IBlockElement Generate() { @@ -714,12 +715,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void HnMixedSequenceTest() { - framework.AddSuppliers(new _Generator_676()); + framework.AddSuppliers(new _Generator_674()); framework.AssertBothValid("hnMixedSequenceTest"); } - private sealed class _Generator_676 : UaValidationTestFramework.Generator { - public _Generator_676() { + private sealed class _Generator_674 : UaValidationTestFramework.Generator { + public _Generator_674() { } public IBlockElement Generate() { @@ -745,12 +746,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void HnMixedSequenceTest2() { - framework.AddSuppliers(new _Generator_706()); + framework.AddSuppliers(new _Generator_704()); framework.AssertBothValid("hnMixedSequenceTest2"); } - private sealed class _Generator_706 : UaValidationTestFramework.Generator { - public _Generator_706() { + private sealed class _Generator_704 : UaValidationTestFramework.Generator { + public _Generator_704() { } public IBlockElement Generate() { @@ -771,12 +772,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void HnMixedSequenceTest3() { - framework.AddSuppliers(new _Generator_730()); + framework.AddSuppliers(new _Generator_728()); framework.AssertBothValid("hnMixedSequenceTest3"); } - private sealed class _Generator_730 : UaValidationTestFramework.Generator { - public _Generator_730() { + private sealed class _Generator_728 : UaValidationTestFramework.Generator { + public _Generator_728() { } public IBlockElement Generate() { diff --git a/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUALayoutTest.cs b/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUALayoutTest.cs index 8f9ed646b3..ce5af9a59b 100644 --- a/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUALayoutTest.cs +++ b/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUALayoutTest.cs @@ -82,7 +82,7 @@ public virtual void SimpleParagraphTest() { // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf/ua validation on Android) [NUnit.Framework.Test] public virtual void SimpleParagraphWithUnderlineTest() { - String outPdf = DESTINATION_FOLDER + "simpleParagraphTest.pdf"; + String outPdf = DESTINATION_FOLDER + "simpleParagraphUnderlinesTest.pdf"; String cmpPdf = SOURCE_FOLDER + "cmp_simpleParagraphWithUnderlineTest.pdf"; PdfUATestPdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(outPdf)); PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.WINANSI, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED @@ -133,12 +133,12 @@ public virtual void SimpleTableTest() { // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf/ua validation on Android) [NUnit.Framework.Test] public virtual void AddNoteWithoutIdTest() { - framework.AddSuppliers(new _Generator_163()); + framework.AddSuppliers(new _Generator_162()); framework.AssertBothFail("noteWithoutID", PdfUAExceptionMessageConstants.NOTE_TAG_SHALL_HAVE_ID_ENTRY); } - private sealed class _Generator_163 : UaValidationTestFramework.Generator { - public _Generator_163() { + private sealed class _Generator_162 : UaValidationTestFramework.Generator { + public _Generator_162() { } public IBlockElement Generate() { @@ -160,13 +160,13 @@ public IBlockElement Generate() { [NUnit.Framework.Test] [LogMessage(iText.IO.Logs.IoLogMessageConstant.NAME_ALREADY_EXISTS_IN_THE_NAME_TREE, Count = 2)] public virtual void AddTwoNotesWithSameIdTest() { - framework.AddSuppliers(new _Generator_185(), new _Generator_201()); + framework.AddSuppliers(new _Generator_184(), new _Generator_200()); framework.AssertBothFail("twoNotesWithSameId", MessageFormatUtil.Format(PdfUAExceptionMessageConstants.NON_UNIQUE_ID_ENTRY_IN_STRUCT_TREE_ROOT , "123"), false); } - private sealed class _Generator_185 : UaValidationTestFramework.Generator { - public _Generator_185() { + private sealed class _Generator_184 : UaValidationTestFramework.Generator { + public _Generator_184() { } public IBlockElement Generate() { @@ -186,8 +186,8 @@ public IBlockElement Generate() { } } - private sealed class _Generator_201 : UaValidationTestFramework.Generator { - public _Generator_201() { + private sealed class _Generator_200 : UaValidationTestFramework.Generator { + public _Generator_200() { } public IBlockElement Generate() { @@ -209,12 +209,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void AddNoteWithValidIdTest() { - framework.AddSuppliers(new _Generator_224()); + framework.AddSuppliers(new _Generator_223()); framework.AssertBothValid("noteWithValidID"); } - private sealed class _Generator_224 : UaValidationTestFramework.Generator { - public _Generator_224() { + private sealed class _Generator_223 : UaValidationTestFramework.Generator { + public _Generator_223() { } public IBlockElement Generate() { @@ -236,12 +236,12 @@ public IBlockElement Generate() { [NUnit.Framework.Test] public virtual void AddTwoNotesWithDifferentIdTest() { - framework.AddSuppliers(new _Generator_245(), new _Generator_261()); + framework.AddSuppliers(new _Generator_244(), new _Generator_260()); framework.AssertBothValid("twoNotesWithDifferentId"); } - private sealed class _Generator_245 : UaValidationTestFramework.Generator { - public _Generator_245() { + private sealed class _Generator_244 : UaValidationTestFramework.Generator { + public _Generator_244() { } public IBlockElement Generate() { @@ -261,8 +261,8 @@ public IBlockElement Generate() { } } - private sealed class _Generator_261 : UaValidationTestFramework.Generator { - public _Generator_261() { + private sealed class _Generator_260 : UaValidationTestFramework.Generator { + public _Generator_260() { } public IBlockElement Generate() { diff --git a/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUATableTest.cs b/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUATableTest.cs index 7f1ca75333..943580631b 100644 --- a/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUATableTest.cs +++ b/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUATableTest.cs @@ -28,7 +28,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Kernel.Pdf.Tagging; using iText.Layout.Element; using iText.Pdfua; -using iText.Pdfua.Exceptions; +using iText.Pdfua.Logs; using iText.Test; using iText.Test.Attributes; @@ -262,7 +262,7 @@ public virtual void TableWithHeaderScopeColumn13() { PdfUATableTest.TableBuilder tableBuilder = new PdfUATableTest.TableBuilder(3); tableBuilder.AddHeaderCell(new PdfUATableTest.HeaderCellSupplier(null, "Header 1", 1, 1, "Column")); tableBuilder.AddHeaderCell(new PdfUATableTest.HeaderCellSupplier(null, "Header 2", 1, 1, "Column")); - tableBuilder.AddHeaderCell(new _Generator_304()); + tableBuilder.AddHeaderCell(new _Generator_302()); for (int i = 0; i < 9; i++) { tableBuilder.AddBodyCell(new PdfUATableTest.DataCellSupplier("Data 1", 1, 1, null)); tableBuilder.AddBodyCell(new PdfUATableTest.DataCellSupplier("Data 1", 1, 1, null)); @@ -271,8 +271,8 @@ public virtual void TableWithHeaderScopeColumn13() { framework.AssertBothFail("tableWithHeaderScopeColumn13"); } - private sealed class _Generator_304 : UaValidationTestFramework.Generator { - public _Generator_304() { + private sealed class _Generator_302 : UaValidationTestFramework.Generator { + public _Generator_302() { } public Cell Generate() { @@ -434,7 +434,7 @@ public virtual void TableWithHeaderRowScope07() { PdfUATableTest.TableBuilder tableBuilder = new PdfUATableTest.TableBuilder(3); tableBuilder.AddBodyCell(new PdfUATableTest.HeaderCellSupplier(null, "Header 1", 1, 1, "Row")); tableBuilder.AddBodyCell(new PdfUATableTest.DataCellSupplier("Data 1", 1, 1, null)); - tableBuilder.AddBodyCell(new _Generator_508()); + tableBuilder.AddBodyCell(new _Generator_506()); tableBuilder.AddBodyCell(new PdfUATableTest.HeaderCellSupplier(null, "Header 1", 1, 1, "Row")); tableBuilder.AddBodyCell(new PdfUATableTest.DataCellSupplier("Data 1", 1, 1, null)); tableBuilder.AddBodyCell(new PdfUATableTest.DataCellSupplier("Data 1", 1, 1, null)); @@ -442,8 +442,8 @@ public virtual void TableWithHeaderRowScope07() { framework.AssertBothFail("tableWithHeaderRowScope07"); } - private sealed class _Generator_508 : UaValidationTestFramework.Generator { - public _Generator_508() { + private sealed class _Generator_506 : UaValidationTestFramework.Generator { + public _Generator_506() { } public Cell Generate() { @@ -876,14 +876,14 @@ public virtual void RoleMapping01() { root.AddRoleMapping("FancyTD", StandardRoles.TD); } )); - tableBuilder.AddBodyCell(new _Generator_1010()); - tableBuilder.AddBodyCell(new _Generator_1020()); + tableBuilder.AddBodyCell(new _Generator_1008()); + tableBuilder.AddBodyCell(new _Generator_1018()); framework.AddSuppliers(tableBuilder); framework.AssertBothValid("tableCustomRoles"); } - private sealed class _Generator_1010 : UaValidationTestFramework.Generator { - public _Generator_1010() { + private sealed class _Generator_1008 : UaValidationTestFramework.Generator { + public _Generator_1008() { } public Cell Generate() { @@ -894,8 +894,8 @@ public Cell Generate() { } } - private sealed class _Generator_1020 : UaValidationTestFramework.Generator { - public _Generator_1020() { + private sealed class _Generator_1018 : UaValidationTestFramework.Generator { + public _Generator_1018() { } public Cell Generate() { diff --git a/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUATest.cs b/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUATest.cs index 18d1ab6259..7d079a2d64 100644 --- a/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUATest.cs +++ b/itext.tests/itext.pdfua.tests/itext/pdfua/checkers/PdfUATest.cs @@ -35,10 +35,12 @@ You should have received a copy of the GNU Affero General Public License using iText.Kernel.Pdf.Tagging; using iText.Kernel.Pdf.Tagutils; using iText.Kernel.Utils; +using iText.Kernel.Validation; using iText.Layout; using iText.Layout.Element; using iText.Pdfua; using iText.Pdfua.Exceptions; +using iText.Pdfua.Logs; using iText.Test; using iText.Test.Attributes; using iText.Test.Pdfa; @@ -74,25 +76,6 @@ public virtual void InitializeFramework() { framework = new UaValidationTestFramework(DESTINATION_FOLDER); } - [NUnit.Framework.Test] - public virtual void FlushingOnPageWarningDisabledDoesntLog() { - String outPdf = DESTINATION_FOLDER + "flushingOnPageCloseLogsWarningDisabledTest.pdf"; - String cmpPdf = SOURCE_FOLDER + "cmp_flushingOnPageCloseLogsWarningDisabledTest.pdf"; - PdfUATestPdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(outPdf)); - pdfDoc.DisablePageFlushingWarning(); - Document document = new Document(pdfDoc); - PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.WINANSI, PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED - ); - document.SetFont(font); - for (int i = 0; i < 40; i++) { - document.Add(new Paragraph("Hello World!")); - } - pdfDoc.GetPage(1).Flush(); - pdfDoc.Close(); - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, DESTINATION_FOLDER, "diff_" - )); - } - [NUnit.Framework.Test] public virtual void CheckPoint01_007_suspectsHasEntryTrue() { PdfUATestPdfDocument pdfDoc = new PdfUATestPdfDocument(new PdfWriter(new MemoryStream())); @@ -153,8 +136,8 @@ public virtual void InvalidUA1DocumentWithFlushedPageTest() { [NUnit.Framework.Test] public virtual void DocumentWithNoLangEntryTest() { String outPdf = DESTINATION_FOLDER + "documentWithNoLangEntryTest.pdf"; - PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outPdf, new WriterProperties().AddUAXmpMetadata().SetPdfVersion - (PdfVersion.PDF_1_7))); + PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outPdf, new WriterProperties().AddPdfUaXmpMetadata(PdfUAConformance + .PDF_UA_1).SetPdfVersion(PdfVersion.PDF_1_7))); pdfDoc.SetTagged(); ValidationContainer validationContainer = new ValidationContainer(); validationContainer.AddChecker(new PdfUA1Checker(pdfDoc)); @@ -170,8 +153,8 @@ public virtual void DocumentWithNoLangEntryTest() { [NUnit.Framework.Test] public virtual void DocumentWithEmptyStringLangEntryTest() { String outPdf = DESTINATION_FOLDER + "documentWithEmptyStringLangEntryTest.pdf"; - PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outPdf, new WriterProperties().AddUAXmpMetadata().SetPdfVersion - (PdfVersion.PDF_1_7))); + PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outPdf, new WriterProperties().AddPdfUaXmpMetadata(PdfUAConformance + .PDF_UA_1).SetPdfVersion(PdfVersion.PDF_1_7))); pdfDoc.SetTagged(); ValidationContainer validationContainer = new ValidationContainer(); validationContainer.AddChecker(new PdfUA1Checker(pdfDoc)); @@ -188,16 +171,8 @@ public virtual void DocumentWithEmptyStringLangEntryTest() { [NUnit.Framework.Test] public virtual void DocumentWithComplexLangEntryTest() { String outPdf = DESTINATION_FOLDER + "documentWithComplexLangEntryTest.pdf"; - PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outPdf, new WriterProperties().AddUAXmpMetadata().SetPdfVersion - (PdfVersion.PDF_1_7))); - pdfDoc.SetTagged(); - ValidationContainer validationContainer = new ValidationContainer(); - validationContainer.AddChecker(new PdfUA1Checker(pdfDoc)); - pdfDoc.GetDiContainer().Register(typeof(ValidationContainer), validationContainer); - pdfDoc.GetCatalog().SetLang(new PdfString("qaa-Qaaa-QM-x-southern")); - pdfDoc.GetCatalog().SetViewerPreferences(new PdfViewerPreferences().SetDisplayDocTitle(true)); - PdfDocumentInfo info = pdfDoc.GetDocumentInfo(); - info.SetTitle("English pangram"); + PdfDocument pdfDoc = new PdfUADocument(new PdfWriter(outPdf), new PdfUAConfig(PdfUAConformance.PDF_UA_1, "English pangram" + , "qaa-Qaaa-QM-x-southern")); pdfDoc.Close(); NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, SOURCE_FOLDER + "cmp_documentWithComplexLangEntryTest.pdf" , DESTINATION_FOLDER, "diff_")); @@ -208,8 +183,8 @@ public virtual void DocumentWithComplexLangEntryTest() { [NUnit.Framework.Test] public virtual void DocumentWithoutViewerPreferencesTest() { String outPdf = DESTINATION_FOLDER + "documentWithoutViewerPreferencesTest.pdf"; - PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outPdf, new WriterProperties().AddUAXmpMetadata().SetPdfVersion - (PdfVersion.PDF_1_7))); + PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outPdf, new WriterProperties().AddPdfUaXmpMetadata(PdfUAConformance + .PDF_UA_1).SetPdfVersion(PdfVersion.PDF_1_7))); pdfDoc.SetTagged(); ValidationContainer validationContainer = new ValidationContainer(); validationContainer.AddChecker(new PdfUA1Checker(pdfDoc)); @@ -224,8 +199,8 @@ public virtual void DocumentWithoutViewerPreferencesTest() { [NUnit.Framework.Test] public virtual void DocumentWithEmptyViewerPreferencesTest() { String outPdf = DESTINATION_FOLDER + "documentWithEmptyViewerPreferencesTest.pdf"; - PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outPdf, new WriterProperties().AddUAXmpMetadata().SetPdfVersion - (PdfVersion.PDF_1_7))); + PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outPdf, new WriterProperties().AddPdfUaXmpMetadata(PdfUAConformance + .PDF_UA_1).SetPdfVersion(PdfVersion.PDF_1_7))); pdfDoc.SetTagged(); ValidationContainer validationContainer = new ValidationContainer(); validationContainer.AddChecker(new PdfUA1Checker(pdfDoc)); @@ -241,8 +216,8 @@ public virtual void DocumentWithEmptyViewerPreferencesTest() { [NUnit.Framework.Test] public virtual void DocumentWithInvalidViewerPreferencesTest() { String outPdf = DESTINATION_FOLDER + "documentWithEmptyViewerPreferencesTest.pdf"; - PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outPdf, new WriterProperties().AddUAXmpMetadata().SetPdfVersion - (PdfVersion.PDF_1_7))); + PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outPdf, new WriterProperties().AddPdfUaXmpMetadata(PdfUAConformance + .PDF_UA_1).SetPdfVersion(PdfVersion.PDF_1_7))); pdfDoc.SetTagged(); ValidationContainer validationContainer = new ValidationContainer(); validationContainer.AddChecker(new PdfUA1Checker(pdfDoc)); @@ -411,8 +386,9 @@ public virtual void OpenDocumentWithDuplicatingIdInStructTree() { [NUnit.Framework.Test] public virtual void ManualPdfUaCreation() { String outPdf = DESTINATION_FOLDER + "manualPdfUaCreation.pdf"; - PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outPdf, new WriterProperties().AddUAXmpMetadata().SetPdfVersion - (PdfVersion.PDF_1_7))); + WriterProperties properties = new WriterProperties().AddPdfUaXmpMetadata(PdfUAConformance.PDF_UA_1).SetPdfVersion + (PdfVersion.PDF_1_7); + PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outPdf, properties)); Document document = new Document(pdfDoc, PageSize.A4.Rotate()); //TAGGED PDF //Make document tagged diff --git a/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUACanvasTest/cmp_01_003_ContentMarkedAsArtifactsPresentInsideTaggedContent.pdf b/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUACanvasXObjectTest/cmp_copyPageAsFormWithCorrectFontXobjectWithUnTaggedPdf.pdf similarity index 85% rename from itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUACanvasTest/cmp_01_003_ContentMarkedAsArtifactsPresentInsideTaggedContent.pdf rename to itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUACanvasXObjectTest/cmp_copyPageAsFormWithCorrectFontXobjectWithUnTaggedPdf.pdf index be27b91d32..4293d9eb0a 100644 Binary files a/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUACanvasTest/cmp_01_003_ContentMarkedAsArtifactsPresentInsideTaggedContent.pdf and b/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUACanvasXObjectTest/cmp_copyPageAsFormWithCorrectFontXobjectWithUnTaggedPdf.pdf differ diff --git a/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUATest/cmp_invalidDocWithFlushedPageTest.pdf b/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUACanvasXObjectTest/cmp_copyPageAsFormXobjectWithUnTaggedPdf.pdf similarity index 64% rename from itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUATest/cmp_invalidDocWithFlushedPageTest.pdf rename to itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUACanvasXObjectTest/cmp_copyPageAsFormXobjectWithUnTaggedPdf.pdf index ffa318c266..e96e7e16ef 100644 Binary files a/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUATest/cmp_invalidDocWithFlushedPageTest.pdf and b/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUACanvasXObjectTest/cmp_copyPageAsFormXobjectWithUnTaggedPdf.pdf differ diff --git a/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUACanvasXObjectTest/cmp_manualPdfUaCreation.pdf b/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUACanvasXObjectTest/cmp_manualPdfUaCreation.pdf new file mode 100644 index 0000000000..db16029824 Binary files /dev/null and b/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUACanvasXObjectTest/cmp_manualPdfUaCreation.pdf differ diff --git a/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUACanvasTest/cmp_01_005_TextContentIsNotInTagTree.pdf b/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUACanvasXObjectTest/cmp_manuallyAddToCanvasWithUnAndCorrectFontUnAndArtifactPdf.pdf similarity index 84% rename from itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUACanvasTest/cmp_01_005_TextContentIsNotInTagTree.pdf rename to itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUACanvasXObjectTest/cmp_manuallyAddToCanvasWithUnAndCorrectFontUnAndArtifactPdf.pdf index f7d58f9479..693feea3cc 100644 Binary files a/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUACanvasTest/cmp_01_005_TextContentIsNotInTagTree.pdf and b/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUACanvasXObjectTest/cmp_manuallyAddToCanvasWithUnAndCorrectFontUnAndArtifactPdf.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/PdfEncryptionTest/encryptedAes128EmbeddedFilesOnly.pdf b/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUACanvasXObjectTest/cmp_manuallyAddToCanvasWithUnTaggedPdf.pdf similarity index 50% rename from itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/PdfEncryptionTest/encryptedAes128EmbeddedFilesOnly.pdf rename to itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUACanvasXObjectTest/cmp_manuallyAddToCanvasWithUnTaggedPdf.pdf index df3c74612d..01fc714ebf 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/crypto/pdfencryption/PdfEncryptionTest/encryptedAes128EmbeddedFilesOnly.pdf and b/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUACanvasXObjectTest/cmp_manuallyAddToCanvasWithUnTaggedPdf.pdf differ diff --git a/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUACanvasXObjectTest/cmp_xobjectTesting.pdf b/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUACanvasXObjectTest/cmp_xobjectTesting.pdf new file mode 100644 index 0000000000..d7b244aa07 Binary files /dev/null and b/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUACanvasXObjectTest/cmp_xobjectTesting.pdf differ diff --git a/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUADocumentTest/usualPdf.pdf b/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUADocumentTest/usualPdf.pdf new file mode 100644 index 0000000000..09ec41b5bb Binary files /dev/null and b/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUADocumentTest/usualPdf.pdf differ diff --git a/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUAHeadingsTest/cmp_roleMappingTest.pdf b/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUAHeadingsTest/cmp_roleMappingTest.pdf deleted file mode 100644 index 65756af185..0000000000 Binary files a/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUAHeadingsTest/cmp_roleMappingTest.pdf and /dev/null differ diff --git a/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUAHeadingsTest/invalidSequence.pdf b/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUAHeadingsTest/invalidSequence.pdf deleted file mode 100644 index f2d886340d..0000000000 Binary files a/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUAHeadingsTest/invalidSequence.pdf and /dev/null differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/RootSvgNodeRendererTest/svg/cmp_invalidHeight.pdf b/itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUAMetadataUnitTest/result.pdf similarity index 100% rename from itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/RootSvgNodeRendererTest/svg/cmp_invalidHeight.pdf rename to itext.tests/itext.pdfua.tests/resources/itext/pdfua/PdfUAMetadataUnitTest/result.pdf diff --git a/itext.tests/itext.sign.tests/Properties/AssemblyInfo.cs b/itext.tests/itext.sign.tests/Properties/AssemblyInfo.cs index 5b100f599a..be68ae2d71 100644 --- a/itext.tests/itext.sign.tests/Properties/AssemblyInfo.cs +++ b/itext.tests/itext.sign.tests/Properties/AssemblyInfo.cs @@ -15,9 +15,9 @@ [assembly: Guid("be15bdf3-b184-4e2f-8459-ebee3160e19d")] -[assembly: AssemblyVersion("8.0.5.0")] -[assembly: AssemblyFileVersion("8.0.5.0")] -[assembly: AssemblyInformationalVersion("8.0.5")] +[assembly: AssemblyVersion("9.0.0.0")] +[assembly: AssemblyFileVersion("9.0.0.0")] +[assembly: AssemblyInformationalVersion("9.0.0")] #if !NETSTANDARD2_0 [assembly: NUnit.Framework.Timeout(300000)] diff --git a/itext.tests/itext.sign.tests/itext/signatures/CertificateSupportedCriticalExtensionsTest.cs b/itext.tests/itext.sign.tests/itext/signatures/CertificateSupportedCriticalExtensionsTest.cs index ac203130a6..e111ec4324 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/CertificateSupportedCriticalExtensionsTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/CertificateSupportedCriticalExtensionsTest.cs @@ -24,6 +24,7 @@ You should have received a copy of the GNU Affero General Public License using System; using System.Collections; using System.Collections.Generic; +using iText.Kernel.Crypto; using iText.Test; using NUnit.Framework; @@ -45,7 +46,7 @@ public void SupportedCriticalOIDsTest() cert.KeyUsage = new bool[] { true, true }; - Assert.False(SignUtils.HasUnsupportedCriticalExtension(cert)); + Assert.False(CertificateVerification.HasUnsupportedCriticalExtension(cert)); } [Test] @@ -59,7 +60,7 @@ public void BasicConstraintsSupportedTest() cert.SetCriticalExtensions(criticalExtensions); - Assert.False(SignUtils.HasUnsupportedCriticalExtension(cert)); + Assert.False(CertificateVerification.HasUnsupportedCriticalExtension(cert)); } [Test] @@ -78,7 +79,7 @@ public void ExtendedKeyUsageWithIdKpTimestampingTest() cert.SetExtendedKeyUsage(extendedKeyUsage); - Assert.False(SignUtils.HasUnsupportedCriticalExtension(cert)); + Assert.False(CertificateVerification.HasUnsupportedCriticalExtension(cert)); } [Test] @@ -97,7 +98,7 @@ public void ExtendedKeyUsageWithoutIdKpTimestampingTest() cert.SetExtendedKeyUsage(extendedKeyUsage); - Assert.False(SignUtils.HasUnsupportedCriticalExtension(cert)); + Assert.False(CertificateVerification.HasUnsupportedCriticalExtension(cert)); } [Test] @@ -110,7 +111,7 @@ public void IdKpTimestampingWithoutExtendedKeyUsageTest() cert.SetExtendedKeyUsage(extendedKeyUsage); - Assert.False(SignUtils.HasUnsupportedCriticalExtension(cert)); + Assert.False(CertificateVerification.HasUnsupportedCriticalExtension(cert)); } [Test] @@ -124,13 +125,13 @@ public void NotSupportedOIDTest() cert.SetCriticalExtensions(criticalExtensions); - Assert.True(SignUtils.HasUnsupportedCriticalExtension(cert)); + Assert.True(CertificateVerification.HasUnsupportedCriticalExtension(cert)); } [Test] public void CertificateIsNullTest() { - Assert.Catch(typeof(ArgumentException), () => SignUtils.HasUnsupportedCriticalExtension(null)); + Assert.Catch(typeof(ArgumentException), () => CertificateVerification.HasUnsupportedCriticalExtension(null)); } [Test] @@ -140,7 +141,7 @@ public void CertificateHasNoExtensionsTest() cert.SetCriticalExtensions(null); - Assert.False(SignUtils.HasUnsupportedCriticalExtension(cert)); + Assert.False(CertificateVerification.HasUnsupportedCriticalExtension(cert)); } } } diff --git a/itext.tests/itext.sign.tests/itext/signatures/CertificateUtilTest.cs b/itext.tests/itext.sign.tests/itext/signatures/CertificateUtilTest.cs index 2a51bc5019..f03cc0a832 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/CertificateUtilTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/CertificateUtilTest.cs @@ -59,13 +59,6 @@ public virtual void GetCRLFromStringNullTest() { NUnit.Framework.Assert.IsNull(CertificateUtil.GetCRL((String)null)); } - [NUnit.Framework.Test] - public virtual void GetCRLFromCertificateWithoutCRLTest() { - IX509Certificate tsaCert = (IX509Certificate)PemFileHelper.ReadFirstChain(CERTS_SRC + "rootRsa.pem")[0]; - IX509Crl crl = CertificateUtil.GetCRL(tsaCert); - NUnit.Framework.Assert.IsNull(crl); - } - [NUnit.Framework.Test] public virtual void GetCRLsFromCertificateWithoutCRLTest() { IX509Certificate tsaCert = (IX509Certificate)PemFileHelper.ReadFirstChain(CERTS_SRC + "rootRsa.pem")[0]; diff --git a/itext.tests/itext.sign.tests/itext/signatures/DigestAlgorithmsManualTest.cs b/itext.tests/itext.sign.tests/itext/signatures/DigestAlgorithmsManualTest.cs index 210c7eba4c..ed80312612 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/DigestAlgorithmsManualTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/DigestAlgorithmsManualTest.cs @@ -22,12 +22,22 @@ You should have received a copy of the GNU Affero General Public License */ using System; using System.IO; +using iText.Bouncycastleconnector; +using iText.Commons.Bouncycastle; +using iText.Kernel.Crypto; +using iText.Kernel.Logs; +using iText.Signatures.Logs; using iText.Test; +using iText.Test.Attributes; namespace iText.Signatures { + [NUnit.Framework.Category("BouncyCastleUnitTest")] public class DigestAlgorithmsManualTest : ExtendedITextTest { + private static readonly IBouncyCastleFactory BOUNCY_CASTLE_FACTORY = BouncyCastleFactoryCreator.GetFactory(); + private static readonly bool FIPS_MODE = "BCFIPS".Equals(BOUNCY_CASTLE_FACTORY.GetProviderName()); + [NUnit.Framework.Test] public virtual void DigestSHA1SunPKCS11Test() { @@ -54,5 +64,13 @@ public virtual void DigestSHA256SUNTest() }; NUnit.Framework.Assert.AreEqual(expected, hash); } + + [LogMessage(KernelLogMessageConstant.ALGORITHM_NOT_FROM_SPEC, Ignore = true)] + [NUnit.Framework.Test] + public virtual void NotAllowedNameGetAllowedDigestTest() { + String name = "SM3"; + String oid = "1.2.156.10197.1.401"; + NUnit.Framework.Assert.AreEqual(FIPS_MODE ? null : oid, DigestAlgorithms.GetAllowedDigest(name)); + } } } diff --git a/itext.tests/itext.sign.tests/itext/signatures/DigestAlgorithmsTest.cs b/itext.tests/itext.sign.tests/itext/signatures/DigestAlgorithmsTest.cs index a3469d5444..2cbc069da1 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/DigestAlgorithmsTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/DigestAlgorithmsTest.cs @@ -23,7 +23,8 @@ You should have received a copy of the GNU Affero General Public License using System; using iText.Bouncycastleconnector; using iText.Commons.Bouncycastle; -using iText.Signatures.Logs; +using iText.Kernel.Crypto; +using iText.Kernel.Logs; using iText.Test; using iText.Test.Attributes; @@ -66,20 +67,12 @@ public virtual void NullNameGetAllowedDigestTest() { NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => DigestAlgorithms.GetAllowedDigest(null)); } - [LogMessage(SignLogMessageConstant.ALGORITHM_NOT_FROM_SPEC, Ignore = true)] + [LogMessage(KernelLogMessageConstant.ALGORITHM_NOT_FROM_SPEC, Ignore = true)] [NUnit.Framework.Test] public virtual void NotAllowedOidGetDigestTest() { String name = "SM3"; String oid = "1.2.156.10197.1.401"; NUnit.Framework.Assert.AreEqual(FIPS_MODE ? oid : name, DigestAlgorithms.GetDigest(oid)); } - - [LogMessage(SignLogMessageConstant.ALGORITHM_NOT_FROM_SPEC, Ignore = true)] - [NUnit.Framework.Test] - public virtual void NotAllowedNameGetAllowedDigestTest() { - String name = "SM3"; - String oid = "1.2.156.10197.1.401"; - NUnit.Framework.Assert.AreEqual(FIPS_MODE ? null : oid, DigestAlgorithms.GetAllowedDigest(name)); - } } } diff --git a/itext.tests/itext.sign.tests/itext/signatures/OcspClientBouncyCastleTest.cs b/itext.tests/itext.sign.tests/itext/signatures/OcspClientBouncyCastleTest.cs index 8813dfec2d..77c0473a47 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/OcspClientBouncyCastleTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/OcspClientBouncyCastleTest.cs @@ -135,14 +135,6 @@ public virtual void GetBasicOcspRespNullTest() { NUnit.Framework.Assert.IsNull(basicOCSPResp); } - [NUnit.Framework.Test] - [LogMessage("OCSP response could not be verified")] - public virtual void GetBasicOCSPRespLogMessageTest() { - OcspClientBouncyCastle ocspClientBouncyCastle = CreateOcspClient(); - IBasicOcspResponse basicOCSPResp = ocspClientBouncyCastle.GetBasicOCSPResp(null, null, null); - NUnit.Framework.Assert.IsNull(basicOCSPResp); - } - [NUnit.Framework.Test] public virtual void GetEncodedTest() { OcspClientBouncyCastle ocspClientBouncyCastle = CreateOcspClient(); @@ -185,8 +177,7 @@ private static OcspClientBouncyCastle CreateOcspClient() { } private static OcspClientBouncyCastle CreateOcspClient(TestOcspResponseBuilder builder) { - OCSPVerifier ocspVerifier = new OCSPVerifier(null, null); - return new OcspClientBouncyCastleTest.TestOcspClientBouncyCastle(ocspVerifier, builder); + return new OcspClientBouncyCastleTest.TestOcspClientBouncyCastle(builder); } private static OcspClientBouncyCastle CreateTestOcspClient(TestOcspResponseBuilder responseBuilder) { @@ -202,8 +193,8 @@ private static TestOcspResponseBuilder CreateBuilder(ICertStatus status) { private sealed class TestOcspClientBouncyCastle : OcspClientBouncyCastle { private static TestOcspResponseBuilder testOcspBuilder; - public TestOcspClientBouncyCastle(OCSPVerifier verifier, TestOcspResponseBuilder testBuilder) - : base(verifier) { + public TestOcspClientBouncyCastle(TestOcspResponseBuilder testBuilder) + : base() { testOcspBuilder = testBuilder; } diff --git a/itext.tests/itext.sign.tests/itext/signatures/PKCS7ExternalSignatureContainerTest.cs b/itext.tests/itext.sign.tests/itext/signatures/PKCS7ExternalSignatureContainerTest.cs index 19967ce5ce..c7872e3b73 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/PKCS7ExternalSignatureContainerTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/PKCS7ExternalSignatureContainerTest.cs @@ -28,6 +28,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Utils; using iText.IO.Source; +using iText.Kernel.Crypto; using iText.Kernel.Pdf; using iText.Signatures.Testutils; using iText.Signatures.Testutils.Builder; diff --git a/itext.tests/itext.sign.tests/itext/signatures/PdfPKCS7ManuallyPortedTest.cs b/itext.tests/itext.sign.tests/itext/signatures/PdfPKCS7ManuallyPortedTest.cs index fd1577733c..b8622c4837 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/PdfPKCS7ManuallyPortedTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/PdfPKCS7ManuallyPortedTest.cs @@ -74,13 +74,19 @@ public virtual void VerifyRsaSha3SignatureTest() { } [NUnit.Framework.Test] - public virtual void VerifyRsaPssSha3SignatureTest() - { - if ("BC".Equals(BOUNCY_CASTLE_FACTORY.GetProviderName())) { - VerifyIsoExtensionExample("RSASSA-PSS", "sample-pss-sha3_256.pdf"); - } else { - // Signer "RSASSA-PSS not recognised in BCFIPS mode - NUnit.Framework.Assert.Catch(typeof(PdfException), () => VerifyIsoExtensionExample("RSASSA-PSS", "sample-pss-sha3_256.pdf")); + public virtual void VerifyRsaPssSha3SignatureTest() { + VerifyIsoExtensionExample("RSASSA-PSS", "sample-pss-sha3_256.pdf"); + } + + [NUnit.Framework.Test] + public virtual void VerifyEd448SignatureTest() { + // SHAKE256 is not available in BCFIPS + if ("BCFIPS".Equals(BOUNCY_CASTLE_FACTORY.GetProviderName())) { + NUnit.Framework.Assert.Catch(typeof(PdfException), () => VerifyIsoExtensionExample("Ed448", "sample-ed448-shake256.pdf" + )); + } + else { + VerifyIsoExtensionExample("Ed448", "sample-ed448-shake256.pdf"); } } } diff --git a/itext.tests/itext.sign.tests/itext/signatures/PdfPKCS7Test.cs b/itext.tests/itext.sign.tests/itext/signatures/PdfPKCS7Test.cs index b30fb0e974..650f0a67cd 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/PdfPKCS7Test.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/PdfPKCS7Test.cs @@ -28,6 +28,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Asn1.Tsp; using iText.Commons.Bouncycastle.Cert; using iText.Commons.Utils; +using iText.Kernel.Crypto; using iText.Kernel.Exceptions; using iText.Kernel.Pdf; using iText.Signatures.Exceptions; @@ -72,7 +73,7 @@ public virtual void SimpleCreationWithPrivateKeyTest() { NUnit.Framework.Assert.AreEqual(expectedOid, pkcs7.GetDigestAlgorithmOid()); NUnit.Framework.Assert.AreEqual(chain[0], pkcs7.GetSigningCertificate()); NUnit.Framework.Assert.AreEqual(chain, pkcs7.GetCertificates()); - NUnit.Framework.Assert.AreEqual(SecurityIDs.ID_RSA_WITH_SHA256, pkcs7.GetSignatureMechanismOid()); + NUnit.Framework.Assert.AreEqual(OID.RSA_WITH_SHA256, pkcs7.GetSignatureMechanismOid()); } [NUnit.Framework.Test] @@ -286,18 +287,6 @@ public virtual void GetEncodedPkcs7WithRevocationInfoTest() { NUnit.Framework.Assert.AreEqual(SerializedAsString(bytes), SerializedAsString(cmpBytes)); } - [NUnit.Framework.Test] - public virtual void VerifyEd448SignatureTest() { - // SHAKE256 is not available in BCFIPS - if ("BCFIPS".Equals(BOUNCY_CASTLE_FACTORY.GetProviderName())) { - NUnit.Framework.Assert.Catch(typeof(PdfException), () => VerifyIsoExtensionExample("Ed448", "sample-ed448-shake256.pdf" - )); - } - else { - VerifyIsoExtensionExample("Ed448", "sample-ed448-shake256.pdf"); - } - } - [NUnit.Framework.Test] public virtual void VerifyNistECDSASha2SignatureTest() { VerifyIsoExtensionExample("SHA256withECDSA", "sample-nistp256-sha256.pdf"); diff --git a/itext.tests/itext.sign.tests/itext/signatures/PdfSignatureAppearanceUnitTest.cs b/itext.tests/itext.sign.tests/itext/signatures/PdfSignatureAppearanceUnitTest.cs deleted file mode 100644 index d7052e1e06..0000000000 --- a/itext.tests/itext.sign.tests/itext/signatures/PdfSignatureAppearanceUnitTest.cs +++ /dev/null @@ -1,279 +0,0 @@ -/* -This file is part of the iText (R) project. -Copyright (c) 1998-2024 Apryse Group NV -Authors: Apryse Software. - -This program is offered under a commercial and under the AGPL license. -For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. - -AGPL licensing: -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . -*/ -using System; -using System.IO; -using iText.Commons.Bouncycastle.Cert; -using iText.Commons.Utils; -using iText.Forms.Form; -using iText.Forms.Form.Element; -using iText.IO.Font.Constants; -using iText.IO.Image; -using iText.Kernel.Colors; -using iText.Kernel.Font; -using iText.Kernel.Geom; -using iText.Kernel.Pdf; -using iText.Kernel.Pdf.Xobject; -using iText.Kernel.Utils; -using iText.Layout; -using iText.Layout.Borders; -using iText.Layout.Font; -using iText.Layout.Properties; -using iText.Signatures.Testutils; -using iText.Test; - -namespace iText.Signatures { - /// - /// The idea of this test is to check the - /// - /// 's getters. - /// - /// - /// The idea of this test is to check the - /// - /// 's getters. - /// For actual result of setters invocations one should check the integration test for this class. - /// - [NUnit.Framework.Category("BouncyCastleUnitTest")] - public class PdfSignatureAppearanceUnitTest : ExtendedITextTest { - // The source folder points to the integration test, so that the resources are nor duplicated - public static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext - .CurrentContext.TestDirectory) + "/resources/itext/signatures/sign/PdfSignatureAppearanceTest/"; - - public static readonly String DESTINATION_FOLDER = NUnit.Framework.TestContext.CurrentContext.TestDirectory - + "/test/itext/signatures/sign/PdfSignatureAppearanceUnitTest/"; - - public static readonly String KEYSTORE_PATH = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext - .CurrentContext.TestDirectory) + "/resources/itext/signatures/sign/PdfSignatureAppearanceTest/test.pem"; - - public static readonly char[] PASSWORD = "kspass".ToCharArray(); - - private static IX509Certificate[] chain; - - [NUnit.Framework.OneTimeSetUp] - public static void Before() { - CreateOrClearDestinationFolder(DESTINATION_FOLDER); - chain = PemFileHelper.ReadFirstChain(KEYSTORE_PATH); - } - - [NUnit.Framework.Test] - public virtual void ReasonCaptionTest() { - PdfSignatureAppearance signatureAppearance = GetTestSignatureAppearance(); - String newReasonCaption = "Hello World"; - NUnit.Framework.Assert.IsNull(signatureAppearance.GetLayer2Text()); - String layer2Text = signatureAppearance.GenerateSignatureText().GenerateDescriptionText(); - // There is no text from new reason caption in the default layer 2 text - NUnit.Framework.Assert.IsFalse(layer2Text.Contains(newReasonCaption)); - signatureAppearance.SetReasonCaption(newReasonCaption); - layer2Text = signatureAppearance.GenerateSignatureText().GenerateDescriptionText(); - // Now layer 2 text contains text from new reason caption - NUnit.Framework.Assert.IsTrue(layer2Text.Contains(newReasonCaption)); - } - - [NUnit.Framework.Test] - public virtual void LocationCaptionTest() { - PdfSignatureAppearance signatureAppearance = GetTestSignatureAppearance(); - String newLocationCaption = "Hello World"; - NUnit.Framework.Assert.IsNull(signatureAppearance.GetLayer2Text()); - String layer2Text = signatureAppearance.GenerateSignatureText().GenerateDescriptionText(); - // There is no text from new location caption in the default layer 2 text - NUnit.Framework.Assert.IsFalse(layer2Text.Contains(newLocationCaption)); - signatureAppearance.SetLocationCaption(newLocationCaption); - layer2Text = signatureAppearance.GenerateSignatureText().GenerateDescriptionText(); - // Now layer 2 text contains text from new location caption - NUnit.Framework.Assert.IsTrue(layer2Text.Contains(newLocationCaption)); - } - - [NUnit.Framework.Test] - public virtual void RenderingModeSetGetTest() { - PdfSignatureAppearance signatureAppearance = GetTestSignatureAppearance(); - PdfSignatureAppearance.RenderingMode defaultMode = signatureAppearance.GetRenderingMode(); - NUnit.Framework.Assert.AreEqual(PdfSignatureAppearance.RenderingMode.DESCRIPTION, defaultMode); - PdfSignatureAppearance.RenderingMode testRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION; - signatureAppearance.SetRenderingMode(testRenderingMode); - NUnit.Framework.Assert.AreEqual(testRenderingMode, signatureAppearance.GetRenderingMode()); - } - - [NUnit.Framework.Test] - public virtual void SignatureCreatorSetGetTest() { - PdfSignatureAppearance signatureAppearance = GetTestSignatureAppearance(); - NUnit.Framework.Assert.AreEqual("", signatureAppearance.GetSignatureCreator()); - String signatureCreator = "Hello World"; - signatureAppearance.SetSignatureCreator(signatureCreator); - NUnit.Framework.Assert.AreEqual(signatureCreator, signatureAppearance.GetSignatureCreator()); - } - - [NUnit.Framework.Test] - public virtual void ContactSetGetTest() { - PdfSignatureAppearance signatureAppearance = GetTestSignatureAppearance(); - NUnit.Framework.Assert.AreEqual("", signatureAppearance.GetContact()); - String contact = "Hello World"; - signatureAppearance.SetContact(contact); - NUnit.Framework.Assert.AreEqual(contact, signatureAppearance.GetContact()); - } - - [NUnit.Framework.Test] - public virtual void CertificateSetGetTest() { - PdfSignatureAppearance signatureAppearance = GetTestSignatureAppearance(); - NUnit.Framework.Assert.IsNull(signatureAppearance.GetCertificate()); - IX509Certificate testCertificate = chain[0]; - signatureAppearance.SetCertificate(testCertificate); - NUnit.Framework.Assert.AreEqual(testCertificate, signatureAppearance.GetCertificate()); - } - - [NUnit.Framework.Test] - public virtual void SignatureGraphicSetGetTest() { - PdfSignatureAppearance signatureAppearance = GetTestSignatureAppearance(); - NUnit.Framework.Assert.IsNull(signatureAppearance.GetSignatureGraphic()); - ImageData testImageData = ImageDataFactory.Create(SOURCE_FOLDER + "itext.png"); - signatureAppearance.SetSignatureGraphic(testImageData); - NUnit.Framework.Assert.AreEqual(testImageData, signatureAppearance.GetSignatureGraphic()); - } - - [NUnit.Framework.Test] - public virtual void ImageSetGetTest() { - PdfSignatureAppearance signatureAppearance = GetTestSignatureAppearance(); - NUnit.Framework.Assert.IsNull(signatureAppearance.GetImage()); - ImageData testImageData = ImageDataFactory.Create(SOURCE_FOLDER + "itext.png"); - signatureAppearance.SetImage(testImageData); - NUnit.Framework.Assert.AreEqual(testImageData, signatureAppearance.GetImage()); - } - - [NUnit.Framework.Test] - public virtual void ImageScalingSetGetTest() { - PdfSignatureAppearance signatureAppearance = GetTestSignatureAppearance(); - NUnit.Framework.Assert.AreEqual(0, signatureAppearance.GetImageScale(), 0.0001); - float newScale = 1F; - signatureAppearance.SetImageScale(newScale); - NUnit.Framework.Assert.AreEqual(newScale, signatureAppearance.GetImageScale(), 0.0001); - } - - [NUnit.Framework.Test] - public virtual void Layer2FontSetGetTest() { - PdfSignatureAppearance signatureAppearance = GetTestSignatureAppearance(); - NUnit.Framework.Assert.IsNull(signatureAppearance.GetLayer2Font()); - PdfFont newFont = PdfFontFactory.CreateFont(); - signatureAppearance.SetLayer2Font(newFont); - NUnit.Framework.Assert.AreEqual(newFont, signatureAppearance.GetLayer2Font()); - } - - [NUnit.Framework.Test] - public virtual void SetFontProviderAndFamilyTest() { - PdfSignatureAppearance appearance = GetTestSignatureAppearance(); - FontProvider fontProvider = new FontProvider(); - fontProvider.GetFontSet().AddFont(StandardFonts.HELVETICA, ""); - String fontFamilyName = "fontFamily"; - appearance.SetFontProvider(fontProvider).SetFontFamily(fontFamilyName); - NUnit.Framework.Assert.AreEqual(fontProvider, appearance.GetSignatureAppearance().GetProperty(Property.FONT_PROVIDER)); - NUnit.Framework.Assert.AreEqual(fontFamilyName, ((String[])appearance.GetSignatureAppearance().GetProperty - (Property.FONT))[0]); - } - - [NUnit.Framework.Test] - public virtual void Layer2FontSizeSetGetTest() { - PdfSignatureAppearance signatureAppearance = GetTestSignatureAppearance(); - NUnit.Framework.Assert.AreEqual(0, signatureAppearance.GetLayer2FontSize(), 0.0001); - float newSize = 12F; - signatureAppearance.SetLayer2FontSize(newSize); - NUnit.Framework.Assert.AreEqual(newSize, signatureAppearance.GetLayer2FontSize(), 0.0001); - } - - [NUnit.Framework.Test] - public virtual void Layer2FontColorSetGetTest() { - PdfSignatureAppearance signatureAppearance = GetTestSignatureAppearance(); - NUnit.Framework.Assert.IsNull(signatureAppearance.GetLayer2FontColor()); - Color newColor = ColorConstants.RED; - signatureAppearance.SetLayer2FontColor(newColor); - NUnit.Framework.Assert.AreEqual(newColor, signatureAppearance.GetLayer2FontColor()); - } - - [NUnit.Framework.Test] - public virtual void GetAppearanceInvisibleTest() { - PdfSignatureAppearance appearance = new PdfSignatureAppearance(new PdfDocument(new PdfWriter(new MemoryStream - ())), new Rectangle(0, 100), 1); - PdfFormXObject xObject = appearance.GetAppearance(); - NUnit.Framework.Assert.IsTrue(new Rectangle(0, 0).EqualsWithEpsilon(xObject.GetBBox().ToRectangle())); - } - - [NUnit.Framework.Test] - public virtual void GetSignDateTest() { - PdfSignatureAppearance appearance = new PdfSignatureAppearance(null, new Rectangle(100, 100), 1); - DateTime current = DateTimeUtil.GetCurrentTime(); - appearance.SetSignDate(current); - NUnit.Framework.Assert.AreEqual(current, appearance.GetSignDate()); - } - - [NUnit.Framework.Test] - public virtual void WrongRenderingModeTest() { - using (Document ignored = new Document(new PdfDocument(new PdfWriter(new MemoryStream())))) { - PdfSignatureAppearance appearance = new PdfSignatureAppearance(null, new Rectangle(100, 100), 1); - appearance.SetRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION); - NUnit.Framework.Assert.Catch(typeof(InvalidOperationException), () => appearance.GetSignatureAppearance()); - PdfSignatureAppearance appearance2 = new PdfSignatureAppearance(null, new Rectangle(100, 100), 1); - appearance2.SetRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC); - NUnit.Framework.Assert.Catch(typeof(InvalidOperationException), () => appearance2.GetSignatureAppearance() - ); - } - } - - [NUnit.Framework.Test] - public virtual void BackgroundImageTest() { - String outPdf = DESTINATION_FOLDER + "signatureFieldBackground.pdf"; - String cmpPdf = SOURCE_FOLDER + "cmp_signatureFieldBackground.pdf"; - PdfSignatureAppearance appearance = new PdfSignatureAppearance(null, new Rectangle(100, 100), 1); - using (Document document = new Document(new PdfDocument(new PdfWriter(outPdf)))) { - SignatureFieldAppearance field1 = new SignatureFieldAppearance("field1"); - field1.SetProperty(FormProperty.FORM_FIELD_FLATTEN, true); - field1.SetContent("scale -1").SetFontColor(ColorConstants.GREEN).SetFontSize(50).SetBorder(new SolidBorder - (ColorConstants.RED, 10)).SetHeight(200).SetWidth(300).SetProperty(Property.TEXT_ALIGNMENT, TextAlignment - .CENTER); - appearance.SetSignatureAppearance(field1).SetImage(ImageDataFactory.Create(SOURCE_FOLDER + "1.png")).SetImageScale - (-1).ApplyBackgroundImage(); - document.Add(field1); - SignatureFieldAppearance field2 = new SignatureFieldAppearance("field2"); - field2.SetProperty(FormProperty.FORM_FIELD_FLATTEN, true); - field2.SetContent("scale 0").SetFontColor(ColorConstants.GREEN).SetFontSize(50).SetBorder(new SolidBorder( - ColorConstants.YELLOW, 10)).SetHeight(200).SetWidth(300).SetProperty(Property.TEXT_ALIGNMENT, TextAlignment - .CENTER); - appearance.SetSignatureAppearance(field2).SetImage(ImageDataFactory.Create(SOURCE_FOLDER + "1.png")).SetImageScale - (0).ApplyBackgroundImage(); - document.Add(field2); - SignatureFieldAppearance field3 = new SignatureFieldAppearance("field3"); - field3.SetProperty(FormProperty.FORM_FIELD_FLATTEN, true); - field3.SetContent("scale 0.5").SetFontColor(ColorConstants.GREEN).SetFontSize(50).SetBorder(new SolidBorder - (ColorConstants.GREEN, 10)).SetHeight(200).SetWidth(300).SetProperty(Property.TEXT_ALIGNMENT, TextAlignment - .CENTER); - appearance.SetSignatureAppearance(field3).SetImage(ImageDataFactory.Create(SOURCE_FOLDER + "1.png")).SetImageScale - (0.5f).ApplyBackgroundImage(); - document.Add(field3); - } - NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, DESTINATION_FOLDER)); - } - - private static PdfSignatureAppearance GetTestSignatureAppearance() { - String src = SOURCE_FOLDER + "simpleDocument.pdf"; - PdfSigner signer = new PdfSigner(new PdfReader(src), new MemoryStream(), new StampingProperties()); - return signer.GetSignatureAppearance(); - } - } -} diff --git a/itext.tests/itext.sign.tests/itext/signatures/PdfSignerUnitTest.cs b/itext.tests/itext.sign.tests/itext/signatures/PdfSignerUnitTest.cs index 6cbce7ed02..53dc4b25b0 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/PdfSignerUnitTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/PdfSignerUnitTest.cs @@ -27,7 +27,9 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Utils; using iText.Forms; using iText.Forms.Fields; +using iText.Forms.Form.Element; using iText.IO.Source; +using iText.Kernel.Crypto; using iText.Kernel.Exceptions; using iText.Kernel.Geom; using iText.Kernel.Logs; @@ -80,10 +82,11 @@ public virtual void CreateNewSignatureFormFieldInvisibleAnnotationTest() { ()), new ReaderProperties().SetPassword(OWNER)), new ByteArrayOutputStream(), new StampingProperties() ); signer.cryptoDictionary = new PdfSignature(); - signer.SetPageRect(new Rectangle(100, 100, 0, 0)); + SignerProperties signerProperties = new SignerProperties().SetPageRect(new Rectangle(100, 100, 0, 0)); + signer.SetSignerProperties(signerProperties); PdfAcroForm acroForm = PdfFormCreator.GetAcroForm(signer.document, true); - signer.CreateNewSignatureFormField(acroForm, signer.fieldName); - PdfFormField formField = acroForm.GetField(signer.fieldName); + signer.CreateNewSignatureFormField(acroForm, signerProperties.GetFieldName()); + PdfFormField formField = acroForm.GetField(signerProperties.GetFieldName()); PdfDictionary formFieldDictionary = formField.GetPdfObject(); NUnit.Framework.Assert.IsNotNull(formFieldDictionary); NUnit.Framework.Assert.IsTrue(formFieldDictionary.ContainsKey(PdfName.AP)); @@ -99,12 +102,14 @@ public virtual void CreateNewSignatureFormFieldNotInvisibleAnnotationTest() { ()), new ReaderProperties().SetPassword(OWNER)), new ByteArrayOutputStream(), new StampingProperties() ); signer.cryptoDictionary = new PdfSignature(); - signer.SetPageRect(new Rectangle(100, 100, 10, 10)); PdfSigFieldLock fieldLock = new PdfSigFieldLock(); - signer.fieldLock = fieldLock; + SignerProperties signerProperties = new SignerProperties().SetPageRect(new Rectangle(100, 100, 10, 10)).SetFieldLockDict + (fieldLock); + signer.SetSignerProperties(signerProperties); PdfAcroForm acroForm = PdfFormCreator.GetAcroForm(signer.document, true); - NUnit.Framework.Assert.AreEqual(fieldLock, signer.CreateNewSignatureFormField(acroForm, signer.fieldName)); - PdfFormField formField = acroForm.GetField(signer.fieldName); + NUnit.Framework.Assert.AreEqual(fieldLock, signer.CreateNewSignatureFormField(acroForm, signerProperties.GetFieldName + ())); + PdfFormField formField = acroForm.GetField(signerProperties.GetFieldName()); PdfDictionary formFieldDictionary = formField.GetPdfObject(); NUnit.Framework.Assert.IsNotNull(formFieldDictionary); NUnit.Framework.Assert.IsTrue(formFieldDictionary.ContainsKey(PdfName.AP)); @@ -115,8 +120,9 @@ public virtual void SignWithFieldLockNotNullTest() { PdfSigner signer = new PdfSigner(new PdfReader(new MemoryStream(CreateSimpleDocument(PdfVersion.PDF_2_0))) , new ByteArrayOutputStream(), new StampingProperties()); signer.cryptoDictionary = new PdfSignature(); - signer.SetPageRect(new Rectangle(100, 100, 10, 10)); - signer.fieldLock = new PdfSigFieldLock(); + SignerProperties signerProperties = new SignerProperties().SetPageRect(new Rectangle(100, 100, 10, 10)).SetFieldLockDict + (new PdfSigFieldLock()); + signer.SetSignerProperties(signerProperties); IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES ); @@ -162,15 +168,16 @@ public virtual void PopulateExistingSignatureFormFieldInvisibleAnnotationTest() PdfSigner signer = new PdfSigner(new PdfReader(new MemoryStream(outputStream.ToArray()), new ReaderProperties ().SetPassword(OWNER)), new ByteArrayOutputStream(), new StampingProperties()); signer.cryptoDictionary = new PdfSignature(); - signer.SetPageRect(new Rectangle(100, 100, 0, 0)); + SignerProperties signerProperties = new SignerProperties().SetPageRect(new Rectangle(100, 100, 0, 0)); + signer.SetSignerProperties(signerProperties); widgetAnnotation = (PdfWidgetAnnotation)signer.document.GetPage(1).GetAnnotations()[0]; PdfAcroForm acroForm = PdfFormCreator.GetAcroForm(signer.document, true); PdfFormField formField = new PdfSignerUnitTest.ExtendedPdfSignatureFormField(widgetAnnotation, signer.document ); - formField.SetFieldName(signer.fieldName); + formField.SetFieldName(signerProperties.GetFieldName()); acroForm.AddField(formField); signer.PopulateExistingSignatureFormField(acroForm); - formField = acroForm.GetField(signer.fieldName); + formField = acroForm.GetField(signerProperties.GetFieldName()); PdfDictionary formFieldDictionary = formField.GetPdfObject(); NUnit.Framework.Assert.IsNotNull(formFieldDictionary); NUnit.Framework.Assert.IsTrue(formFieldDictionary.ContainsKey(PdfName.AP)); @@ -193,21 +200,51 @@ public virtual void PopulateExistingSignatureFormFieldNotInvisibleAnnotationTest ().SetPassword(OWNER)), new ByteArrayOutputStream(), new StampingProperties()); signer.cryptoDictionary = new PdfSignature(); PdfSigFieldLock fieldLock = new PdfSigFieldLock(); - signer.fieldLock = fieldLock; - signer.SetPageRect(new Rectangle(100, 100, 10, 10)); + SignerProperties signerProperties = new SignerProperties().SetPageRect(new Rectangle(100, 100, 10, 10)).SetFieldLockDict + (fieldLock); + signer.SetSignerProperties(signerProperties); widgetAnnotation = (PdfWidgetAnnotation)signer.document.GetPage(1).GetAnnotations()[0]; PdfAcroForm acroForm = PdfFormCreator.GetAcroForm(signer.document, true); PdfFormField formField = new PdfSignerUnitTest.ExtendedPdfSignatureFormField(widgetAnnotation, signer.document ); - formField.SetFieldName(signer.fieldName); + formField.SetFieldName(signerProperties.GetFieldName()); acroForm.AddField(formField); NUnit.Framework.Assert.AreEqual(signer.PopulateExistingSignatureFormField(acroForm), fieldLock); - formField = acroForm.GetField(signer.fieldName); + formField = acroForm.GetField(signerProperties.GetFieldName()); PdfDictionary formFieldDictionary = formField.GetPdfObject(); NUnit.Framework.Assert.IsNotNull(formFieldDictionary); NUnit.Framework.Assert.IsTrue(formFieldDictionary.ContainsKey(PdfName.AP)); } + [NUnit.Framework.Test] + public virtual void SetAlternativeName() { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + PdfDocument document = new PdfDocument(new PdfWriter(outputStream, new WriterProperties())); + document.SetTagged(); + document.AddNewPage(); + document.Close(); + ByteArrayOutputStream signedOutputStream = new ByteArrayOutputStream(); + PdfSigner signer = new PdfSigner(new PdfReader(new MemoryStream(outputStream.ToArray())), signedOutputStream + , new StampingProperties()); + SignerProperties signerProperties = new SignerProperties().SetFieldName("Signature1").SetPageNumber(1).SetPageRect + (new Rectangle(100, 100, 10, 10)); + signer.SetSignerProperties(signerProperties); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID); + appearance.SetContent("Some text"); + appearance.GetAccessibilityProperties().SetAlternateDescription("Alternate description"); + signerProperties.SetSignatureAppearance(appearance); + IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); + signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES + ); + signer.document.Close(); + PdfDocument signedDocument = new PdfDocument(new PdfReader(new MemoryStream(signedOutputStream.ToArray())) + , new PdfWriter(new ByteArrayOutputStream())); + PdfAcroForm acroForm = PdfFormCreator.GetAcroForm(signedDocument, true); + PdfFormField formField = acroForm.GetField(signerProperties.GetFieldName()); + NUnit.Framework.Assert.AreEqual("Alternate description", formField.GetPdfObject().Get(PdfName.TU).ToString + ()); + } + [NUnit.Framework.Test] public virtual void TempFileProvidedTest() { String tempFileName = "tempFile"; @@ -223,8 +260,8 @@ public virtual void TempFileProvidedTest() { public virtual void InitPdfaDocumentTest() { PdfSigner signer = new PdfSigner(new PdfReader(new MemoryStream(CreateSimplePdfaDocument())), new ByteArrayOutputStream (), new StampingProperties()); - NUnit.Framework.Assert.AreEqual(PdfAConformanceLevel.PDF_A_1A, ((PdfAAgnosticPdfDocument)signer.GetDocument - ()).GetConformanceLevel()); + NUnit.Framework.Assert.AreEqual(PdfAConformance.PDF_A_1A, signer.GetDocument().GetConformance().GetAConformance + ()); } [NUnit.Framework.Test] @@ -232,18 +269,20 @@ public virtual void SigningDateSetGetTest() { PdfSigner signer = new PdfSigner(new PdfReader(new MemoryStream(CreateSimplePdfaDocument())), new ByteArrayOutputStream (), new StampingProperties()); DateTime testDate = DateTimeUtil.GetCurrentTime(); - signer.SetSignDate(testDate); - NUnit.Framework.Assert.AreEqual(testDate, signer.GetSignDate()); + SignerProperties signerProperties = new SignerProperties().SetClaimedSignDate(testDate); + signer.SetSignerProperties(signerProperties); + NUnit.Framework.Assert.AreEqual(testDate, signerProperties.GetClaimedSignDate()); } [NUnit.Framework.Test] public virtual void CertificationLevelSetGetTest() { PdfSigner signer = new PdfSigner(new PdfReader(new MemoryStream(CreateSimplePdfaDocument())), new ByteArrayOutputStream (), new StampingProperties()); - NUnit.Framework.Assert.AreEqual(PdfSigner.NOT_CERTIFIED, signer.GetCertificationLevel()); - int testLevel = PdfSigner.CERTIFIED_NO_CHANGES_ALLOWED; - signer.SetCertificationLevel(testLevel); - NUnit.Framework.Assert.AreEqual(testLevel, signer.GetCertificationLevel()); + NUnit.Framework.Assert.AreEqual(AccessPermissions.UNSPECIFIED, signer.GetSignerProperties().GetCertificationLevel + ()); + AccessPermissions testLevel = AccessPermissions.NO_CHANGES_PERMITTED; + signer.GetSignerProperties().SetCertificationLevel(testLevel); + NUnit.Framework.Assert.AreEqual(testLevel, signer.GetSignerProperties().GetCertificationLevel()); } [NUnit.Framework.Test] @@ -270,8 +309,25 @@ public virtual void SignatureEventSetGetTest() { public virtual void SignatureFieldNameMustNotContainDotTest() { PdfSigner signer = new PdfSigner(new PdfReader(new MemoryStream(CreateSimplePdfaDocument())), new ByteArrayOutputStream (), new StampingProperties()); - Exception exception = NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => signer.SetFieldName("name.with.dots" - )); + SignerProperties signerProperties = new SignerProperties().SetFieldName("name.with.dots"); + Exception exception = NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => signer.SetSignerProperties + (signerProperties)); + NUnit.Framework.Assert.AreEqual(SignExceptionMessageConstant.FIELD_NAMES_CANNOT_CONTAIN_A_DOT, exception.Message + ); + } + + [NUnit.Framework.Test] + public virtual void ChangeSignatureFieldNameToInvalidTest() { + PdfSigner signer = new PdfSigner(new PdfReader(new MemoryStream(CreateSimplePdfaDocument())), new ByteArrayOutputStream + (), new StampingProperties()); + SignerProperties signerProperties = new SignerProperties(); + signer.SetSignerProperties(signerProperties); + NUnit.Framework.Assert.AreEqual("Signature1", signer.GetSignerProperties().GetFieldName()); + signerProperties.SetFieldName("name.with.dots"); + NUnit.Framework.Assert.AreEqual("name.with.dots", signer.GetSignerProperties().GetFieldName()); + IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); + Exception exception = NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => signer.SignDetached(new + BouncyCastleDigest(), pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES)); NUnit.Framework.Assert.AreEqual(SignExceptionMessageConstant.FIELD_NAMES_CANNOT_CONTAIN_A_DOT, exception.Message ); } @@ -314,10 +370,10 @@ public virtual void FieldLockSetGetTest() { PdfReader reader = new PdfReader(new MemoryStream(CreateSimplePdfaDocument())); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PdfSigner signer = new PdfSigner(reader, outputStream, new StampingProperties()); - NUnit.Framework.Assert.IsNull(signer.GetFieldLockDict()); + NUnit.Framework.Assert.IsNull(signer.GetSignerProperties().GetFieldLockDict()); PdfSigFieldLock fieldLock = new PdfSigFieldLock(); - signer.SetFieldLockDict(fieldLock); - NUnit.Framework.Assert.AreEqual(fieldLock, signer.GetFieldLockDict()); + signer.GetSignerProperties().SetFieldLockDict(fieldLock); + NUnit.Framework.Assert.AreEqual(fieldLock, signer.GetSignerProperties().GetFieldLockDict()); } // Android-Conversion-Skip-Block-End @@ -326,8 +382,9 @@ public virtual void SetFieldNameNullForDefaultSignerTest() { PdfReader reader = new PdfReader(new MemoryStream(CreateSimpleDocument())); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PdfSigner signer = new PdfSigner(reader, outputStream, new StampingProperties()); - signer.SetFieldName(null); - NUnit.Framework.Assert.AreEqual("Signature1", signer.GetFieldName()); + SignerProperties signerProperties = new SignerProperties().SetFieldName(null); + signer.SetSignerProperties(signerProperties); + NUnit.Framework.Assert.AreEqual("Signature1", signer.GetSignerProperties().GetFieldName()); } [NUnit.Framework.Test] @@ -336,16 +393,18 @@ public virtual void KeepFieldNameAfterSetToNullTest() { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PdfSigner signer = new PdfSigner(reader, outputStream, new StampingProperties()); String testName = "test_name"; - signer.SetFieldName(testName); - signer.SetFieldName(null); - NUnit.Framework.Assert.AreEqual(testName, signer.GetFieldName()); + SignerProperties signerProperties = new SignerProperties().SetFieldName(testName); + signer.SetSignerProperties(signerProperties); + signerProperties.SetFieldName(null); + NUnit.Framework.Assert.AreEqual(testName, signer.GetSignerProperties().GetFieldName()); } [NUnit.Framework.Test] public virtual void SetFieldNameToFieldWithSameNameAndNoSigTest() { PdfReader reader = new PdfReader(new MemoryStream(CreateDocumentWithEmptyField())); PdfSigner signer = new PdfSigner(reader, new ByteArrayOutputStream(), new StampingProperties()); - Exception e = NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => signer.SetFieldName("test_field" + SignerProperties signerProperties = new SignerProperties().SetFieldName("test_field"); + Exception e = NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => signer.SetSignerProperties(signerProperties )); NUnit.Framework.Assert.AreEqual(SignExceptionMessageConstant.FIELD_TYPE_IS_NOT_A_SIGNATURE_FIELD_TYPE, e.Message ); @@ -359,8 +418,9 @@ public virtual void SetFieldNameToSigFieldWithValueTest() { PdfReader reader = new PdfReader(new MemoryStream(CreateDocumentWithSignatureWithTestValueField(fieldName, fieldValue))); PdfSigner signer = new PdfSigner(reader, new ByteArrayOutputStream(), new StampingProperties()); - Exception e = NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => signer.SetFieldName(fieldName) - ); + SignerProperties signerProperties = new SignerProperties().SetFieldName(fieldName); + Exception e = NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => signer.SetSignerProperties(signerProperties + )); NUnit.Framework.Assert.AreEqual(SignExceptionMessageConstant.FIELD_ALREADY_SIGNED, e.Message); reader.Close(); } @@ -370,8 +430,9 @@ public virtual void SetFieldNameToSigFieldWithoutWidgetsTest() { String fieldName = "test_field"; PdfReader reader = new PdfReader(new MemoryStream(CreateDocumentWithSignatureField(fieldName))); PdfSigner signer = new PdfSigner(reader, new ByteArrayOutputStream(), new StampingProperties()); - signer.SetFieldName(fieldName); - NUnit.Framework.Assert.AreEqual(fieldName, signer.GetFieldName()); + SignerProperties signerProperties = new SignerProperties().SetFieldName(fieldName); + signer.SetSignerProperties(signerProperties); + NUnit.Framework.Assert.AreEqual(fieldName, signer.GetSignerProperties().GetFieldName()); reader.Close(); } @@ -439,7 +500,7 @@ private static byte[] CreateSimplePdfaDocument() { Stream @is = FileUtil.GetInputStreamForFile(PDFA_RESOURCES + "sRGB Color Space Profile.icm"); PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , @is); - PdfDocument document = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1A, outputIntent); + PdfDocument document = new PdfADocument(writer, PdfAConformance.PDF_A_1A, outputIntent); document.SetTagged(); document.GetCatalog().SetLang(new PdfString("en-US")); document.AddNewPage(); diff --git a/itext.tests/itext.sign.tests/itext/signatures/PdfTwoPhaseSignerUnitTest.cs b/itext.tests/itext.sign.tests/itext/signatures/PdfTwoPhaseSignerUnitTest.cs index c3c0d891c0..e203733b68 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/PdfTwoPhaseSignerUnitTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/PdfTwoPhaseSignerUnitTest.cs @@ -25,6 +25,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Bouncycastleconnector; using iText.Commons.Bouncycastle; using iText.IO.Source; +using iText.Kernel.Crypto; using iText.Kernel.Pdf; using iText.Test; diff --git a/itext.tests/itext.sign.tests/itext/signatures/PdfUASignerTest.cs b/itext.tests/itext.sign.tests/itext/signatures/PdfUASignerTest.cs new file mode 100644 index 0000000000..fc2dafda59 --- /dev/null +++ b/itext.tests/itext.sign.tests/itext/signatures/PdfUASignerTest.cs @@ -0,0 +1,328 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using System.IO; +using Microsoft.Extensions.Logging; +using iText.Bouncycastleconnector; +using iText.Commons; +using iText.Commons.Bouncycastle; +using iText.Commons.Bouncycastle.Cert; +using iText.Commons.Bouncycastle.Crypto; +using iText.Commons.Utils; +using iText.Forms.Fields.Properties; +using iText.Forms.Form.Element; +using iText.IO.Util; +using iText.Kernel.Crypto; +using iText.Kernel.Font; +using iText.Kernel.Geom; +using iText.Kernel.Pdf; +using iText.Pdfua; +using iText.Pdfua.Exceptions; +using iText.Signatures.Testutils; +using iText.Test; +using iText.Test.Pdfa; + +namespace iText.Signatures { + // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf\a validation on Android) + [NUnit.Framework.Category("IntegrationTest")] + public class PdfUASignerTest : ExtendedITextTest { + private static readonly IBouncyCastleFactory BOUNCY_CASTLE_FACTORY = BouncyCastleFactoryCreator.GetFactory + (); + + private static readonly String DESTINATION_FOLDER = NUnit.Framework.TestContext.CurrentContext.TestDirectory + + "/test/itext/signatures/PdfUASignerTest/"; + + private static readonly String FONT = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + .CurrentContext.TestDirectory) + "/resources/itext/signatures/font/FreeSans.ttf"; + + private static readonly ILogger logger = ITextLogManager.GetLogger(typeof(PdfUASignerTest)); + + public static readonly String CERTIFICATE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + .CurrentContext.TestDirectory) + "/resources/itext/signatures/certs/"; + + private static readonly char[] PASSWORD = "testpassphrase".ToCharArray(); + + [NUnit.Framework.OneTimeSetUp] + public static void BeforeClass() { + CreateOrClearDestinationFolder(DESTINATION_FOLDER); + } + + [NUnit.Framework.Test] + public virtual void InvisibleSignatureWithNoTU() { + MemoryStream inPdf = GenerateSimplePdfUA1Document(); + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfUAConformanceException), () => { + GenerateSignature(inPdf, "invisibleSignatureWithNoTU", (signer) => { + } + ); + } + ); + NUnit.Framework.Assert.AreEqual(PdfUAExceptionMessageConstants.MISSING_FORM_FIELD_DESCRIPTION, e.Message); + } + + [NUnit.Framework.Test] + public virtual void InvisibleSignatureWithTU() { + MemoryStream inPdf = GenerateSimplePdfUA1Document(); + String outPdf = GenerateSignature(inPdf, "invisibleSignatureWithTU", (signer) => { + signer.SetSignerProperties(new SignerProperties().SetFieldName("Signature12")); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID); + appearance.GetAccessibilityProperties().SetAlternateDescription("Some alternate description"); + signer.GetSignerProperties().SetSignatureAppearance(appearance); + } + ); + NUnit.Framework.Assert.IsNull(new VeraPdfValidator().Validate(outPdf)); + } + + // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf\a validation on Android) + [NUnit.Framework.Test] + public virtual void VisibleSignatureWithTUButNotAFont() { + MemoryStream inPdf = GenerateSimplePdfUA1Document(); + String outPdf = GenerateSignature(inPdf, "visibleSignatureWithTUButNotAFont", (signer) => { + signer.SetSignerProperties(new SignerProperties().SetFieldName("Signature12")); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID); + appearance.GetAccessibilityProperties().SetAlternateDescription("Some alternate description"); + try { + appearance.SetFont(PdfFontFactory.CreateFont(FONT)); + } + catch (System.IO.IOException) { + throw new Exception(); + } + appearance.SetContent("Some signature content"); + signer.GetSignerProperties().SetPageNumber(1).SetPageRect(new Rectangle(36, 648, 200, 100)).SetSignatureAppearance + (appearance); + } + ); + NUnit.Framework.Assert.IsNull(new VeraPdfValidator().Validate(outPdf)); + } + + // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf\a validation on Android) + [NUnit.Framework.Test] + public virtual void VisibleSignatureWithoutTUFont() { + MemoryStream inPdf = GenerateSimplePdfUA1Document(); + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfUAConformanceException), () => { + GenerateSignature(inPdf, "visibleSignatureWithoutTUFont", (signer) => { + signer.SetSignerProperties(new SignerProperties().SetFieldName("Signature12")); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID); + appearance.SetContent(new SignedAppearanceText().SetLocationLine("Dummy location").SetReasonLine("Dummy reason" + ).SetSignedBy("Dummy")); + try { + appearance.SetFont(PdfFontFactory.CreateFont(FONT)); + } + catch (System.IO.IOException) { + throw new Exception(); + } + signer.GetSignerProperties().SetPageNumber(1).SetPageRect(new Rectangle(36, 648, 200, 100)).SetSignatureAppearance + (appearance); + } + ); + } + ); + } + + [NUnit.Framework.Test] + public virtual void VisibleSignatureWithNoFontSelected() { + MemoryStream inPdf = GenerateSimplePdfUA1Document(); + Exception e = NUnit.Framework.Assert.Catch(typeof(PdfUAConformanceException), () => { + GenerateSignature(inPdf, "visibleSignatureWithNoFontSelected", (signer) => { + signer.SetSignerProperties(new SignerProperties().SetFieldName("Signature12")); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID); + appearance.SetContent("Some signature content"); + signer.GetSignerProperties().SetPageNumber(1).SetPageRect(new Rectangle(36, 648, 200, 100)); + appearance.GetAccessibilityProperties().SetAlternateDescription("Some alternate description"); + appearance.SetContent(new SignedAppearanceText().SetSignedBy("Dummy").SetReasonLine("Dummy reason").SetLocationLine + ("Dummy location")); + signer.GetSignerProperties().SetSignatureAppearance(appearance); + } + ); + } + ); + } + + [NUnit.Framework.Test] + public virtual void NormalPdfSignerInvisibleSignatureWithTU() { + MemoryStream inPdf = GenerateSimplePdfUA1Document(); + String outPdf = GenerateSignatureNormal(inPdf, "normalPdfSignerInvisibleSignatureWithTU", (signer) => { + signer.SetSignerProperties(new SignerProperties().SetFieldName("Signature12")); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID); + appearance.GetAccessibilityProperties().SetAlternateDescription("Some alternate description"); + signer.GetSignerProperties().SetSignatureAppearance(appearance); + } + ); + NUnit.Framework.Assert.IsNull(new VeraPdfValidator().Validate(outPdf)); + } + + // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf\a validation on Android) + [NUnit.Framework.Test] + public virtual void NormalPdfSignerInvisibleSignatureWithoutTU() { + MemoryStream inPdf = GenerateSimplePdfUA1Document(); + String outPdf = GenerateSignatureNormal(inPdf, "normalPdfSignerInvisibleSignatureWithoutTU", (signer) => { + signer.SetSignerProperties(new SignerProperties().SetFieldName("Signature12")); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID); + signer.GetSignerProperties().SetSignatureAppearance(appearance); + } + ); + NUnit.Framework.Assert.IsNull(new VeraPdfValidator().Validate(outPdf)); + } + + // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf\a validation on Android) + [NUnit.Framework.Test] + public virtual void NormalPdfSignerVisibleSignatureWithoutFont() { + // TODO DEVSIX-8676 Enable keeping A and UA conformance in PdfSigner + //This test should fail with the appropriate exception + MemoryStream inPdf = GenerateSimplePdfUA1Document(); + String outPdf = GenerateSignatureNormal(inPdf, "normalPdfSignerVisibleSignatureWithoutFont", (signer) => { + signer.SetSignerProperties(new SignerProperties().SetFieldName("Signature12")); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID); + appearance.GetAccessibilityProperties().SetAlternateDescription("Some alternate description"); + appearance.SetContent(new SignedAppearanceText().SetLocationLine("Dummy location").SetReasonLine("Dummy reason" + ).SetSignedBy("Dummy")); + signer.GetSignerProperties().SetPageNumber(1).SetPageRect(new Rectangle(36, 648, 200, 100)).SetSignatureAppearance + (appearance); + } + ); + NUnit.Framework.Assert.IsNotNull(new VeraPdfValidator().Validate(outPdf)); + } + + // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf\a validation on Android) + [NUnit.Framework.Test] + public virtual void NormalPdfSignerVisibleSignatureWithFont() { + MemoryStream inPdf = GenerateSimplePdfUA1Document(); + PdfFont font = PdfFontFactory.CreateFont(FONT); + String outPdf = GenerateSignatureNormal(inPdf, "normalPdfSignerVisibleSignatureWithFont", (signer) => { + signer.SetSignerProperties(new SignerProperties().SetFieldName("Signature12")); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID); + appearance.GetAccessibilityProperties().SetAlternateDescription("Some alternate description"); + appearance.SetContent(new SignedAppearanceText().SetLocationLine("Dummy location").SetReasonLine("Dummy reason" + ).SetSignedBy("Dummy")); + appearance.SetFont(font); + signer.GetSignerProperties().SetPageNumber(1).SetPageRect(new Rectangle(36, 648, 200, 100)).SetSignatureAppearance + (appearance); + } + ); + NUnit.Framework.Assert.IsNull(new VeraPdfValidator().Validate(outPdf)); + } + + // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf\a validation on Android) + [NUnit.Framework.Test] + public virtual void NormalPdfSignerVisibleSignatureWithFontEmptyTU() { + // TODO DEVSIX-8676 Enable keeping A and UA conformance in PdfSigner + //Should throw the correct exception if the font is not set + MemoryStream inPdf = GenerateSimplePdfUA1Document(); + PdfFont font = PdfFontFactory.CreateFont(FONT); + String outPdf = GenerateSignatureNormal(inPdf, "normalPdfSignerVisibleSignatureWithFontEmptyTU", (signer) => { + signer.SetSignerProperties(new SignerProperties().SetFieldName("Signature12")); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID); + appearance.GetAccessibilityProperties().SetAlternateDescription(""); + appearance.SetContent(new SignedAppearanceText().SetLocationLine("Dummy location").SetReasonLine("Dummy reason" + ).SetSignedBy("Dummy")); + appearance.SetFont(font); + signer.GetSignerProperties().SetPageNumber(1).SetPageRect(new Rectangle(36, 648, 200, 100)).SetSignatureAppearance + (appearance); + } + ); + NUnit.Framework.Assert.IsNotNull(new VeraPdfValidator().Validate(outPdf)); + } + + // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf\a validation on Android) + [NUnit.Framework.Test] + public virtual void PdfSignerVisibleSignatureWithFontEmptyTU() { + //Should throw the correct exception if the font is not set + MemoryStream inPdf = GenerateSimplePdfUA1Document(); + PdfFont font = PdfFontFactory.CreateFont(FONT); + NUnit.Framework.Assert.Catch(typeof(PdfUAConformanceException), () => { + GenerateSignature(inPdf, "pdfSignerVisibleSignatureWithFontEmptyTU", (signer) => { + signer.SetSignerProperties(new SignerProperties().SetFieldName("Signature12")); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID); + appearance.GetAccessibilityProperties().SetAlternateDescription(""); + appearance.SetContent(new SignedAppearanceText().SetLocationLine("Dummy location").SetReasonLine("Dummy reason" + ).SetSignedBy("Dummy")); + appearance.SetFont(font); + signer.GetSignerProperties().SetPageNumber(1).SetPageRect(new Rectangle(36, 648, 200, 100)).SetSignatureAppearance + (appearance); + } + ); + } + ); + } + + private MemoryStream GenerateSimplePdfUA1Document() { + MemoryStream @out = new MemoryStream(); + PdfUADocument pdfUADocument = new PdfUADocument(new PdfWriter(@out), new PdfUAConfig(PdfUAConformance.PDF_UA_1 + , "Title", "en-US")); + pdfUADocument.AddNewPage(); + pdfUADocument.Close(); + return new MemoryStream(@out.ToArray()); + } + + private String GenerateSignature(MemoryStream inPdf, String name, Action signingAction) { + String certFileName = CERTIFICATE_FOLDER + "sign.pem"; + IPrivateKey signPrivateKey = PemFileHelper.ReadFirstKey(certFileName, PASSWORD); + IExternalSignature pks = new PrivateKeySignature(signPrivateKey, DigestAlgorithms.SHA256); + IX509Certificate[] signChain = PemFileHelper.ReadFirstChain(certFileName); + String outPdf = DESTINATION_FOLDER + name + ".pdf"; + PdfSigner signer = new PdfUASignerTest.PdfUaSigner(new PdfReader(inPdf), FileUtil.GetFileOutputStream(outPdf + ), new StampingProperties()); + signingAction(signer); + signer.SignDetached(new BouncyCastleDigest(), pks, signChain, null, null, null, 0, PdfSigner.CryptoStandard + .CADES); + logger.LogInformation("Out pdf: " + UrlUtil.GetNormalizedFileUriString(outPdf)); + return outPdf; + } + + private String GenerateSignatureNormal(MemoryStream inPdf, String name, Action signingAction) { + String certFileName = CERTIFICATE_FOLDER + "sign.pem"; + IPrivateKey signPrivateKey = PemFileHelper.ReadFirstKey(certFileName, PASSWORD); + IExternalSignature pks = new PrivateKeySignature(signPrivateKey, DigestAlgorithms.SHA256); + IX509Certificate[] signChain = PemFileHelper.ReadFirstChain(certFileName); + String outPdf = DESTINATION_FOLDER + name + ".pdf"; + PdfSigner signer = new PdfSigner(new PdfReader(inPdf), FileUtil.GetFileOutputStream(outPdf), new StampingProperties + ()); + signingAction(signer); + signer.SignDetached(new BouncyCastleDigest(), pks, signChain, null, null, null, 0, PdfSigner.CryptoStandard + .CADES); + logger.LogInformation("Out pdf: " + UrlUtil.GetNormalizedFileUriString(outPdf)); + return outPdf; + } + +//\cond DO_NOT_DOCUMENT + internal class PdfUaSigner : PdfSigner { + public PdfUaSigner(PdfReader reader, Stream outputStream, StampingProperties properties) + : base(reader, outputStream, properties) { + } + + public PdfUaSigner(PdfReader reader, Stream outputStream, String path, StampingProperties stampingProperties + , SignerProperties signerProperties) + : base(reader, outputStream, path, stampingProperties, signerProperties) { + } + + public PdfUaSigner(PdfReader reader, Stream outputStream, String path, StampingProperties properties) + : base(reader, outputStream, path, properties) { + } + + protected internal override PdfDocument InitDocument(PdfReader reader, PdfWriter writer, StampingProperties + properties) { + return new PdfUADocument(reader, writer, new PdfUAConfig(PdfUAConformance.PDF_UA_1, "Title", "en-US")); + } + } +//\endcond + } +} diff --git a/itext.tests/itext.sign.tests/itext/signatures/SignMetaInfoHandlingTest.cs b/itext.tests/itext.sign.tests/itext/signatures/SignMetaInfoHandlingTest.cs index 94f2fc1388..9ce89f4708 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/SignMetaInfoHandlingTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/SignMetaInfoHandlingTest.cs @@ -32,6 +32,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Utils; using iText.IO.Source; using iText.Kernel.Actions.Events; +using iText.Kernel.Crypto; using iText.Kernel.Pdf; using iText.Signatures.Cms; using iText.Signatures.Testutils; diff --git a/itext.tests/itext.sign.tests/itext/signatures/SignaturePolicyInfoTest.cs b/itext.tests/itext.sign.tests/itext/signatures/SignaturePolicyInfoTest.cs index 3a586bb85b..13ff11d9b6 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/SignaturePolicyInfoTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/SignaturePolicyInfoTest.cs @@ -27,6 +27,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Asn1.Esf; using iText.Commons.Bouncycastle.Asn1.X509; using iText.Commons.Utils; +using iText.Kernel.Crypto; using iText.Test; namespace iText.Signatures { diff --git a/itext.tests/itext.sign.tests/itext/signatures/SignatureUtilTest.cs b/itext.tests/itext.sign.tests/itext/signatures/SignatureUtilTest.cs index 8c5d8aba1e..146128acb6 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/SignatureUtilTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/SignatureUtilTest.cs @@ -59,6 +59,30 @@ public virtual void GetSignaturesTest02() { NUnit.Framework.Assert.AreEqual(0, signatureNames.Count); } + [NUnit.Framework.Test] + public virtual void EolNotIncludedIntoByteRangeTest1() { + String inPdf = sourceFolder + "eolNotIncludedIntoByteRange1.pdf"; + PdfDocument pdfDocument = new PdfDocument(new PdfReader(inPdf)); + SignatureUtil signatureUtil = new SignatureUtil(pdfDocument); + NUnit.Framework.Assert.IsFalse(signatureUtil.SignatureCoversWholeDocument("Signature1")); + } + + [NUnit.Framework.Test] + public virtual void EolNotIncludedIntoByteRangeTest2() { + String inPdf = sourceFolder + "eolNotIncludedIntoByteRange2.pdf"; + PdfDocument pdfDocument = new PdfDocument(new PdfReader(inPdf)); + SignatureUtil signatureUtil = new SignatureUtil(pdfDocument); + NUnit.Framework.Assert.IsTrue(signatureUtil.SignatureCoversWholeDocument("Signature1")); + } + + [NUnit.Framework.Test] + public virtual void EolNotIncludedIntoByteRangeTest3() { + String inPdf = sourceFolder + "eolNotIncludedIntoByteRange3.pdf"; + PdfDocument pdfDocument = new PdfDocument(new PdfReader(inPdf)); + SignatureUtil signatureUtil = new SignatureUtil(pdfDocument); + NUnit.Framework.Assert.IsFalse(signatureUtil.SignatureCoversWholeDocument("Signature1")); + } + [NUnit.Framework.Test] public virtual void FirstBytesNotCoveredTest01() { String inPdf = sourceFolder + "firstBytesNotCoveredTest01.pdf"; diff --git a/itext.tests/itext.sign.tests/itext/signatures/TrustedCerrtificatesStoreTest.cs b/itext.tests/itext.sign.tests/itext/signatures/TrustedCerrtificatesStoreTest.cs new file mode 100644 index 0000000000..37a552d811 --- /dev/null +++ b/itext.tests/itext.sign.tests/itext/signatures/TrustedCerrtificatesStoreTest.cs @@ -0,0 +1,252 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using iText.Commons.Bouncycastle.Cert; +using iText.Commons.Utils; +using iText.Signatures.Testutils; +using iText.Signatures.Validation; +using iText.Test; + +namespace iText.Signatures { + [NUnit.Framework.Category("BouncyCastleUnitTest")] + public class TrustedCerrtificatesStoreTest : ExtendedITextTest { + private static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + .CurrentContext.TestDirectory) + "/resources/itext/signatures/certs/"; + + private static readonly char[] KEY_PASSWORD = "testpassphrase".ToCharArray(); + + private static IX509Certificate crlCert; + + private static IX509Certificate crlRootCert; + + private static IX509Certificate intermediateCert; + + private static IX509Certificate ocspCert; + + private static IX509Certificate rootCert; + + private static IX509Certificate signCert; + + private static IX509Certificate tsaCert; + + private static IX509Certificate tsaRootCert; + + [NUnit.Framework.OneTimeSetUp] + public static void SetUpOnce() { + crlCert = (IX509Certificate)PemFileHelper.ReadFirstChain(SOURCE_FOLDER + "crlCert.pem")[0]; + crlRootCert = (IX509Certificate)PemFileHelper.ReadFirstChain(SOURCE_FOLDER + "crlRoot.pem")[0]; + intermediateCert = (IX509Certificate)PemFileHelper.ReadFirstChain(SOURCE_FOLDER + "intermediate.pem")[0]; + ocspCert = (IX509Certificate)PemFileHelper.ReadFirstChain(SOURCE_FOLDER + "ocspCert.pem")[0]; + rootCert = (IX509Certificate)PemFileHelper.ReadFirstChain(SOURCE_FOLDER + "root.pem")[0]; + signCert = (IX509Certificate)PemFileHelper.ReadFirstChain(SOURCE_FOLDER + "sign.pem")[0]; + tsaCert = (IX509Certificate)PemFileHelper.ReadFirstChain(SOURCE_FOLDER + "tsaCert.pem")[0]; + tsaRootCert = (IX509Certificate)PemFileHelper.ReadFirstChain(SOURCE_FOLDER + "tsaRoot.pem")[0]; + } + + [NUnit.Framework.Test] + public virtual void TestIsCertificateGenerallyTrusted() { + TrustedCertificatesStore sut = new TrustedCertificatesStore(); + sut.AddCATrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + sut.AddTimestampTrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + sut.AddOcspTrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + sut.AddCrlTrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + NUnit.Framework.Assert.IsFalse(sut.IsCertificateGenerallyTrusted(rootCert)); + sut.AddGenerallyTrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + NUnit.Framework.Assert.IsTrue(sut.IsCertificateGenerallyTrusted(rootCert)); + } + + [NUnit.Framework.Test] + public virtual void TestIsCertificateTrustedForCA() { + TrustedCertificatesStore sut = new TrustedCertificatesStore(); + sut.AddGenerallyTrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + sut.AddTimestampTrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + sut.AddOcspTrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + sut.AddCrlTrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + NUnit.Framework.Assert.IsFalse(sut.IsCertificateTrustedForCA(rootCert)); + sut.AddCATrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + NUnit.Framework.Assert.IsTrue(sut.IsCertificateTrustedForCA(rootCert)); + } + + [NUnit.Framework.Test] + public virtual void TestIsCertificateTrustedForTimestamp() { + TrustedCertificatesStore sut = new TrustedCertificatesStore(); + sut.AddGenerallyTrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + sut.AddCATrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + sut.AddOcspTrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + sut.AddCrlTrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + NUnit.Framework.Assert.IsFalse(sut.IsCertificateTrustedForTimestamp(rootCert)); + sut.AddTimestampTrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + NUnit.Framework.Assert.IsTrue(sut.IsCertificateTrustedForTimestamp(rootCert)); + } + + [NUnit.Framework.Test] + public virtual void TestIsCertificateTrustedForOcsp() { + TrustedCertificatesStore sut = new TrustedCertificatesStore(); + sut.AddGenerallyTrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + sut.AddCATrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + sut.AddTimestampTrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + sut.AddCrlTrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + NUnit.Framework.Assert.IsFalse(sut.IsCertificateTrustedForOcsp(rootCert)); + sut.AddOcspTrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + NUnit.Framework.Assert.IsTrue(sut.IsCertificateTrustedForOcsp(rootCert)); + } + + [NUnit.Framework.Test] + public virtual void TestIsCertificateTrustedForCrl() { + TrustedCertificatesStore sut = new TrustedCertificatesStore(); + sut.AddGenerallyTrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + sut.AddCATrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + sut.AddTimestampTrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + sut.AddOcspTrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + NUnit.Framework.Assert.IsFalse(sut.IsCertificateTrustedForCrl(rootCert)); + sut.AddCrlTrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + NUnit.Framework.Assert.IsTrue(sut.IsCertificateTrustedForCrl(rootCert)); + } + + [NUnit.Framework.Test] + public virtual void TestGetKnownCertificates() { + TrustedCertificatesStore sut = new TrustedCertificatesStore(); + sut.AddCrlTrustedCertificates(JavaCollectionsUtil.SingletonList(crlCert)); + sut.AddCATrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + sut.AddOcspTrustedCertificates(JavaCollectionsUtil.SingletonList(ocspCert)); + sut.AddTimestampTrustedCertificates(JavaCollectionsUtil.SingletonList(tsaCert)); + sut.AddGenerallyTrustedCertificates(JavaCollectionsUtil.SingletonList(tsaRootCert)); + NUnit.Framework.Assert.AreEqual(1, sut.GetKnownCertificates(crlCert.GetSubjectDN().ToString()).Count); + NUnit.Framework.Assert.AreEqual(1, sut.GetKnownCertificates(rootCert.GetSubjectDN().ToString()).Count); + } + + [NUnit.Framework.Test] + public virtual void TestGetAllTrustedCertificates() { + TrustedCertificatesStore sut = new TrustedCertificatesStore(); + sut.AddCrlTrustedCertificates(JavaCollectionsUtil.SingletonList(tsaRootCert)); + sut.AddCATrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + sut.AddOcspTrustedCertificates(JavaCollectionsUtil.SingletonList(tsaRootCert)); + sut.AddTimestampTrustedCertificates(JavaCollectionsUtil.SingletonList(tsaCert)); + sut.AddGenerallyTrustedCertificates(JavaCollectionsUtil.SingletonList(tsaRootCert)); + //duplicates should be removed + NUnit.Framework.Assert.AreEqual(3, sut.GetAllTrustedCertificates().Count); + NUnit.Framework.Assert.IsTrue(sut.GetAllTrustedCertificates().Contains(tsaRootCert)); + NUnit.Framework.Assert.IsTrue(sut.GetAllTrustedCertificates().Contains(rootCert)); + NUnit.Framework.Assert.IsTrue(sut.GetAllTrustedCertificates().Contains(tsaCert)); + } + + [NUnit.Framework.Test] + public virtual void TestGetAllTrustedCertificatesByName() { + TrustedCertificatesStore sut = new TrustedCertificatesStore(); + sut.AddCrlTrustedCertificates(JavaCollectionsUtil.SingletonList(tsaRootCert)); + sut.AddCATrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + sut.AddOcspTrustedCertificates(JavaCollectionsUtil.SingletonList(tsaRootCert)); + sut.AddTimestampTrustedCertificates(JavaCollectionsUtil.SingletonList(tsaCert)); + sut.AddGenerallyTrustedCertificates(JavaCollectionsUtil.SingletonList(tsaRootCert)); + //duplicates should be removed + NUnit.Framework.Assert.AreEqual(1, sut.GetAllTrustedCertificates(tsaRootCert.GetSubjectDN().ToString()).Count + ); + NUnit.Framework.Assert.IsTrue(sut.GetAllTrustedCertificates(tsaRootCert.GetSubjectDN().ToString()).Contains + (tsaRootCert)); + NUnit.Framework.Assert.IsTrue(sut.GetAllTrustedCertificates(rootCert.GetSubjectDN().ToString()).Contains(rootCert + )); + NUnit.Framework.Assert.IsTrue(sut.GetAllTrustedCertificates(tsaCert.GetSubjectDN().ToString()).Contains(tsaCert + )); + } + + [NUnit.Framework.Test] + public virtual void TestGetGenerallyTrustedCertificates() { + TrustedCertificatesStore sut = new TrustedCertificatesStore(); + sut.AddGenerallyTrustedCertificates(JavaCollectionsUtil.SingletonList(signCert)); + sut.AddCATrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + sut.AddTimestampTrustedCertificates(JavaCollectionsUtil.SingletonList(tsaCert)); + sut.AddOcspTrustedCertificates(JavaCollectionsUtil.SingletonList(ocspCert)); + sut.AddCrlTrustedCertificates(JavaCollectionsUtil.SingletonList(crlCert)); + String name = signCert.GetSubjectDN().ToString(); + NUnit.Framework.Assert.AreEqual(1, sut.GetGenerallyTrustedCertificates(name).Count); + NUnit.Framework.Assert.AreEqual(0, sut.GetCertificatesTrustedForCA(name).Count); + NUnit.Framework.Assert.AreEqual(0, sut.GetCertificatesTrustedForCrl(name).Count); + NUnit.Framework.Assert.AreEqual(0, sut.GetCertificatesTrustedForOcsp(name).Count); + NUnit.Framework.Assert.AreEqual(0, sut.GetCertificatesTrustedForTimestamp(name).Count); + } + + [NUnit.Framework.Test] + public virtual void TestGetCertificatesTrustedForCA() { + TrustedCertificatesStore sut = new TrustedCertificatesStore(); + sut.AddGenerallyTrustedCertificates(JavaCollectionsUtil.SingletonList(signCert)); + sut.AddCATrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + sut.AddTimestampTrustedCertificates(JavaCollectionsUtil.SingletonList(tsaCert)); + sut.AddOcspTrustedCertificates(JavaCollectionsUtil.SingletonList(ocspCert)); + sut.AddCrlTrustedCertificates(JavaCollectionsUtil.SingletonList(crlCert)); + String name = rootCert.GetSubjectDN().ToString(); + NUnit.Framework.Assert.AreEqual(0, sut.GetGenerallyTrustedCertificates(name).Count); + NUnit.Framework.Assert.AreEqual(1, sut.GetCertificatesTrustedForCA(name).Count); + NUnit.Framework.Assert.AreEqual(0, sut.GetCertificatesTrustedForCrl(name).Count); + NUnit.Framework.Assert.AreEqual(0, sut.GetCertificatesTrustedForOcsp(name).Count); + NUnit.Framework.Assert.AreEqual(0, sut.GetCertificatesTrustedForTimestamp(name).Count); + } + + [NUnit.Framework.Test] + public virtual void TestGetCertificatesTrustedForTimeStamp() { + TrustedCertificatesStore sut = new TrustedCertificatesStore(); + sut.AddGenerallyTrustedCertificates(JavaCollectionsUtil.SingletonList(signCert)); + sut.AddCATrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + sut.AddTimestampTrustedCertificates(JavaCollectionsUtil.SingletonList(tsaCert)); + sut.AddOcspTrustedCertificates(JavaCollectionsUtil.SingletonList(ocspCert)); + sut.AddCrlTrustedCertificates(JavaCollectionsUtil.SingletonList(crlCert)); + String name = tsaCert.GetSubjectDN().ToString(); + NUnit.Framework.Assert.AreEqual(0, sut.GetGenerallyTrustedCertificates(name).Count); + NUnit.Framework.Assert.AreEqual(0, sut.GetCertificatesTrustedForCA(name).Count); + NUnit.Framework.Assert.AreEqual(0, sut.GetCertificatesTrustedForCrl(name).Count); + NUnit.Framework.Assert.AreEqual(0, sut.GetCertificatesTrustedForOcsp(name).Count); + NUnit.Framework.Assert.AreEqual(1, sut.GetCertificatesTrustedForTimestamp(name).Count); + } + + [NUnit.Framework.Test] + public virtual void TestGetCertificatesTrustedForOcsp() { + TrustedCertificatesStore sut = new TrustedCertificatesStore(); + sut.AddGenerallyTrustedCertificates(JavaCollectionsUtil.SingletonList(signCert)); + sut.AddCATrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + sut.AddTimestampTrustedCertificates(JavaCollectionsUtil.SingletonList(tsaCert)); + sut.AddOcspTrustedCertificates(JavaCollectionsUtil.SingletonList(ocspCert)); + sut.AddCrlTrustedCertificates(JavaCollectionsUtil.SingletonList(crlCert)); + String name = ocspCert.GetSubjectDN().ToString(); + NUnit.Framework.Assert.AreEqual(0, sut.GetGenerallyTrustedCertificates(name).Count); + NUnit.Framework.Assert.AreEqual(0, sut.GetCertificatesTrustedForCA(name).Count); + NUnit.Framework.Assert.AreEqual(0, sut.GetCertificatesTrustedForCrl(name).Count); + NUnit.Framework.Assert.AreEqual(1, sut.GetCertificatesTrustedForOcsp(name).Count); + NUnit.Framework.Assert.AreEqual(0, sut.GetCertificatesTrustedForTimestamp(name).Count); + } + + [NUnit.Framework.Test] + public virtual void TestGetCertificatesTrustedForCrl() { + TrustedCertificatesStore sut = new TrustedCertificatesStore(); + sut.AddGenerallyTrustedCertificates(JavaCollectionsUtil.SingletonList(signCert)); + sut.AddCATrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + sut.AddTimestampTrustedCertificates(JavaCollectionsUtil.SingletonList(tsaCert)); + sut.AddOcspTrustedCertificates(JavaCollectionsUtil.SingletonList(ocspCert)); + sut.AddCrlTrustedCertificates(JavaCollectionsUtil.SingletonList(crlCert)); + String name = crlCert.GetSubjectDN().ToString(); + NUnit.Framework.Assert.AreEqual(0, sut.GetGenerallyTrustedCertificates(name).Count); + NUnit.Framework.Assert.AreEqual(0, sut.GetCertificatesTrustedForCA(name).Count); + NUnit.Framework.Assert.AreEqual(1, sut.GetCertificatesTrustedForCrl(name).Count); + NUnit.Framework.Assert.AreEqual(0, sut.GetCertificatesTrustedForOcsp(name).Count); + NUnit.Framework.Assert.AreEqual(0, sut.GetCertificatesTrustedForTimestamp(name).Count); + } + } +} diff --git a/itext.tests/itext.sign.tests/itext/signatures/cms/CMSContainerTest.cs b/itext.tests/itext.sign.tests/itext/signatures/cms/CMSContainerTest.cs index 5492337358..5d4915aa4b 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/cms/CMSContainerTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/cms/CMSContainerTest.cs @@ -30,6 +30,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Cert; using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Utils; +using iText.Kernel.Crypto; using iText.Kernel.Exceptions; using iText.Kernel.Pdf; using iText.Signatures; @@ -84,8 +85,8 @@ public virtual void TestSerialize() { si.SetMessageDigest(new byte[256]); si.SetOcspResponses(fakeOcspREsponses); si.SetCrlResponses(JavaCollectionsUtil.SingletonList(testCrlResponse)); - si.SetDigestAlgorithm(new AlgorithmIdentifier(SecurityIDs.ID_SHA512)); - si.SetSigningCertificateAndAddToSignedAttributes(signCert, SecurityIDs.ID_SHA512); + si.SetDigestAlgorithm(new AlgorithmIdentifier(OID.SHA_512)); + si.SetSigningCertificateAndAddToSignedAttributes(signCert, OID.SHA_512); si.SetSignatureAlgorithm(new AlgorithmIdentifier(SignatureMechanisms.GetSignatureMechanismOid("RSA", DigestAlgorithms .SHA512))); si.SetSignature(new byte[256]); @@ -105,8 +106,8 @@ public virtual void TestSerializationWithRevocationData() { SignerInfo si = new SignerInfo(); si.SetSigningCertificate(signCert); si.SetMessageDigest(new byte[256]); - si.SetDigestAlgorithm(new AlgorithmIdentifier(SecurityIDs.ID_SHA512)); - si.SetSigningCertificateAndAddToSignedAttributes(signCert, SecurityIDs.ID_SHA512); + si.SetDigestAlgorithm(new AlgorithmIdentifier(OID.SHA_512)); + si.SetSigningCertificateAndAddToSignedAttributes(signCert, OID.SHA_512); si.SetSignatureAlgorithm(new AlgorithmIdentifier(SignatureMechanisms.GetSignatureMechanismOid("RSA", DigestAlgorithms .SHA512))); si.SetSignature(new byte[256]); @@ -127,10 +128,10 @@ public virtual void TestGetSizeEstimation() { si.SetMessageDigest(new byte[256]); si.SetOcspResponses(fakeOcspREsponses); si.SetCrlResponses(JavaCollectionsUtil.SingletonList(testCrlResponse)); - si.SetDigestAlgorithm(new AlgorithmIdentifier(SecurityIDs.ID_SHA512)); + si.SetDigestAlgorithm(new AlgorithmIdentifier(OID.SHA_512)); si.SetSignatureAlgorithm(new AlgorithmIdentifier(SignatureMechanisms.GetSignatureMechanismOid("RSA", DigestAlgorithms .SHA512))); - si.SetSigningCertificateAndAddToSignedAttributes(signCert, SecurityIDs.ID_SHA512); + si.SetSigningCertificateAndAddToSignedAttributes(signCert, OID.SHA_512); si.SetSignature(new byte[256]); sut.SetSignerInfo(si); long size = sut.GetSizeEstimation(); diff --git a/itext.tests/itext.sign.tests/itext/signatures/cms/EncapsulatedContentInfoTest.cs b/itext.tests/itext.sign.tests/itext/signatures/cms/EncapsulatedContentInfoTest.cs index 1d8d3ca577..5072b829eb 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/cms/EncapsulatedContentInfoTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/cms/EncapsulatedContentInfoTest.cs @@ -25,7 +25,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle; using iText.Commons.Bouncycastle.Asn1; using iText.Commons.Utils; -using iText.Signatures; +using iText.Kernel.Crypto; using iText.Test; namespace iText.Signatures.Cms { @@ -40,10 +40,10 @@ public class EncapsulatedContentInfoTest : ExtendedITextTest { [NUnit.Framework.Test] public virtual void TestDeserializationWithoutContent() { IAsn1EncodableVector v = FACTORY.CreateASN1EncodableVector(); - v.Add(FACTORY.CreateASN1ObjectIdentifier(SecurityIDs.ID_PKCS7_DATA)); + v.Add(FACTORY.CreateASN1ObjectIdentifier(OID.PKCS7_DATA)); IAsn1Sequence testData = FACTORY.CreateDERSequence(v); EncapsulatedContentInfo sut = new EncapsulatedContentInfo(testData); - NUnit.Framework.Assert.AreEqual(SecurityIDs.ID_PKCS7_DATA, sut.GetContentType()); + NUnit.Framework.Assert.AreEqual(OID.PKCS7_DATA, sut.GetContentType()); NUnit.Framework.Assert.IsNull(sut.GetContent()); } @@ -57,16 +57,16 @@ public virtual void TestDeserializationWithContent() { [NUnit.Framework.Test] public virtual void TestCreation() { - EncapsulatedContentInfo sut = new EncapsulatedContentInfo(SecurityIDs.ID_PKCS7_DATA); - NUnit.Framework.Assert.AreEqual(SecurityIDs.ID_PKCS7_DATA, sut.GetContentType()); + EncapsulatedContentInfo sut = new EncapsulatedContentInfo(OID.PKCS7_DATA); + NUnit.Framework.Assert.AreEqual(OID.PKCS7_DATA, sut.GetContentType()); NUnit.Framework.Assert.IsNull(sut.GetContent()); } [NUnit.Framework.Test] public virtual void TestCreationWithContent() { - EncapsulatedContentInfo sut = new EncapsulatedContentInfo(SecurityIDs.ID_PKCS7_DATA, FACTORY.CreateDEROctetString - (new byte[20])); - NUnit.Framework.Assert.AreEqual(SecurityIDs.ID_PKCS7_DATA, sut.GetContentType()); + EncapsulatedContentInfo sut = new EncapsulatedContentInfo(OID.PKCS7_DATA, FACTORY.CreateDEROctetString(new + byte[20])); + NUnit.Framework.Assert.AreEqual(OID.PKCS7_DATA, sut.GetContentType()); NUnit.Framework.Assert.IsNotNull(sut.GetContent()); } } diff --git a/itext.tests/itext.sign.tests/itext/signatures/cms/SignerInfoTest.cs b/itext.tests/itext.sign.tests/itext/signatures/cms/SignerInfoTest.cs index 3500896cc0..ab65bb081a 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/cms/SignerInfoTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/cms/SignerInfoTest.cs @@ -30,8 +30,8 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Cert; using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Utils; +using iText.Kernel.Crypto; using iText.Kernel.Exceptions; -using iText.Signatures; using iText.Signatures.Exceptions; using iText.Signatures.Testutils; using iText.Signatures.Testutils.Builder; @@ -97,14 +97,14 @@ public virtual void Init() { [NUnit.Framework.Test] public virtual void TestSignedAttributesReadonlyModeActivatedByGettingSerializedData() { SignerInfo si = new SignerInfo(); - si.SetSignatureAlgorithm(new AlgorithmIdentifier(SecurityIDs.ID_RSA)); + si.SetSignatureAlgorithm(new AlgorithmIdentifier(OID.RSA)); si.SetSigningCertificate(signCert); List fakeOcspREsponses = new List(); fakeOcspREsponses.Add(Convert.FromBase64String(CMSTestHelper.BASE64_OCSP_RESPONSE)); si.SetMessageDigest(new byte[1024]); si.SetOcspResponses(fakeOcspREsponses); si.SetCrlResponses(testCrlResponse); - si.SetDigestAlgorithm(new AlgorithmIdentifier(SecurityIDs.ID_SHA512)); + si.SetDigestAlgorithm(new AlgorithmIdentifier(OID.SHA_512)); si.SerializeSignedAttributes(); NUnit.Framework.Assert.Catch(typeof(InvalidOperationException), () => si.SetSerializedSignedAttributes(new byte[1235])); @@ -115,16 +115,16 @@ public virtual void TestSignedAttributesReadonlyModeActivatedByGettingSerialized CmsAttribute attribute = new CmsAttribute("", FACTORY.CreateASN1Integer(1)); NUnit.Framework.Assert.Catch(typeof(InvalidOperationException), () => si.AddSignedAttribute(attribute)); NUnit.Framework.Assert.Catch(typeof(InvalidOperationException), () => si.AddSignerCertificateToSignedAttributes - (signCert, SecurityIDs.ID_SHA512)); + (signCert, OID.SHA_512)); } [NUnit.Framework.Test] public virtual void TestGetSerializedBasicSignedAttributes() { SignerInfo si = new SignerInfo(); - si.SetSignatureAlgorithm(new AlgorithmIdentifier(SecurityIDs.ID_RSASSA_PSS)); + si.SetSignatureAlgorithm(new AlgorithmIdentifier(OID.RSASSA_PSS)); si.SetSigningCertificate(signCert); si.SetMessageDigest(MESSAGE_DIGEST); - si.SetDigestAlgorithm(new AlgorithmIdentifier(SecurityIDs.ID_SHA512)); + si.SetDigestAlgorithm(new AlgorithmIdentifier(OID.SHA_512)); byte[] serRes = si.SerializeSignedAttributes(); NUnit.Framework.Assert.AreEqual(SerializedAsString(EXPECTEDRESULT_1), SerializedAsString(serRes)); } @@ -132,14 +132,14 @@ public virtual void TestGetSerializedBasicSignedAttributes() { [NUnit.Framework.Test] public virtual void TestGetSerializedExtendedSignedAttributes() { SignerInfo si = new SignerInfo(); - si.SetSignatureAlgorithm(new AlgorithmIdentifier(SecurityIDs.ID_RSASSA_PSS)); + si.SetSignatureAlgorithm(new AlgorithmIdentifier(OID.RSASSA_PSS)); si.SetSigningCertificate(signCert); List fakeOcspREsponses = new List(); fakeOcspREsponses.Add(Convert.FromBase64String(CMSTestHelper.BASE64_OCSP_RESPONSE)); si.SetOcspResponses(fakeOcspREsponses); si.SetCrlResponses(testCrlResponse); si.SetMessageDigest(new byte[1024]); - si.SetDigestAlgorithm(new AlgorithmIdentifier(SecurityIDs.ID_SHA512)); + si.SetDigestAlgorithm(new AlgorithmIdentifier(OID.SHA_512)); byte[] serRes = si.SerializeSignedAttributes(); NUnit.Framework.Assert.AreEqual(SerializedAsString(EXPECTEDRESULT_2), SerializedAsString(serRes)); } @@ -147,11 +147,11 @@ public virtual void TestGetSerializedExtendedSignedAttributes() { [NUnit.Framework.Test] public virtual void TestGetSerializedExtendedSignedAttributesCrlOnly() { SignerInfo si = new SignerInfo(); - si.SetSignatureAlgorithm(new AlgorithmIdentifier(SecurityIDs.ID_RSASSA_PSS)); + si.SetSignatureAlgorithm(new AlgorithmIdentifier(OID.RSASSA_PSS)); si.SetSigningCertificate(signCert); si.SetCrlResponses(testCrlResponse); si.SetMessageDigest(new byte[1024]); - si.SetDigestAlgorithm(new AlgorithmIdentifier(SecurityIDs.ID_SHA512)); + si.SetDigestAlgorithm(new AlgorithmIdentifier(OID.SHA_512)); byte[] serRes = si.SerializeSignedAttributes(); NUnit.Framework.Assert.AreEqual(SerializedAsString(EXPECTEDRESULT_5), SerializedAsString(serRes)); } @@ -159,30 +159,30 @@ public virtual void TestGetSerializedExtendedSignedAttributesCrlOnly() { [NUnit.Framework.Test] public virtual void TestAddSignedAttribute() { SignerInfo si = new SignerInfo(); - NUnit.Framework.Assert.IsFalse(si.GetSignedAttributes().Any((a) => Object.Equals(a.GetType(), SecurityIDs. - ID_SIGNING_TIME))); - CmsAttribute attrib = new CmsAttribute(SecurityIDs.ID_SIGNING_TIME, FACTORY.CreateNullASN1Set()); + NUnit.Framework.Assert.IsFalse(si.GetSignedAttributes().Any((a) => Object.Equals(a.GetType(), OID.SIGNING_TIME + ))); + CmsAttribute attrib = new CmsAttribute(OID.SIGNING_TIME, FACTORY.CreateNullASN1Set()); si.AddSignedAttribute(attrib); - NUnit.Framework.Assert.IsTrue(si.GetSignedAttributes().Any((a) => Object.Equals(a.GetType(), SecurityIDs.ID_SIGNING_TIME + NUnit.Framework.Assert.IsTrue(si.GetSignedAttributes().Any((a) => Object.Equals(a.GetType(), OID.SIGNING_TIME ))); } [NUnit.Framework.Test] public virtual void TestAddUnsignedAttribute() { SignerInfo si = new SignerInfo(); - CmsAttribute attrib = new CmsAttribute(SecurityIDs.ID_SIGNING_TIME, FACTORY.CreateNullASN1Set()); + CmsAttribute attrib = new CmsAttribute(OID.SIGNING_TIME, FACTORY.CreateNullASN1Set()); si.AddUnSignedAttribute(attrib); - NUnit.Framework.Assert.AreEqual(SecurityIDs.ID_SIGNING_TIME, SignTestPortUtil.GetFirstElement(si.GetUnSignedAttributes()).GetType()); + NUnit.Framework.Assert.AreEqual(OID.SIGNING_TIME, SignTestPortUtil.GetFirstElement(si.GetUnSignedAttributes + ()).GetType()); } [NUnit.Framework.Test] public virtual void TestGetSerializedSignedAttributesWithCertificateId() { SignerInfo si = new SignerInfo(); - si.SetSignatureAlgorithm(new AlgorithmIdentifier(SecurityIDs.ID_RSASSA_PSS)); + si.SetSignatureAlgorithm(new AlgorithmIdentifier(OID.RSASSA_PSS)); si.SetSigningCertificate(signCert); si.SetMessageDigest(new byte[1024]); - si.SetDigestAlgorithm(new AlgorithmIdentifier(SecurityIDs.ID_SHA512)); + si.SetDigestAlgorithm(new AlgorithmIdentifier(OID.SHA_512)); si.AddSignerCertificateToSignedAttributes(signCert, "2.16.840.1.101.3.4.2.3"); byte[] serRes = si.SerializeSignedAttributes(); NUnit.Framework.Assert.AreEqual(SerializedAsString(EXPECTEDRESULT_3), SerializedAsString(serRes)); @@ -191,10 +191,10 @@ public virtual void TestGetSerializedSignedAttributesWithCertificateId() { [NUnit.Framework.Test] public virtual void TestGetSerializedSignedAttributesWithCertificateIdTroughCertSetter() { SignerInfo si = new SignerInfo(); - si.SetSignatureAlgorithm(new AlgorithmIdentifier(SecurityIDs.ID_RSASSA_PSS)); + si.SetSignatureAlgorithm(new AlgorithmIdentifier(OID.RSASSA_PSS)); si.SetSigningCertificateAndAddToSignedAttributes(signCert, "2.16.840.1.101.3.4.2.3"); si.SetMessageDigest(new byte[1024]); - si.SetDigestAlgorithm(new AlgorithmIdentifier(SecurityIDs.ID_SHA512)); + si.SetDigestAlgorithm(new AlgorithmIdentifier(OID.SHA_512)); byte[] serRes = si.SerializeSignedAttributes(); NUnit.Framework.Assert.AreEqual(SerializedAsString(EXPECTEDRESULT_3), SerializedAsString(serRes)); } @@ -202,12 +202,12 @@ public virtual void TestGetSerializedSignedAttributesWithCertificateIdTroughCert [NUnit.Framework.Test] public virtual void TestGetAsDerSequence() { SignerInfo si = new SignerInfo(); - si.AddUnSignedAttribute(new CmsAttribute(SecurityIDs.ID_SIGNING_TIME, FACTORY.CreateDERSet(FACTORY.CreateASN1Integer - (123456)))); + si.AddUnSignedAttribute(new CmsAttribute(OID.SIGNING_TIME, FACTORY.CreateDERSet(FACTORY.CreateASN1Integer( + 123456)))); si.SetSigningCertificateAndAddToSignedAttributes(signCert, "2.16.840.1.101.3.4.2.3"); - si.SetSignatureAlgorithm(new AlgorithmIdentifier(SecurityIDs.ID_RSASSA_PSS)); + si.SetSignatureAlgorithm(new AlgorithmIdentifier(OID.RSASSA_PSS)); si.SetMessageDigest(new byte[1024]); - si.SetDigestAlgorithm(new AlgorithmIdentifier(SecurityIDs.ID_SHA512)); + si.SetDigestAlgorithm(new AlgorithmIdentifier(OID.SHA_512)); si.SetSignature(new byte[512]); IDerSequence res = si.GetAsDerSequence(); NUnit.Framework.Assert.AreEqual(SerializedAsString(EXPECTEDRESULT_4), SerializedAsString(res.GetEncoded()) @@ -217,12 +217,12 @@ public virtual void TestGetAsDerSequence() { [NUnit.Framework.Test] public virtual void TestEstimatedSizeWithSignature() { SignerInfo si = new SignerInfo(); - si.AddUnSignedAttribute(new CmsAttribute(SecurityIDs.ID_SIGNING_TIME, FACTORY.CreateDERSet(FACTORY.CreateASN1Integer - (123456)))); - si.SetSignatureAlgorithm(new AlgorithmIdentifier(SecurityIDs.ID_RSASSA_PSS)); + si.AddUnSignedAttribute(new CmsAttribute(OID.SIGNING_TIME, FACTORY.CreateDERSet(FACTORY.CreateASN1Integer( + 123456)))); + si.SetSignatureAlgorithm(new AlgorithmIdentifier(OID.RSASSA_PSS)); si.SetSigningCertificateAndAddToSignedAttributes(signCert, "2.16.840.1.101.3.4.2.3"); si.SetMessageDigest(new byte[1024]); - si.SetDigestAlgorithm(new AlgorithmIdentifier(SecurityIDs.ID_SHA512)); + si.SetDigestAlgorithm(new AlgorithmIdentifier(OID.SHA_512)); si.SetSignature(new byte[512]); long res = si.GetEstimatedSize(); NUnit.Framework.Assert.AreEqual(1973, res); @@ -231,10 +231,10 @@ public virtual void TestEstimatedSizeWithSignature() { [NUnit.Framework.Test] public virtual void TestSignedAttributesSerializationRoundTrip() { SignerInfo si = new SignerInfo(); - si.SetSignatureAlgorithm(new AlgorithmIdentifier(SecurityIDs.ID_RSASSA_PSS)); + si.SetSignatureAlgorithm(new AlgorithmIdentifier(OID.RSASSA_PSS)); si.SetSigningCertificateAndAddToSignedAttributes(signCert, "2.16.840.1.101.3.4.2.3"); si.SetMessageDigest(new byte[1024]); - si.SetDigestAlgorithm(new AlgorithmIdentifier(SecurityIDs.ID_SHA512)); + si.SetDigestAlgorithm(new AlgorithmIdentifier(OID.SHA_512)); si.SetSignature(new byte[512]); byte[] serialized = si.SerializeSignedAttributes(); SignerInfo si2 = new SignerInfo(); @@ -250,12 +250,12 @@ public virtual void TestSignedAttributesSerializationRoundTrip() { [NUnit.Framework.Test] public virtual void TestEstimatedSizeEstimatedSignature() { SignerInfo si = new SignerInfo(); - si.AddUnSignedAttribute(new CmsAttribute(SecurityIDs.ID_SIGNING_TIME, FACTORY.CreateDERSet(FACTORY.CreateASN1Integer - (123456)))); - si.SetSignatureAlgorithm(new AlgorithmIdentifier(SecurityIDs.ID_RSASSA_PSS)); + si.AddUnSignedAttribute(new CmsAttribute(OID.SIGNING_TIME, FACTORY.CreateDERSet(FACTORY.CreateASN1Integer( + 123456)))); + si.SetSignatureAlgorithm(new AlgorithmIdentifier(OID.RSASSA_PSS)); si.SetSigningCertificateAndAddToSignedAttributes(signCert, "2.16.840.1.101.3.4.2.3"); si.SetMessageDigest(new byte[1024]); - si.SetDigestAlgorithm(new AlgorithmIdentifier(SecurityIDs.ID_SHA512)); + si.SetDigestAlgorithm(new AlgorithmIdentifier(OID.SHA_512)); long res = si.GetEstimatedSize(); NUnit.Framework.Assert.AreEqual(2485, res); } @@ -263,12 +263,12 @@ public virtual void TestEstimatedSizeEstimatedSignature() { [NUnit.Framework.Test] public virtual void TestSerializeAndDeserializeSignerInfo() { SignerInfo si = new SignerInfo(); - si.AddUnSignedAttribute(new CmsAttribute(SecurityIDs.ID_SIGNING_TIME, FACTORY.CreateDERSet(FACTORY.CreateASN1Integer - (123456)))); - si.SetSignatureAlgorithm(new AlgorithmIdentifier(SecurityIDs.ID_RSASSA_PSS)); + si.AddUnSignedAttribute(new CmsAttribute(OID.SIGNING_TIME, FACTORY.CreateDERSet(FACTORY.CreateASN1Integer( + 123456)))); + si.SetSignatureAlgorithm(new AlgorithmIdentifier(OID.RSASSA_PSS)); si.SetSigningCertificateAndAddToSignedAttributes(signCert, "2.16.840.1.101.3.4.2.3"); si.SetMessageDigest(new byte[1024]); - si.SetDigestAlgorithm(new AlgorithmIdentifier(SecurityIDs.ID_SHA512)); + si.SetDigestAlgorithm(new AlgorithmIdentifier(OID.SHA_512)); IDerSequence encoded = si.GetAsDerSequence(false); SignerInfo si2 = new SignerInfo(encoded, JavaCollectionsUtil.SingletonList(signCert)); NUnit.Framework.Assert.AreEqual(si.GetSignedAttributes().Count, si2.GetSignedAttributes().Count); @@ -277,7 +277,7 @@ public virtual void TestSerializeAndDeserializeSignerInfo() { [NUnit.Framework.Test] public virtual void TestSerializeAndDeserializeSignedAttributes() { SignerInfo si = new SignerInfo(); - si.AddSignerCertificateToSignedAttributes(signCert, SecurityIDs.ID_SHA256); + si.AddSignerCertificateToSignedAttributes(signCert, OID.SHA_256); si.SetMessageDigest(new byte[20]); byte[] attribs = si.SerializeSignedAttributes(); SignerInfo si2 = new SignerInfo(); diff --git a/itext.tests/itext.sign.tests/itext/signatures/mac/ReadSignedMacProtectedDocumentTest.cs b/itext.tests/itext.sign.tests/itext/signatures/mac/ReadSignedMacProtectedDocumentTest.cs new file mode 100644 index 0000000000..a606f28189 --- /dev/null +++ b/itext.tests/itext.sign.tests/itext/signatures/mac/ReadSignedMacProtectedDocumentTest.cs @@ -0,0 +1,81 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using iText.Commons.Utils; +using iText.Kernel.Exceptions; +using iText.Kernel.Logs; +using iText.Kernel.Pdf; +using iText.Kernel.Utils; +using iText.Test; +using iText.Test.Attributes; + +namespace iText.Signatures.Mac { + [NUnit.Framework.Category("BouncyCastleIntegrationTest")] + public class ReadSignedMacProtectedDocumentTest : ExtendedITextTest { + private static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + .CurrentContext.TestDirectory) + "/resources/itext/signatures/mac/ReadSignedMacProtectedDocumentTest/"; + + private static readonly String DESTINATION_FOLDER = NUnit.Framework.TestContext.CurrentContext.TestDirectory + + "/test/itext/signatures/mac/ReadSignedMacProtectedDocumentTest/"; + + private static readonly byte[] ENCRYPTION_PASSWORD = "123".GetBytes(); + + [NUnit.Framework.OneTimeSetUp] + public static void Before() { + CreateOrClearDestinationFolder(DESTINATION_FOLDER); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void ReadSignedMacProtectedInvalidDocTest() { + String srcFileName = SOURCE_FOLDER + "signedMacProtectedInvalidDoc.pdf"; + String exceptionMessage = NUnit.Framework.Assert.Catch(typeof(PdfException), () => { + using (PdfDocument ignored = new PdfDocument(new PdfReader(srcFileName, new ReaderProperties().SetPassword + (ENCRYPTION_PASSWORD)))) { + } + } + ).Message; + // Do nothing. + NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.MAC_VALIDATION_FAILED, exceptionMessage); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void UpdateSignedMacProtectedDocumentTest() { + String fileName = "updateSignedMacProtectedDocumentTest.pdf"; + String srcFileName = SOURCE_FOLDER + "thirdPartyMacProtectedAndSignedDocument.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + String cmpFileName = SOURCE_FOLDER + "cmp_" + fileName; + using (PdfDocument ignored = new PdfDocument(new PdfReader(srcFileName, new ReaderProperties().SetPassword + (ENCRYPTION_PASSWORD)), new PdfWriter(FileUtil.GetFileOutputStream(outputFileName)), new StampingProperties + ().UseAppendMode())) { + } + // Do nothing. + // This call produces INFO log from AESCipher caused by exception while decrypting. The reason is that, + // while comparing encrypted signed documents, CompareTool needs to mark signature value as unencrypted. + // Instead, it tries to decrypt not encrypted value which results in exception. + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outputFileName, cmpFileName, DESTINATION_FOLDER + , "diff", ENCRYPTION_PASSWORD, ENCRYPTION_PASSWORD)); + } + } +} diff --git a/itext.tests/itext.sign.tests/itext/signatures/mac/SignedDocumentWithMacTest.cs b/itext.tests/itext.sign.tests/itext/signatures/mac/SignedDocumentWithMacTest.cs new file mode 100644 index 0000000000..94c695cf3a --- /dev/null +++ b/itext.tests/itext.sign.tests/itext/signatures/mac/SignedDocumentWithMacTest.cs @@ -0,0 +1,326 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using System.Collections.Generic; +using System.IO; +using NUnit.Framework; +using iText.Bouncycastleconnector; +using iText.Commons.Bouncycastle; +using iText.Commons.Bouncycastle.Cert; +using iText.Commons.Bouncycastle.Crypto; +using iText.Commons.Utils; +using iText.Kernel.Crypto; +using iText.Kernel.Exceptions; +using iText.Kernel.Logs; +using iText.Kernel.Pdf; +using iText.Signatures; +using iText.Signatures.Testutils; +using iText.Signatures.Testutils.Client; +using iText.Test; +using iText.Test.Attributes; + +namespace iText.Signatures.Mac { + [NUnit.Framework.Category("BouncyCastleIntegrationTest")] + public class SignedDocumentWithMacTest : ExtendedITextTest { + private static readonly IBouncyCastleFactory FACTORY = BouncyCastleFactoryCreator.GetFactory(); + + private static readonly String CERTS_SRC = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + .CurrentContext.TestDirectory) + "/resources/itext/signatures/mac/SignedDocumentWithMacTest/certs/"; + + private static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + .CurrentContext.TestDirectory) + "/resources/itext/signatures/mac/SignedDocumentWithMacTest/"; + + private static readonly String DESTINATION_FOLDER = NUnit.Framework.TestContext.CurrentContext.TestDirectory + + "/test/itext/signatures/mac/SignedDocumentWithMacTest/"; + + private static readonly byte[] ENCRYPTION_PASSWORD = "123".GetBytes(); + + private static readonly char[] PRIVATE_KEY_PASSWORD = "testpassphrase".ToCharArray(); + + [NUnit.Framework.OneTimeSetUp] + public static void Before() { + CreateOrClearDestinationFolder(DESTINATION_FOLDER); + } + + public static IEnumerable CreateParameters() { + return JavaUtil.ArraysAsList(new Object[] { "signCertRsa01.pem", "signDetached" }, new Object[] { "tsaCert.pem" + , "timestamping" }, new Object[] { "signCertRsa01.pem", "signExternalContainerReal" }, new Object[] { + "signCertRsa01.pem", "signExternalContainerBlank" }); + } + + [NUnit.Framework.TestCaseSource("CreateParameters")] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void SignMacProtectedDocTest(String certName, String signingOperation) { + String fileName = "signMacProtectedDocTest_" + signingOperation + ".pdf"; + String srcFileName = SOURCE_FOLDER + "macEncryptedDoc.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + String signCertFileName = CERTS_SRC + certName; + String cmpFileName = SOURCE_FOLDER + "cmp_" + fileName; + IX509Certificate[] signRsaChain = PemFileHelper.ReadFirstChain(signCertFileName); + IPrivateKey signRsaPrivateKey = PemFileHelper.ReadFirstKey(signCertFileName, PRIVATE_KEY_PASSWORD); + using (PdfReader reader = new PdfReader(srcFileName, new ReaderProperties().SetPassword(ENCRYPTION_PASSWORD + ))) { + using (Stream outputStream = FileUtil.GetFileOutputStream(outputFileName)) { + PdfSigner pdfSigner = new PdfSigner(reader, outputStream, new StampingProperties()); + if (signingOperation.Equals("signExternalContainerBlank")) { + NUnit.Framework.Assert.Catch(typeof(PdfException), () => PerformSigningOperation(signingOperation, pdfSigner + , signRsaPrivateKey, signRsaChain)); + } + else { + PerformSigningOperation(signingOperation, pdfSigner, signRsaPrivateKey, signRsaChain); + } + } + } + if (!signingOperation.Equals("signExternalContainerBlank")) { + ReaderProperties properties = new ReaderProperties().SetPassword(ENCRYPTION_PASSWORD); + NUnit.Framework.Assert.IsNull(SignaturesCompareTool.CompareSignatures(outputFileName, cmpFileName, properties + , properties)); + } + } + + [NUnit.Framework.TestCaseSource("CreateParameters")] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void SignNotMacProtectedDocTest(String certName, String signingOperation) { + String fileName = "signNotMacProtectedDocTest_" + signingOperation + ".pdf"; + String srcFileName = SOURCE_FOLDER + "noMacProtectionDocument.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + String signCertFileName = CERTS_SRC + certName; + String cmpFileName = SOURCE_FOLDER + "cmp_" + fileName; + IX509Certificate[] signRsaChain = PemFileHelper.ReadFirstChain(signCertFileName); + IPrivateKey signRsaPrivateKey = PemFileHelper.ReadFirstKey(signCertFileName, PRIVATE_KEY_PASSWORD); + using (PdfReader reader = new PdfReader(srcFileName, new ReaderProperties().SetPassword(ENCRYPTION_PASSWORD + ))) { + using (Stream outputStream = FileUtil.GetFileOutputStream(outputFileName)) { + PdfSigner pdfSigner = new PdfSigner(reader, outputStream, new StampingProperties()); + if (signingOperation.Equals("signExternalContainerBlank")) { + NUnit.Framework.Assert.Catch(typeof(PdfException), () => PerformSigningOperation(signingOperation, pdfSigner + , signRsaPrivateKey, signRsaChain)); + } + else { + PerformSigningOperation(signingOperation, pdfSigner, signRsaPrivateKey, signRsaChain); + } + } + } + if (!signingOperation.Equals("signExternalContainerBlank")) { + ReaderProperties properties = new ReaderProperties().SetPassword(ENCRYPTION_PASSWORD); + NUnit.Framework.Assert.IsNull(SignaturesCompareTool.CompareSignatures(outputFileName, cmpFileName, properties + , properties)); + } + } + + [NUnit.Framework.TestCaseSource("CreateParameters")] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void SignNotMacProtectedDoc17Test(String certName, String signingOperation) { + String fileName = "signNotMacProtectedDoc17Test_" + signingOperation + ".pdf"; + String srcFileName = SOURCE_FOLDER + "noMacProtectionDocument_1_7.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + String signCertFileName = CERTS_SRC + certName; + String cmpFileName = SOURCE_FOLDER + "cmp_" + fileName; + IX509Certificate[] signRsaChain = PemFileHelper.ReadFirstChain(signCertFileName); + IPrivateKey signRsaPrivateKey = PemFileHelper.ReadFirstKey(signCertFileName, PRIVATE_KEY_PASSWORD); + using (PdfReader reader = new PdfReader(srcFileName, new ReaderProperties().SetPassword(ENCRYPTION_PASSWORD + ))) { + using (Stream outputStream = FileUtil.GetFileOutputStream(outputFileName)) { + PdfSigner pdfSigner = new PdfSigner(reader, outputStream, new StampingProperties()); + PerformSigningOperation(signingOperation, pdfSigner, signRsaPrivateKey, signRsaChain); + } + } + // TODO DEVSIX-8637 Add else statement for empty signature container + if (!signingOperation.Equals("signExternalContainerBlank")) { + ReaderProperties properties = new ReaderProperties().SetPassword(ENCRYPTION_PASSWORD); + NUnit.Framework.Assert.IsNull(SignaturesCompareTool.CompareSignatures(outputFileName, cmpFileName, properties + , properties)); + } + } + + [NUnit.Framework.TestCaseSource("CreateParameters")] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void SignNotMacProtectedDocInAppendModeTest(String certName, String signingOperation) { + // MAC should not be added in append mode + String fileName = "signNotMacProtectedDocInAppendModeTest_" + signingOperation + ".pdf"; + String srcFileName = SOURCE_FOLDER + "noMacProtectionDocument.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + String signCertFileName = CERTS_SRC + certName; + String cmpFileName = SOURCE_FOLDER + "cmp_" + fileName; + IX509Certificate[] signRsaChain = PemFileHelper.ReadFirstChain(signCertFileName); + IPrivateKey signRsaPrivateKey = PemFileHelper.ReadFirstKey(signCertFileName, PRIVATE_KEY_PASSWORD); + using (PdfReader reader = new PdfReader(srcFileName, new ReaderProperties().SetPassword(ENCRYPTION_PASSWORD + ))) { + using (Stream outputStream = FileUtil.GetFileOutputStream(outputFileName)) { + PdfSigner pdfSigner = new PdfSigner(reader, outputStream, new StampingProperties().UseAppendMode()); + PerformSigningOperation(signingOperation, pdfSigner, signRsaPrivateKey, signRsaChain); + } + } + // TODO DEVSIX-8637 Add else statement for empty signature container + if (!signingOperation.Equals("signExternalContainerBlank")) { + ReaderProperties properties = new ReaderProperties().SetPassword(ENCRYPTION_PASSWORD); + NUnit.Framework.Assert.IsNull(SignaturesCompareTool.CompareSignatures(outputFileName, cmpFileName, properties + , properties)); + } + } + + [NUnit.Framework.TestCaseSource("CreateParameters")] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void SignMacProtectedDocInAppendModeTest(String certName, String signingOperation) { + String fileName = "signMacProtectedDocInAppendModeTest_" + signingOperation + ".pdf"; + String srcFileName = SOURCE_FOLDER + "macEncryptedDoc.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + String signCertFileName = CERTS_SRC + certName; + String cmpFileName = SOURCE_FOLDER + "cmp_" + fileName; + IX509Certificate[] signRsaChain = PemFileHelper.ReadFirstChain(signCertFileName); + IPrivateKey signRsaPrivateKey = PemFileHelper.ReadFirstKey(signCertFileName, PRIVATE_KEY_PASSWORD); + using (PdfReader reader = new PdfReader(srcFileName, new ReaderProperties().SetPassword(ENCRYPTION_PASSWORD + ))) { + using (Stream outputStream = FileUtil.GetFileOutputStream(outputFileName)) { + PdfSigner pdfSigner = new PdfSigner(reader, outputStream, new StampingProperties().UseAppendMode()); + if (signingOperation.Equals("signExternalContainerBlank")) { + NUnit.Framework.Assert.Catch(typeof(PdfException), () => PerformSigningOperation(signingOperation, pdfSigner + , signRsaPrivateKey, signRsaChain)); + } + else { + PerformSigningOperation(signingOperation, pdfSigner, signRsaPrivateKey, signRsaChain); + } + } + } + if (!signingOperation.Equals("signExternalContainerBlank")) { + ReaderProperties properties = new ReaderProperties().SetPassword(ENCRYPTION_PASSWORD); + NUnit.Framework.Assert.IsNull(SignaturesCompareTool.CompareSignatures(outputFileName, cmpFileName, properties + , properties)); + } + } + + [NUnit.Framework.TestCaseSource("CreateParameters")] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void SignMacProtectedDocWithSHA3_384Test(String certName, String signingOperation) { + String fileName = "signMacProtectedDocWithSHA3_384Test_" + signingOperation + ".pdf"; + String srcFileName = SOURCE_FOLDER + "macEncryptedDocSHA3_384.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + String signCertFileName = CERTS_SRC + certName; + String cmpFileName = SOURCE_FOLDER + "cmp_" + fileName; + IX509Certificate[] signRsaChain = PemFileHelper.ReadFirstChain(signCertFileName); + IPrivateKey signRsaPrivateKey = PemFileHelper.ReadFirstKey(signCertFileName, PRIVATE_KEY_PASSWORD); + using (PdfReader reader = new PdfReader(srcFileName, new ReaderProperties().SetPassword(ENCRYPTION_PASSWORD + ))) { + using (Stream outputStream = FileUtil.GetFileOutputStream(outputFileName)) { + PdfSigner pdfSigner = new PdfSigner(reader, outputStream, new StampingProperties()); + if (signingOperation.Equals("signExternalContainerBlank")) { + NUnit.Framework.Assert.Catch(typeof(PdfException), () => PerformSigningOperation(signingOperation, pdfSigner + , signRsaPrivateKey, signRsaChain)); + } + else { + PerformSigningOperation(signingOperation, pdfSigner, signRsaPrivateKey, signRsaChain); + } + } + } + if (!signingOperation.Equals("signExternalContainerBlank")) { + ReaderProperties properties = new ReaderProperties().SetPassword(ENCRYPTION_PASSWORD); + NUnit.Framework.Assert.IsNull(SignaturesCompareTool.CompareSignatures(outputFileName, cmpFileName, properties + , properties)); + } + } + + [NUnit.Framework.TestCaseSource("CreateParameters")] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void SignMacPublicEncryptionDocTest(String certName, String signingOperation) { + try { + BouncyCastleFactoryCreator.GetFactory().IsEncryptionFeatureSupported(0, true); + } + catch (Exception) { + NUnit.Framework.Assume.That(false); + } + String fileName = "signMacPublicEncryptionDocTest_" + signingOperation + ".pdf"; + String srcFileName = SOURCE_FOLDER + "macEncryptedWithPublicHandlerDoc.pdf"; + String outputFileName = DESTINATION_FOLDER + fileName; + String signCertFileName = CERTS_SRC + certName; + String cmpFileName = SOURCE_FOLDER + "cmp_" + fileName; + IX509Certificate[] signRsaChain = PemFileHelper.ReadFirstChain(signCertFileName); + IPrivateKey signRsaPrivateKey = PemFileHelper.ReadFirstKey(signCertFileName, PRIVATE_KEY_PASSWORD); + IX509Certificate certificate = CryptoUtil.ReadPublicCertificate(FileUtil.GetInputStreamForFile(CERTS_SRC + + "SHA256withRSA.cer")); + IPrivateKey privateKey = PemFileHelper.ReadFirstKey(CERTS_SRC + "SHA256withRSA.key", PRIVATE_KEY_PASSWORD); + ReaderProperties properties = new ReaderProperties().SetPublicKeySecurityParams(certificate, privateKey); + using (PdfReader reader = new PdfReader(srcFileName, properties)) { + using (Stream outputStream = FileUtil.GetFileOutputStream(outputFileName)) { + PdfSigner pdfSigner = new PdfSigner(reader, outputStream, new StampingProperties()); + if (signingOperation.Equals("signExternalContainerBlank")) { + NUnit.Framework.Assert.Catch(typeof(PdfException), () => PerformSigningOperation(signingOperation, pdfSigner + , signRsaPrivateKey, signRsaChain)); + } + else { + PerformSigningOperation(signingOperation, pdfSigner, signRsaPrivateKey, signRsaChain); + } + } + } + if (!signingOperation.Equals("signExternalContainerBlank")) { + NUnit.Framework.Assert.IsNull(SignaturesCompareTool.CompareSignatures(outputFileName, cmpFileName, properties + , properties)); + } + } + + private static void PerformSigningOperation(String signingOperation, PdfSigner pdfSigner, IPrivateKey privateKey + , IX509Certificate[] chain) { + switch (signingOperation) { + case "signDetached": { + PerformSignDetached(pdfSigner, privateKey, chain); + break; + } + + case "timestamping": { + PerformTimestamping(pdfSigner, privateKey, chain); + break; + } + + case "signExternalContainerReal": { + PerformSignExternalContainerReal(pdfSigner, privateKey, chain); + break; + } + + case "signExternalContainerBlank": { + PerformSignExternalContainerBlank(pdfSigner); + break; + } + } + } + + private static void PerformSignDetached(PdfSigner pdfSigner, IPrivateKey privateKey, IX509Certificate[] chain + ) { + pdfSigner.SignDetached(new PrivateKeySignature(privateKey, DigestAlgorithms.SHA256), chain, null, null, null + , 0, PdfSigner.CryptoStandard.CADES); + } + + private static void PerformSignExternalContainerReal(PdfSigner pdfSigner, IPrivateKey privateKey, IX509Certificate + [] chain) { + pdfSigner.SignExternalContainer(new PKCS7ExternalSignatureContainer(privateKey, chain, "SHA-512"), 5000); + } + + private static void PerformSignExternalContainerBlank(PdfSigner pdfSigner) { + pdfSigner.SignExternalContainer(new ExternalBlankSignatureContainer(PdfName.Adobe_PPKLite, PdfName.Adbe_pkcs7_detached + ), 5000); + } + + private static void PerformTimestamping(PdfSigner pdfSigner, IPrivateKey privateKey, IX509Certificate[] chain + ) { + pdfSigner.Timestamp(new TestTsaClient(JavaUtil.ArraysAsList(chain), privateKey), "timestamp1"); + } + } +} diff --git a/itext.tests/itext.sign.tests/itext/signatures/sign/AnnotationsSigningTest.cs b/itext.tests/itext.sign.tests/itext/signatures/sign/AnnotationsSigningTest.cs index 0884ae6a06..0e42064882 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/sign/AnnotationsSigningTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/sign/AnnotationsSigningTest.cs @@ -25,6 +25,9 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Cert; using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Utils; +using iText.Forms.Fields.Properties; +using iText.Forms.Form.Element; +using iText.Kernel.Crypto; using iText.Kernel.Geom; using iText.Kernel.Pdf; using iText.Kernel.Utils; @@ -69,7 +72,7 @@ public virtual void SigningDocumentAppendModeIndirectPageAnnotsTest() { Rectangle rect = new Rectangle(30, 200, 200, 100); String fieldName = "Signature1"; Sign(srcFile, fieldName, outPdf, chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CADES, "Test 1" - , "TestCity", rect, false, true, PdfSigner.NOT_CERTIFIED, 12f); + , "TestCity", rect, false, true, AccessPermissions.UNSPECIFIED, 12f); NUnit.Framework.Assert.IsNull(new CompareTool().CompareVisually(outPdf, cmpPdf, DESTINATION_FOLDER, "diff_" , GetTestMap(rect))); NUnit.Framework.Assert.IsNull(SignaturesCompareTool.CompareSignatures(outPdf, cmpPdf)); @@ -83,7 +86,7 @@ public virtual void SigningIntoExistingFieldWithPKeyTest() { String outPdf = DESTINATION_FOLDER + "emptySignature01.pdf"; String fieldName = "Signature1"; Sign(srcFile, fieldName, outPdf, chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CADES, "Test 1" - , "TestCity", null, false, false, PdfSigner.NOT_CERTIFIED, 12f); + , "TestCity", null, false, false, AccessPermissions.UNSPECIFIED, 12f); NUnit.Framework.Assert.IsNull(new CompareTool().CompareVisually(outPdf, cmpPdf, DESTINATION_FOLDER, "diff_" , GetTestMap(new Rectangle(41, 693, 237, 781)))); NUnit.Framework.Assert.IsNull(SignaturesCompareTool.CompareSignatures(outPdf, cmpPdf)); @@ -97,7 +100,7 @@ public virtual void SigningIntoExistingFieldWithoutPKeyTest() { String outPdf = DESTINATION_FOLDER + "emptySignature02.pdf"; String fieldName = "Signature1"; Sign(srcFile, fieldName, outPdf, chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CADES, "Test 1" - , "TestCity", null, false, false, PdfSigner.NOT_CERTIFIED, 12f); + , "TestCity", null, false, false, AccessPermissions.UNSPECIFIED, 12f); NUnit.Framework.Assert.IsNull(new CompareTool().CompareVisually(outPdf, cmpPdf, DESTINATION_FOLDER, "diff_" , GetTestMap(new Rectangle(41, 693, 237, 781)))); NUnit.Framework.Assert.IsNull(SignaturesCompareTool.CompareSignatures(outPdf, cmpPdf)); @@ -118,30 +121,33 @@ protected internal virtual void Sign(String src, String name, String dest, IX509 pk, String digestAlgorithm, PdfSigner.CryptoStandard subfilter, String reason, String location, Rectangle rectangleForNewField, bool setReuseAppearance, bool isAppendMode) { Sign(src, name, dest, chain, pk, digestAlgorithm, subfilter, reason, location, rectangleForNewField, setReuseAppearance - , isAppendMode, PdfSigner.NOT_CERTIFIED, null); + , isAppendMode, AccessPermissions.UNSPECIFIED, null); } protected internal virtual void Sign(String src, String name, String dest, IX509Certificate[] chain, IPrivateKey pk, String digestAlgorithm, PdfSigner.CryptoStandard subfilter, String reason, String location, Rectangle - rectangleForNewField, bool setReuseAppearance, bool isAppendMode, int certificationLevel, float? fontSize - ) { + rectangleForNewField, bool setReuseAppearance, bool isAppendMode, AccessPermissions certificationLevel + , float? fontSize) { PdfReader reader = new PdfReader(src); StampingProperties properties = new StampingProperties(); if (isAppendMode) { properties.UseAppendMode(); } PdfSigner signer = new PdfSigner(reader, FileUtil.GetFileOutputStream(dest), properties); - signer.SetCertificationLevel(certificationLevel); - signer.SetFieldName(name); + SignerProperties signerProperties = new SignerProperties().SetCertificationLevel(certificationLevel).SetFieldName + (name); // Creating the appearance - PdfSignatureAppearance appearance = signer.GetSignatureAppearance(); - appearance.SetReason(reason).SetLocation(location).SetReuseAppearance(setReuseAppearance); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent + (new SignedAppearanceText()); + signerProperties.SetReason(reason).SetLocation(location).SetSignatureAppearance(appearance); if (rectangleForNewField != null) { - signer.SetPageRect(rectangleForNewField); + signerProperties.SetPageRect(rectangleForNewField); } if (fontSize != null) { - appearance.SetLayer2FontSize((float)fontSize); + appearance.SetFontSize((float)fontSize); } + signer.SetSignerProperties(signerProperties); + signer.GetSignatureField().SetReuseAppearance(setReuseAppearance); // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm); signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, subfilter); diff --git a/itext.tests/itext.sign.tests/itext/signatures/sign/CrlClientOnlineTest.cs b/itext.tests/itext.sign.tests/itext/signatures/sign/CrlClientOnlineTest.cs index 56eda802c1..d3171d5848 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/sign/CrlClientOnlineTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/sign/CrlClientOnlineTest.cs @@ -119,14 +119,14 @@ public virtual void CannotGetEncodedWhenCertIsNullTest() { [LogMessage("Checking CRL: ", LogLevel = LogLevelConstants.INFO, Count = 3)] [LogMessage("Added CRL found at: ", LogLevel = LogLevelConstants.INFO, Count = 3)] public virtual void UnreachableSeveralCrlDistributionPointsFromTheCertChainTest() { - CrlClientOnline crlClientOnline = new _CrlClientOnline_152(); + CrlClientOnline crlClientOnline = new _CrlClientOnline_151(); IX509Certificate checkCert = (IX509Certificate)PemFileHelper.ReadFirstChain(chainWithSeveralUrls)[1]; ICollection bytes = crlClientOnline.GetEncoded(checkCert, null); NUnit.Framework.Assert.AreEqual(3, bytes.Count); } - private sealed class _CrlClientOnline_152 : CrlClientOnline { - public _CrlClientOnline_152() { + private sealed class _CrlClientOnline_151 : CrlClientOnline { + public _CrlClientOnline_151() { } protected internal override Stream GetCrlResponse(IX509Certificate cert, Uri url) { diff --git a/itext.tests/itext.sign.tests/itext/signatures/sign/EncryptedSigningTest.cs b/itext.tests/itext.sign.tests/itext/signatures/sign/EncryptedSigningTest.cs index 7d02dfa27e..05838de718 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/sign/EncryptedSigningTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/sign/EncryptedSigningTest.cs @@ -26,6 +26,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Cert; using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Utils; +using iText.Kernel.Crypto; using iText.Kernel.Logs; using iText.Kernel.Pdf; using iText.Signatures; @@ -75,7 +76,8 @@ public virtual void SignEncryptedPdfTest() { PdfReader reader = new PdfReader(srcFile, new ReaderProperties().SetPassword(ownerPass)); PdfSigner signer = new PdfSigner(reader, FileUtil.GetFileOutputStream(outPdf), new StampingProperties().UseAppendMode ()); - signer.SetFieldName(fieldName); + SignerProperties signerProperties = new SignerProperties().SetFieldName(fieldName); + signer.SetSignerProperties(signerProperties); // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES diff --git a/itext.tests/itext.sign.tests/itext/signatures/sign/IsoSignatureExtensionsRoundtripTest.cs b/itext.tests/itext.sign.tests/itext/signatures/sign/IsoSignatureExtensionsRoundtripTest.cs index fbc548db63..a5d964ada2 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/sign/IsoSignatureExtensionsRoundtripTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/sign/IsoSignatureExtensionsRoundtripTest.cs @@ -26,12 +26,13 @@ You should have received a copy of the GNU Affero General Public License using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X9; using iText.Bouncycastleconnector; -using iText.Bouncycastlefips.Security; using iText.Commons.Bouncycastle; using iText.Commons.Bouncycastle.Cert; using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Bouncycastle.Security; using iText.Commons.Utils; +using iText.Forms.Form.Element; +using iText.Kernel.Crypto; using iText.Kernel.Exceptions; using iText.Kernel.Geom; using iText.Kernel.Pdf; @@ -138,18 +139,12 @@ public virtual void TestNistP256WithSha3_256() { public virtual void TestRsaWithSha3_512() { // For now we use a generic OID, but NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_512 would // be more appropriate - DoRoundTrip("rsa", DigestAlgorithms.SHA3_512, new DerObjectIdentifier(SecurityIDs.ID_RSA_WITH_SHA3_512)); + DoRoundTrip("rsa", DigestAlgorithms.SHA3_512, new DerObjectIdentifier(OID.RSA_WITH_SHA3_512)); } [NUnit.Framework.Test] - public virtual void TestRsaSsaPssWithSha3_256() - { - if ("BC".Equals(BOUNCY_CASTLE_FACTORY.GetProviderName())) { - DoRoundTrip("rsa", DigestAlgorithms.SHA3_256, "RSASSA-PSS", new DerObjectIdentifier(SecurityIDs.ID_RSASSA_PSS)); - } else { - // Signer RSASSA-PSS not recognised in BCFIPS mode - NUnit.Framework.Assert.Catch(typeof(PdfException), () => DoRoundTrip("rsa", DigestAlgorithms.SHA3_256, "RSASSA-PSS", new DerObjectIdentifier(SecurityIDs.ID_RSASSA_PSS))); - } + public virtual void TestRsaSsaPssWithSha3_256() { + DoRoundTrip("rsa", DigestAlgorithms.SHA3_256, "RSASSA-PSS", new DerObjectIdentifier(OID.RSASSA_PSS)); } [NUnit.Framework.Test] @@ -246,14 +241,17 @@ public virtual void TestIsoExtensionsWithMultipleSignatures() { IPrivateKey signPrivateKey = ReadUnencryptedPrivateKey(System.IO.Path.Combine(SOURCE_FOLDER, keySample1 + ".key.pem")); IExternalSignature pks = new PrivateKeySignature(signPrivateKey, DigestAlgorithms.SHA3_256); PdfSigner signer = new PdfSigner(new PdfReader(in1), baos1, new StampingProperties()); - signer.SetFieldName("Signature1"); + SignerProperties signerProperties = new SignerProperties().SetFieldName("Signature1"); + signer.SetSignerProperties(signerProperties); + signer.SignDetached(new BouncyCastleDigest(), pks, signChain1, null, null, null, 0, PdfSigner.CryptoStandard.CMS); } using (Stream in2 = new MemoryStream(baos1.ToArray())) { IPrivateKey signPrivateKey = ReadUnencryptedPrivateKey(System.IO.Path.Combine(SOURCE_FOLDER, keySample2 + ".key.pem")); IExternalSignature pks = new PrivateKeySignature(signPrivateKey, DigestAlgorithms.SHA512); PdfSigner signer = new PdfSigner(new PdfReader(in2), baos2, new StampingProperties()); - signer.SetFieldName("Signature2"); + SignerProperties signerProperties = new SignerProperties().SetFieldName("Signature2"); + signer.SetSignerProperties(signerProperties); signer.SignDetached(new BouncyCastleDigest(), pks, signChain2, null, null, null, 0, PdfSigner.CryptoStandard.CMS); } CheckIsoExtensions(baos2.ToArray(), JavaUtil.ArraysAsList(32001, 32002)); @@ -294,9 +292,13 @@ private void DoSign(String keySampleName, String digestAlgo, String signatureAlg // and accessing that information requires APIs that are not available in older JDKs we still support. IExternalSignature pks = new PrivateKeySignature(signPrivateKey, digestAlgo, signatureAlgo, null); PdfSigner signer = new PdfSigner(new PdfReader(SOURCE_FILE), os, new StampingProperties()); - signer.SetFieldName(SIGNATURE_FIELD); - signer.GetSignatureAppearance().SetPageRect(new Rectangle(50, 650, 200, 100)).SetReason("Test").SetLocation - ("TestCity").SetLayer2Text("Approval test signature.\nCreated by iText."); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID) + .SetContent("Approval test signature.\nCreated by iText."); + SignerProperties signerProperties = new SignerProperties() + .SetFieldName(SIGNATURE_FIELD) + .SetPageRect(new Rectangle(50, 650, 200, 100)) + .SetReason("Test").SetLocation("TestCity").SetSignatureAppearance(appearance); + signer.SetSignerProperties(signerProperties); signer.SignDetached(new BouncyCastleDigest(), pks, signChain, null, null, null, 0, PdfSigner.CryptoStandard.CMS); } diff --git a/itext.tests/itext.sign.tests/itext/signatures/sign/LtvSigTest.cs b/itext.tests/itext.sign.tests/itext/signatures/sign/LtvSigTest.cs index fd0072b4b0..190c01891c 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/sign/LtvSigTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/sign/LtvSigTest.cs @@ -27,6 +27,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Cert; using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Utils; +using iText.Kernel.Crypto; using iText.Kernel.Pdf; using iText.Signatures; using iText.Signatures.Testutils; @@ -103,7 +104,7 @@ public virtual void LtvEnabledSingleSignatureNoCrlDataTest() { )); PdfSigner signer = new PdfSigner(new PdfReader(srcFileName), FileUtil.GetFileOutputStream(ltvFileName), new StampingProperties()); - signer.SetFieldName("Signature1"); + signer.SetSignerProperties(new SignerProperties().SetFieldName("Signature1")); signer.SignDetached(new BouncyCastleDigest(), pks, signChain, crlNotAvailableList, testOcspClient, testTsa, 0, PdfSigner.CryptoStandard .CADES); NUnit.Framework.Assert.IsNull(SignaturesCompareTool.CompareSignatures(ltvFileName, compareFile)); @@ -137,7 +138,7 @@ public virtual void LtvEnabledSingleSignatureNoOcspDataTest() { TestCrlClient testCrlClient = PrepareCrlClientForIssuer(caCertP12FileName, intermediateCertP12FileName); PdfSigner signer = new PdfSigner(new PdfReader(srcFileName), FileUtil.GetFileOutputStream(ltvFileName), new StampingProperties()); - signer.SetFieldName("Signature1"); + signer.SetSignerProperties(new SignerProperties().SetFieldName("Signature1")); signer.SignDetached(new BouncyCastleDigest(), pks, signChain, JavaCollectionsUtil.SingletonList(testCrlClient), null, testTsa , 0, PdfSigner.CryptoStandard.CADES); NUnit.Framework.Assert.IsNull(SignaturesCompareTool.CompareSignatures(ltvFileName, compareFile)); diff --git a/itext.tests/itext.sign.tests/itext/signatures/sign/PadesSigTest.cs b/itext.tests/itext.sign.tests/itext/signatures/sign/PadesSigTest.cs index e8079c33cf..80b77e44d3 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/sign/PadesSigTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/sign/PadesSigTest.cs @@ -29,6 +29,8 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Cert; using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Utils; +using iText.Forms.Form.Element; +using iText.Kernel.Crypto; using iText.Kernel.Geom; using iText.Kernel.Pdf; using iText.Signatures; @@ -141,9 +143,12 @@ private void SignApproval(String signCertFileName, String outFileName, ISignatur IExternalSignature pks = new PrivateKeySignature(signPrivateKey, DigestAlgorithms.SHA256); PdfSigner signer = new PdfSigner(new PdfReader(srcFileName), FileUtil.GetFileOutputStream(outFileName), new StampingProperties()); - signer.SetFieldName("Signature1"); - signer.GetSignatureAppearance().SetPageRect(new Rectangle(50, 650, 200, 100)).SetReason("Test").SetLocation - ("TestCity").SetLayer2Text("Approval test signature.\nCreated by iText."); + SignerProperties signerProperties = new SignerProperties().SetFieldName("Signature1"); + signer.SetSignerProperties(signerProperties); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent + ("Approval test signature.\nCreated by iText."); + signerProperties.SetPageRect(new Rectangle(50, 650, 200, 100)).SetReason("Test").SetLocation("TestCity").SetSignatureAppearance + (appearance); if (sigPolicyIdentifier != null) { signer.SignDetached(pks, signChain, null, null, null, 0, PdfSigner.CryptoStandard.CADES, sigPolicyIdentifier ); diff --git a/itext.tests/itext.sign.tests/itext/signatures/sign/PadesSignatureLevelTest.cs b/itext.tests/itext.sign.tests/itext/signatures/sign/PadesSignatureLevelTest.cs index bf64ab3ecb..2d9a40b2b7 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/sign/PadesSignatureLevelTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/sign/PadesSignatureLevelTest.cs @@ -21,14 +21,14 @@ You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ using System; -using System.IO; using iText.Bouncycastleconnector; using iText.Commons.Bouncycastle.Cert; using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Utils; +using iText.Forms.Form.Element; +using iText.Kernel.Crypto; using iText.Kernel.Geom; using iText.Kernel.Pdf; -using iText.Signatures; using iText.Signatures.Testutils; using iText.Signatures.Testutils.Client; using iText.Test; @@ -73,9 +73,13 @@ public virtual void PadesSignatureLevelTTest01() { IPrivateKey tsaPrivateKey = PemFileHelper.ReadFirstKey(tsaCertFileName, password); PdfSigner signer = new PdfSigner(new PdfReader(srcFileName), FileUtil.GetFileOutputStream(outFileName), new StampingProperties()); - signer.SetFieldName("Signature1"); - signer.GetSignatureAppearance().SetPageRect(new Rectangle(50, 650, 200, 100)).SetReason("Test").SetLocation - ("TestCity").SetLayer2Text("Approval test signature.\nCreated by iText."); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID) + .SetContent("Approval test signature.\nCreated by iText."); + SignerProperties signerProperties = new SignerProperties() + .SetFieldName("Signature1") + .SetPageRect(new Rectangle(50, 650, 200, 100)) + .SetReason("Test").SetLocation("TestCity").SetSignatureAppearance(appearance); + signer.SetSignerProperties(signerProperties); TestTsaClient testTsa = new TestTsaClient(JavaUtil.ArraysAsList(tsaChain), tsaPrivateKey); signer.SignDetached(new BouncyCastleDigest(), pks, signRsaChain, null, null, testTsa, 0, PdfSigner.CryptoStandard.CADES); TestSignUtils.BasicCheckSignedDoc(destinationFolder + "padesSignatureLevelTTest01.pdf", "Signature1"); diff --git a/itext.tests/itext.sign.tests/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest.cs b/itext.tests/itext.sign.tests/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest.cs index 6b6374329f..b638786603 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest.cs @@ -33,6 +33,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Security; using iText.Commons.Utils; using iText.Forms.Form.Element; +using iText.Kernel.Crypto; using iText.Kernel.Geom; using iText.Kernel.Pdf; using iText.Signatures; @@ -313,7 +314,7 @@ public virtual void TwoStepSigningBaselineLTATest() { private SignerProperties CreateSignerProperties() { SignerProperties signerProperties = new SignerProperties(); signerProperties.SetFieldName("Signature1"); - SignatureFieldAppearance appearance = new SignatureFieldAppearance(signerProperties.GetFieldName()).SetContent + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent ("Approval test signature.\nCreated by iText."); signerProperties.SetPageRect(new Rectangle(50, 650, 200, 100)).SetSignatureAppearance(appearance); return signerProperties; diff --git a/itext.tests/itext.sign.tests/itext/signatures/sign/PadesTwoPhaseSigningTest.cs b/itext.tests/itext.sign.tests/itext/signatures/sign/PadesTwoPhaseSigningTest.cs index ccc545b0c1..f9d4aba8e6 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/sign/PadesTwoPhaseSigningTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/sign/PadesTwoPhaseSigningTest.cs @@ -28,6 +28,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Utils; using iText.Forms.Form.Element; +using iText.Kernel.Crypto; using iText.Kernel.Exceptions; using iText.Kernel.Geom; using iText.Kernel.Pdf; @@ -125,7 +126,7 @@ public virtual void MissingTimestampClientTest() { private SignerProperties CreateSignerProperties() { SignerProperties signerProperties = new SignerProperties(); signerProperties.SetFieldName("Signature1"); - SignatureFieldAppearance appearance = new SignatureFieldAppearance(signerProperties.GetFieldName()).SetContent + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent ("Approval test signature.\nCreated by iText."); signerProperties.SetPageRect(new Rectangle(50, 650, 200, 100)).SetSignatureAppearance(appearance); return signerProperties; diff --git a/itext.tests/itext.sign.tests/itext/signatures/sign/Pdf20SigningTest.cs b/itext.tests/itext.sign.tests/itext/signatures/sign/Pdf20SigningTest.cs index 7a5f427559..b03d1f3786 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/sign/Pdf20SigningTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/sign/Pdf20SigningTest.cs @@ -27,6 +27,9 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Cert; using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Utils; +using iText.Forms.Fields.Properties; +using iText.Forms.Form.Element; +using iText.Kernel.Crypto; using iText.Kernel.Exceptions; using iText.Kernel.Geom; using iText.Kernel.Pdf; @@ -35,6 +38,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Signatures.Exceptions; using iText.Signatures.Testutils; using iText.Test; +using iText.Test.Attributes; namespace iText.Signatures.Sign { [NUnit.Framework.Category("BouncyCastleIntegrationTest")] @@ -72,8 +76,8 @@ public virtual void SignExistingFieldWhenDirectAcroformAndNoSigFlagTest() { String srcFile = SOURCE_FOLDER + "signExistingFieldWhenDirectAcroformAndNoSigFlag.pdf"; String outPdf = DESTINATION_FOLDER + "signExistingFieldWhenDirectAcroformAndNoSigFlag.pdf"; String fieldName = "Signature1"; - Sign(srcFile, fieldName, outPdf, chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CADES, PdfSigner - .NOT_CERTIFIED); + Sign(srcFile, fieldName, outPdf, chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CADES, AccessPermissions + .UNSPECIFIED); PdfDocument doc = new PdfDocument(new PdfReader(outPdf)); PdfNumber sigFlag = doc.GetCatalog().GetPdfObject().GetAsDictionary(PdfName.AcroForm).GetAsNumber(PdfName. SigFlags); @@ -81,6 +85,7 @@ public virtual void SignExistingFieldWhenDirectAcroformAndNoSigFlagTest() { } [NUnit.Framework.Test] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.EXISTING_TAG_STRUCTURE_ROOT_IS_NOT_STANDARD)] public virtual void SignPdf2CertificationAfterApprovalTest() { String srcFile = SOURCE_FOLDER + "approvalSignedDocPdf2.pdf"; String outPdf = DESTINATION_FOLDER + "signedPdf2CertificationAfterApproval.pdf"; @@ -88,7 +93,7 @@ public virtual void SignPdf2CertificationAfterApprovalTest() { String fieldName = "Signature2"; Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => Sign(srcFile, fieldName, outPdf, chain , pk, DigestAlgorithms.RIPEMD160, PdfSigner.CryptoStandard.CADES, "Test 1", "TestCity", rect, false, true - , PdfSigner.CERTIFIED_NO_CHANGES_ALLOWED, null)); + , AccessPermissions.NO_CHANGES_PERMITTED, null)); NUnit.Framework.Assert.AreEqual(SignExceptionMessageConstant.CERTIFICATION_SIGNATURE_CREATION_FAILED_DOC_SHALL_NOT_CONTAIN_SIGS , e.Message); } @@ -129,7 +134,7 @@ public virtual void SignPdf2CmsTest() { Rectangle rect = new Rectangle(30, 200, 200, 100); String fieldName = "Signature1"; Sign(srcFile, fieldName, outPdf, chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS, "Test 1" - , "TestCity", rect, false, true, PdfSigner.NOT_CERTIFIED, 12f); + , "TestCity", rect, false, true, AccessPermissions.UNSPECIFIED, 12f); NUnit.Framework.Assert.IsNull(new CompareTool().CompareVisually(outPdf, cmpPdf, DESTINATION_FOLDER, "diff_" , GetTestMap(rect))); NUnit.Framework.Assert.IsNull(SignaturesCompareTool.CompareSignatures(outPdf, cmpPdf)); @@ -143,20 +148,21 @@ public virtual void SignPdf2CadesTest() { Rectangle rect = new Rectangle(30, 200, 200, 100); String fieldName = "Signature1"; Sign(srcFile, fieldName, outPdf, chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CADES, "Test 1" - , "TestCity", rect, false, true, PdfSigner.NOT_CERTIFIED, 12f); + , "TestCity", rect, false, true, AccessPermissions.UNSPECIFIED, 12f); NUnit.Framework.Assert.IsNull(new CompareTool().CompareVisually(outPdf, cmpPdf, DESTINATION_FOLDER, "diff_" , GetTestMap(rect))); NUnit.Framework.Assert.IsNull(SignaturesCompareTool.CompareSignatures(outPdf, cmpPdf)); } protected internal virtual void Sign(String src, String name, String dest, IX509Certificate[] chain, IPrivateKey - pk, String digestAlgorithm, PdfSigner.CryptoStandard subfilter, int certificationLevel) { + pk, String digestAlgorithm, PdfSigner.CryptoStandard subfilter, AccessPermissions certificationLevel) { PdfReader reader = new PdfReader(src); StampingProperties properties = new StampingProperties(); properties.UseAppendMode(); PdfSigner signer = new PdfSigner(reader, FileUtil.GetFileOutputStream(dest), properties); - signer.SetCertificationLevel(certificationLevel); - signer.SetFieldName(name); + SignerProperties signerProperties = new SignerProperties().SetCertificationLevel(certificationLevel).SetFieldName + (name); + signer.SetSignerProperties(signerProperties); // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm); signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, subfilter); @@ -164,25 +170,27 @@ protected internal virtual void Sign(String src, String name, String dest, IX509 protected internal virtual void Sign(String src, String name, String dest, IX509Certificate[] chain, IPrivateKey pk, String digestAlgorithm, PdfSigner.CryptoStandard subfilter, String reason, String location, Rectangle - rectangleForNewField, bool setReuseAppearance, bool isAppendMode, int certificationLevel, float? fontSize - ) { + rectangleForNewField, bool setReuseAppearance, bool isAppendMode, AccessPermissions certificationLevel + , float? fontSize) { PdfReader reader = new PdfReader(src); StampingProperties properties = new StampingProperties(); if (isAppendMode) { properties.UseAppendMode(); } PdfSigner signer = new PdfSigner(reader, FileUtil.GetFileOutputStream(dest), properties); - signer.SetCertificationLevel(certificationLevel); - signer.SetFieldName(name); + SignerProperties signerProperties = new SignerProperties().SetCertificationLevel(certificationLevel).SetFieldName + (name).SetReason(reason).SetLocation(location); // Creating the appearance - PdfSignatureAppearance appearance = signer.GetSignatureAppearance().SetReason(reason).SetLocation(location - ).SetReuseAppearance(setReuseAppearance); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent + (new SignedAppearanceText()); if (rectangleForNewField != null) { - signer.SetPageRect(rectangleForNewField); + signerProperties.SetPageRect(rectangleForNewField); } if (fontSize != null) { - appearance.SetLayer2FontSize((float)fontSize); + appearance.SetFontSize((float)fontSize); } + signer.SetSignerProperties(signerProperties); + signer.GetSignatureField().SetReuseAppearance(setReuseAppearance); // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm); signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, subfilter); @@ -192,7 +200,7 @@ protected internal virtual void Sign(String src, String name, String dest, IX509 pk, String digestAlgorithm, PdfSigner.CryptoStandard subfilter, String reason, String location, Rectangle rectangleForNewField, bool setReuseAppearance, bool isAppendMode) { Sign(src, name, dest, chain, pk, digestAlgorithm, subfilter, reason, location, rectangleForNewField, setReuseAppearance - , isAppendMode, PdfSigner.NOT_CERTIFIED, null); + , isAppendMode, AccessPermissions.UNSPECIFIED, null); } private static IDictionary> GetTestMap(Rectangle ignoredArea) { diff --git a/itext.tests/itext.sign.tests/itext/signatures/sign/PdfASigningTest.cs b/itext.tests/itext.sign.tests/itext/signatures/sign/PdfASigningTest.cs index 1e18aa3ada..ea7bb24f2a 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/sign/PdfASigningTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/sign/PdfASigningTest.cs @@ -26,6 +26,9 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Utils; using iText.Forms; +using iText.Forms.Fields.Properties; +using iText.Forms.Form.Element; +using iText.Kernel.Crypto; using iText.Kernel.Font; using iText.Kernel.Geom; using iText.Kernel.Pdf; @@ -81,7 +84,7 @@ public virtual void SimpleSigningTest() { Rectangle rect = new Rectangle(x, y, w, h); String fieldName = "Signature1"; Sign(src, fieldName, dest, chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CADES, "Test 1", "TestCity" - , rect, false, false, PdfSigner.NOT_CERTIFIED, 12f); + , rect, false, false, AccessPermissions.UNSPECIFIED, 12f); NUnit.Framework.Assert.IsNull(new VeraPdfValidator().Validate(dest)); // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf\a validation on Android) NUnit.Framework.Assert.IsNull(SignaturesCompareTool.CompareSignatures(dest, sourceFolder + "cmp_" + fileName @@ -96,8 +99,9 @@ public virtual void SigningPdfA2DocumentTest() { String @out = destinationFolder + "signedPdfA2Document.pdf"; PdfReader reader = new PdfReader(FileUtil.GetInputStreamForFile(src)); PdfSigner signer = new PdfSigner(reader, FileUtil.GetFileOutputStream(@out), new StampingProperties()); - signer.SetFieldLockDict(new PdfSigFieldLock()); - signer.SetCertificationLevel(PdfSigner.CERTIFIED_NO_CHANGES_ALLOWED); + SignerProperties signerProperties = new SignerProperties().SetFieldLockDict(new PdfSigFieldLock()).SetCertificationLevel + (AccessPermissions.NO_CHANGES_PERMITTED); + signer.SetSignerProperties(signerProperties); IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES ); @@ -113,7 +117,7 @@ public virtual void SignPdf2CmsTest() { String fieldName = "Signature1"; Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => Sign(srcFile, fieldName , outPdf, chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS, "Test 1", "TestCity", rect - , false, true, PdfSigner.NOT_CERTIFIED, 12f)); + , false, true, AccessPermissions.UNSPECIFIED, 12f)); NUnit.Framework.Assert.AreEqual(PdfaExceptionMessageConstant.SIGNATURE_SHALL_CONFORM_TO_ONE_OF_THE_PADES_PROFILE , e.Message); } @@ -126,7 +130,7 @@ public virtual void SignPdf2CadesTest() { Rectangle rect = new Rectangle(30, 200, 200, 100); String fieldName = "Signature1"; Sign(srcFile, fieldName, outPdf, chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CADES, "Test 1" - , "TestCity", rect, false, true, PdfSigner.NOT_CERTIFIED, 12f); + , "TestCity", rect, false, true, AccessPermissions.UNSPECIFIED, 12f); NUnit.Framework.Assert.IsNull(new CompareTool().CompareVisually(outPdf, cmpPdf, destinationFolder, "diff_" , GetTestMap(rect))); NUnit.Framework.Assert.IsNull(SignaturesCompareTool.CompareSignatures(outPdf, cmpPdf)); @@ -140,8 +144,9 @@ public virtual void FailedSigningPdfA2DocumentTest() { String @out = destinationFolder + "signedPdfADocument2.pdf"; PdfReader reader = new PdfReader(FileUtil.GetInputStreamForFile(src)); PdfSigner signer = new PdfSigner(reader, FileUtil.GetFileOutputStream(@out), new StampingProperties()); - signer.SetFieldLockDict(new PdfSigFieldLock()); - signer.SetCertificationLevel(PdfSigner.NOT_CERTIFIED); + SignerProperties signerProperties = new SignerProperties().SetFieldLockDict(new PdfSigFieldLock()).SetCertificationLevel + (AccessPermissions.UNSPECIFIED); + signer.SetSignerProperties(signerProperties); int x = 36; int y = 548; int w = 200; @@ -149,8 +154,11 @@ public virtual void FailedSigningPdfA2DocumentTest() { Rectangle rect = new Rectangle(x, y, w, h); PdfFont font = PdfFontFactory.CreateFont("Helvetica", "WinAnsi", PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED ); - signer.SetPageRect(rect).GetSignatureAppearance().SetReason("pdfA test").SetLocation("TestCity").SetLayer2Font - (font).SetReuseAppearance(false); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent + (new SignedAppearanceText()).SetFont(font); + signerProperties.SetPageRect(rect).SetReason("pdfA test").SetLocation("TestCity").SetSignatureAppearance(appearance + ); + signer.GetSignatureField().SetReuseAppearance(false); IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES)); @@ -162,32 +170,36 @@ protected internal virtual void Sign(String src, String name, String dest, IX509 pk, String digestAlgorithm, PdfSigner.CryptoStandard subfilter, String reason, String location, Rectangle rectangleForNewField, bool setReuseAppearance, bool isAppendMode) { Sign(src, name, dest, chain, pk, digestAlgorithm, subfilter, reason, location, rectangleForNewField, setReuseAppearance - , isAppendMode, PdfSigner.NOT_CERTIFIED, null); + , isAppendMode, AccessPermissions.UNSPECIFIED, null); } protected internal virtual void Sign(String src, String name, String dest, IX509Certificate[] chain, IPrivateKey pk, String digestAlgorithm, PdfSigner.CryptoStandard subfilter, String reason, String location, Rectangle - rectangleForNewField, bool setReuseAppearance, bool isAppendMode, int certificationLevel, float? fontSize - ) { + rectangleForNewField, bool setReuseAppearance, bool isAppendMode, AccessPermissions certificationLevel + , float? fontSize) { PdfReader reader = new PdfReader(src); StampingProperties properties = new StampingProperties(); if (isAppendMode) { properties.UseAppendMode(); } PdfSigner signer = new PdfSigner(reader, FileUtil.GetFileOutputStream(dest), properties); - signer.SetCertificationLevel(certificationLevel); + SignerProperties signerProperties = new SignerProperties().SetCertificationLevel(certificationLevel).SetFieldName + (name); + signer.SetSignerProperties(signerProperties); PdfFont font = PdfFontFactory.CreateFont(FONT, "WinAnsi", PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED ); - signer.SetFieldName(name); // Creating the appearance - PdfSignatureAppearance appearance = signer.GetSignatureAppearance().SetReason(reason).SetLocation(location - ).SetLayer2Font(font).SetReuseAppearance(setReuseAppearance); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent + (new SignedAppearanceText()); + appearance.SetFont(font); + signerProperties.SetReason(reason).SetLocation(location).SetSignatureAppearance(appearance); if (rectangleForNewField != null) { - signer.SetPageRect(rectangleForNewField); + signerProperties.SetPageRect(rectangleForNewField); } if (fontSize != null) { - appearance.SetLayer2FontSize((float)fontSize); + appearance.SetFontSize((float)fontSize); } + signer.GetSignatureField().SetReuseAppearance(setReuseAppearance); // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm); signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, subfilter); diff --git a/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesAdvancedTest.cs b/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesAdvancedTest.cs index 25e0140988..3a1d2e864c 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesAdvancedTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesAdvancedTest.cs @@ -23,13 +23,13 @@ You should have received a copy of the GNU Affero General Public License using System; using System.Collections.Generic; using System.IO; -using System.Linq; using iText.Bouncycastleconnector; using iText.Commons.Bouncycastle; using iText.Commons.Bouncycastle.Cert; using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Utils; using iText.Forms.Form.Element; +using iText.Kernel.Crypto; using iText.Kernel.Exceptions; using iText.Kernel.Geom; using iText.Kernel.Pdf; @@ -42,7 +42,6 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Signatures.Sign { [NUnit.Framework.Category("BouncyCastleIntegrationTest")] - [NUnit.Framework.TestFixtureSource("CreateParametersTestFixtureData")] public class PdfPadesAdvancedTest : ExtendedITextTest { private static readonly IBouncyCastleFactory FACTORY = BouncyCastleFactoryCreator.GetFactory(); @@ -57,44 +56,11 @@ public class PdfPadesAdvancedTest : ExtendedITextTest { private static readonly char[] PASSWORD = "testpassphrase".ToCharArray(); - private readonly String signingCertName; - - private readonly String rootCertName; - - private readonly bool? isOcspRevoked; - - private readonly String cmpFilePostfix; - - private readonly int? amountOfCrlsForSign; - - private readonly int? amountOfOcspsForSign; - - private readonly int? amountOfCrlsForRoot; - - private readonly int? amountOfOcspsForRoot; - [NUnit.Framework.OneTimeSetUp] public static void Before() { CreateOrClearDestinationFolder(DESTINATION_FOLDER); } - public PdfPadesAdvancedTest(Object signingCertName, Object rootCertName, Object isOcspRevoked, Object cmpFilePostfix - , Object amountOfCrlsForSign, Object amountOfOcspsForSign, Object amountOfCrlsForRoot, Object amountOfOcspsForRoot - ) { - this.signingCertName = (String)signingCertName; - this.rootCertName = (String)rootCertName; - this.isOcspRevoked = (bool?)isOcspRevoked; - this.cmpFilePostfix = (String)cmpFilePostfix; - this.amountOfCrlsForSign = (int?)amountOfCrlsForSign; - this.amountOfOcspsForSign = (int?)amountOfOcspsForSign; - this.amountOfCrlsForRoot = (int?)amountOfCrlsForRoot; - this.amountOfOcspsForRoot = (int?)amountOfOcspsForRoot; - } - - public PdfPadesAdvancedTest(Object[] array) - : this(array[0], array[1], array[2], array[3], array[4], array[5], array[6], array[7]) { - } - public static IEnumerable CreateParameters() { IList parameters = new List(); parameters.AddAll(CreateParametersUsingRootName("rootCertNoCrlNoOcsp", 0, 0)); @@ -104,10 +70,6 @@ public static IEnumerable CreateParameters() { return parameters; } - public static ICollection CreateParametersTestFixtureData() { - return CreateParameters().Select(array => new NUnit.Framework.TestFixtureData(array)).ToList(); - } - private static IList CreateParametersUsingRootName(String rootCertName, int crlsForRoot, int ocspForRoot ) { return JavaUtil.ArraysAsList(new Object[] { "signCertCrlOcsp.pem", rootCertName + ".pem", false, "_signCertCrlOcsp_" @@ -121,8 +83,10 @@ private static IList CreateParametersUsingRootName(String rootCertName + rootCertName, 1, 0, crlsForRoot, ocspForRoot }); } - [NUnit.Framework.Test] - public virtual void SignWithAdvancedClientsTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void SignWithAdvancedClientsTest(String signingCertName, String rootCertName, bool? isOcspRevoked + , String cmpFilePostfix, int? amountOfCrlsForSign, int? amountOfOcspsForSign, int? amountOfCrlsForRoot + , int? amountOfOcspsForRoot) { String srcFileName = SOURCE_FOLDER + "helloWorldDoc.pdf"; String signCertFileName = CERTS_SRC + signingCertName; String rootCertFileName = CERTS_SRC + rootCertName; @@ -134,7 +98,7 @@ public virtual void SignWithAdvancedClientsTest() { IX509Certificate[] tsaChain = PemFileHelper.ReadFirstChain(tsaCertFileName); IPrivateKey tsaPrivateKey = PemFileHelper.ReadFirstKey(tsaCertFileName, PASSWORD); TestTsaClient testTsa = new TestTsaClient(JavaUtil.ArraysAsList(tsaChain), tsaPrivateKey); - AdvancedTestOcspClient testOcspClient = new AdvancedTestOcspClient(null); + AdvancedTestOcspClient testOcspClient = new AdvancedTestOcspClient(); TestOcspResponseBuilder ocspBuilderMainCert = new TestOcspResponseBuilder(rootCert, rootPrivateKey); if ((bool)isOcspRevoked) { ocspBuilderMainCert.SetCertificateStatus(FACTORY.CreateRevokedStatus(TimeTestUtil.TEST_DATE_TIME, FACTORY. @@ -175,12 +139,13 @@ public virtual void SignWithAdvancedClientsTest() { padesSigner.SignWithBaselineLTAProfile(signerProperties, signRsaChain, pks, testTsa); TestSignUtils.BasicCheckSignedDoc(new MemoryStream(outputStream.ToArray()), "Signature1"); AssertDss(outputStream, rootCert, signRsaCert, (IX509Certificate)tsaChain[0], (IX509Certificate)tsaChain[1 - ]); + ], amountOfCrlsForRoot, amountOfCrlsForSign, amountOfOcspsForRoot, amountOfOcspsForSign); } } private void AssertDss(MemoryStream outputStream, IX509Certificate rootCert, IX509Certificate signRsaCert, - IX509Certificate tsaCert, IX509Certificate rootTsaCert) { + IX509Certificate tsaCert, IX509Certificate rootTsaCert, int? amountOfCrlsForRoot, int? amountOfCrlsForSign + , int? amountOfOcspsForRoot, int? amountOfOcspsForSign) { IDictionary expectedNumberOfCrls = new Dictionary(); if (amountOfCrlsForRoot + amountOfCrlsForSign != 0) { expectedNumberOfCrls.Put(rootCert.GetSubjectDN().ToString(), amountOfCrlsForRoot + amountOfCrlsForSign); @@ -202,7 +167,7 @@ private String GetCertName(IX509Certificate certificate) { private SignerProperties CreateSignerProperties() { SignerProperties signerProperties = new SignerProperties(); signerProperties.SetFieldName("Signature1"); - SignatureFieldAppearance appearance = new SignatureFieldAppearance(signerProperties.GetFieldName()).SetContent + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent ("Approval test signature.\nCreated by iText."); signerProperties.SetPageRect(new Rectangle(50, 650, 200, 100)).SetSignatureAppearance(appearance); return signerProperties; diff --git a/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesMissingCertificatesTest.cs b/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesMissingCertificatesTest.cs index 032101399c..203d806d57 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesMissingCertificatesTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesMissingCertificatesTest.cs @@ -83,7 +83,7 @@ public virtual void RetrieveMissingCertificatesTest() { IPrivateKey tsaPrivateKey = PemFileHelper.ReadFirstKey(tsaCertFileName, password); SignerProperties signerProperties = CreateSignerProperties(); TestTsaClient testTsa = new TestTsaClient(JavaCollectionsUtil.SingletonList(tsaCert), tsaPrivateKey); - CrlClientOnline testCrlClient = new _CrlClientOnline_111(crlSignedByCrlCert, crlSignedByCA); + CrlClientOnline testCrlClient = new _CrlClientOnline_110(crlSignedByCrlCert, crlSignedByCA); IX509Certificate rootCert = (IX509Certificate)PemFileHelper.ReadFirstChain(rootCertFileName)[0]; IX509Certificate crlRootCert = (IX509Certificate)PemFileHelper.ReadFirstChain(rootCrlFileName)[0]; IX509Certificate ocspRootCert = (IX509Certificate)PemFileHelper.ReadFirstChain(rootOcspFileName)[0]; @@ -96,7 +96,7 @@ public virtual void RetrieveMissingCertificatesTest() { )[0]; IX509Certificate intermediateCert = (IX509Certificate)PemFileHelper.ReadFirstChain(intermediateCertFileName )[0]; - AdvancedTestOcspClient ocspClient = new AdvancedTestOcspClient(null); + AdvancedTestOcspClient ocspClient = new AdvancedTestOcspClient(); ocspClient.AddBuilderForCertIssuer(signCert, ocspCert, ocspPrivateKey); ocspClient.AddBuilderForCertIssuer(ocspIntermediateCert, ocspCert, ocspPrivateKey); ocspClient.AddBuilderForCertIssuer(crlIntermediateCert, ocspCert, ocspPrivateKey); @@ -110,7 +110,7 @@ public virtual void RetrieveMissingCertificatesTest() { , outputStream); padesSigner.SetCrlClient(testCrlClient); padesSigner.SetOcspClient(ocspClient); - IIssuingCertificateRetriever issuingCertificateRetriever = new _IssuingCertificateRetriever_146(crlCertFileName + IIssuingCertificateRetriever issuingCertificateRetriever = new _IssuingCertificateRetriever_145(crlCertFileName , intermediateCrlFileName, rootCrlFileName, intermediateTsaFileName, rootTsaFileName, intermediateOscpFileName , rootOcspFileName, intermediateCertFileName, rootCertFileName); padesSigner.SetIssuingCertificateRetriever(issuingCertificateRetriever); @@ -133,8 +133,8 @@ public virtual void RetrieveMissingCertificatesTest() { , certs); } - private sealed class _CrlClientOnline_111 : CrlClientOnline { - public _CrlClientOnline_111(String crlSignedByCrlCert, String crlSignedByCA) { + private sealed class _CrlClientOnline_110 : CrlClientOnline { + public _CrlClientOnline_110(String crlSignedByCrlCert, String crlSignedByCA) { this.crlSignedByCrlCert = crlSignedByCrlCert; this.crlSignedByCA = crlSignedByCA; } @@ -151,8 +151,8 @@ protected internal override Stream GetCrlResponse(IX509Certificate cert, Uri url private readonly String crlSignedByCA; } - private sealed class _IssuingCertificateRetriever_146 : IssuingCertificateRetriever { - public _IssuingCertificateRetriever_146(String crlCertFileName, String intermediateCrlFileName, String rootCrlFileName + private sealed class _IssuingCertificateRetriever_145 : IssuingCertificateRetriever { + public _IssuingCertificateRetriever_145(String crlCertFileName, String intermediateCrlFileName, String rootCrlFileName , String intermediateTsaFileName, String rootTsaFileName, String intermediateOscpFileName, String rootOcspFileName , String intermediateCertFileName, String rootCertFileName) { this.crlCertFileName = crlCertFileName; @@ -230,7 +230,7 @@ public virtual void RetrieveMissingCertificatesUsingTrustedStoreTest() { IPrivateKey tsaPrivateKey = PemFileHelper.ReadFirstKey(tsaCertFileName, password); SignerProperties signerProperties = CreateSignerProperties(); TestTsaClient testTsa = new TestTsaClient(JavaCollectionsUtil.SingletonList(tsaCert), tsaPrivateKey); - CrlClientOnline testCrlClient = new _CrlClientOnline_222(crlSignedByCrlCert, crlSignedByCA); + CrlClientOnline testCrlClient = new _CrlClientOnline_221(crlSignedByCrlCert, crlSignedByCA); IX509Certificate rootCert = (IX509Certificate)PemFileHelper.ReadFirstChain(rootCertFileName)[0]; IX509Certificate crlRootCert = (IX509Certificate)PemFileHelper.ReadFirstChain(rootCrlFileName)[0]; MemoryStream outputStream = new MemoryStream(); @@ -257,8 +257,8 @@ public virtual void RetrieveMissingCertificatesUsingTrustedStoreTest() { , certs); } - private sealed class _CrlClientOnline_222 : CrlClientOnline { - public _CrlClientOnline_222(String crlSignedByCrlCert, String crlSignedByCA) { + private sealed class _CrlClientOnline_221 : CrlClientOnline { + public _CrlClientOnline_221(String crlSignedByCrlCert, String crlSignedByCA) { this.crlSignedByCrlCert = crlSignedByCrlCert; this.crlSignedByCA = crlSignedByCA; } @@ -282,7 +282,7 @@ private String GetCertName(IX509Certificate certificate) { private SignerProperties CreateSignerProperties() { SignerProperties signerProperties = new SignerProperties(); signerProperties.SetFieldName("Signature1"); - SignatureFieldAppearance appearance = new SignatureFieldAppearance(signerProperties.GetFieldName()).SetContent + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent ("Approval test signature.\nCreated by iText."); signerProperties.SetPageRect(new Rectangle(50, 650, 200, 100)).SetSignatureAppearance(appearance); return signerProperties; diff --git a/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesSignerLevelsTest.cs b/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesSignerLevelsTest.cs index 7f0f166d7c..4065bd4064 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesSignerLevelsTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesSignerLevelsTest.cs @@ -29,6 +29,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Utils; using iText.Forms.Form.Element; +using iText.Kernel.Crypto; using iText.Kernel.Geom; using iText.Kernel.Pdf; using iText.Signatures.Testutils; @@ -261,7 +262,7 @@ public virtual void ProlongDocumentSignaturesTest() { private SignerProperties CreateSignerProperties() { SignerProperties signerProperties = new SignerProperties(); signerProperties.SetFieldName("Signature1"); - SignatureFieldAppearance appearance = new SignatureFieldAppearance(signerProperties.GetFieldName()) + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID) .SetContent("Approval test signature.\nCreated by iText."); signerProperties.SetPageRect(new Rectangle(50, 650, 200, 100)) .SetSignatureAppearance(appearance); diff --git a/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesSignerLtvExtensionsTest.cs b/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesSignerLtvExtensionsTest.cs index 7b76c622d9..e72d41c7c9 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesSignerLtvExtensionsTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesSignerLtvExtensionsTest.cs @@ -29,6 +29,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Utils; using iText.Forms.Form.Element; +using iText.Kernel.Crypto; using iText.Kernel.Geom; using iText.Kernel.Pdf; using iText.Signatures; @@ -137,7 +138,7 @@ private String GetCertName(IX509Certificate certificate) { private SignerProperties CreateSignerProperties() { SignerProperties signerProperties = new SignerProperties(); signerProperties.SetFieldName("Signature1"); - SignatureFieldAppearance appearance = new SignatureFieldAppearance(signerProperties.GetFieldName()).SetContent + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent ("Approval test signature.\nCreated by iText."); signerProperties.SetPageRect(new Rectangle(50, 650, 200, 100)).SetSignatureAppearance(appearance); return signerProperties; diff --git a/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesSignerTest.cs b/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesSignerTest.cs index 4ee066f9e3..5d38a10410 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesSignerTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesSignerTest.cs @@ -30,6 +30,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Security; using iText.Commons.Utils; using iText.Forms.Form.Element; +using iText.Kernel.Crypto; using iText.Kernel.Exceptions; using iText.Kernel.Geom; using iText.Kernel.Pdf; @@ -237,7 +238,7 @@ public virtual void PadesSignatureEd448Test() { private SignerProperties CreateSignerProperties() { SignerProperties signerProperties = new SignerProperties(); signerProperties.SetFieldName("Signature1"); - SignatureFieldAppearance appearance = new SignatureFieldAppearance(signerProperties.GetFieldName()).SetContent + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent ("Approval test signature.\nCreated by iText."); signerProperties.SetPageRect(new Rectangle(50, 650, 200, 100)).SetSignatureAppearance(appearance); return signerProperties; diff --git a/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesWithCrlCertificateTest.cs b/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesWithCrlCertificateTest.cs index af67845b44..ee5f951f4d 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesWithCrlCertificateTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesWithCrlCertificateTest.cs @@ -73,11 +73,11 @@ public virtual void SignCertWithCrlTest() { IPrivateKey tsaPrivateKey = PemFileHelper.ReadFirstKey(tsaCertFileName, PASSWORD); SignerProperties signerProperties = CreateSignerProperties(); TestTsaClient testTsa = new TestTsaClient(JavaUtil.ArraysAsList(tsaChain), tsaPrivateKey); - CrlClientOnline testCrlClient = new _CrlClientOnline_95(); + CrlClientOnline testCrlClient = new _CrlClientOnline_94(); MemoryStream outputStream = new MemoryStream(); PdfPadesSigner padesSigner = CreatePdfPadesSigner(srcFileName, outputStream); padesSigner.SetCrlClient(testCrlClient); - IIssuingCertificateRetriever issuingCertificateRetriever = new _IssuingCertificateRetriever_108(crlCertFileName + IIssuingCertificateRetriever issuingCertificateRetriever = new _IssuingCertificateRetriever_107(crlCertFileName , rootCrlFileName); padesSigner.SetIssuingCertificateRetriever(issuingCertificateRetriever); IX509Certificate[] signChain = new IX509Certificate[] { signCert, rootCert }; @@ -93,8 +93,8 @@ public virtual void SignCertWithCrlTest() { ); } - private sealed class _CrlClientOnline_95 : CrlClientOnline { - public _CrlClientOnline_95() { + private sealed class _CrlClientOnline_94 : CrlClientOnline { + public _CrlClientOnline_94() { } protected internal override Stream GetCrlResponse(IX509Certificate cert, Uri urlt) { @@ -105,8 +105,8 @@ protected internal override Stream GetCrlResponse(IX509Certificate cert, Uri url } } - private sealed class _IssuingCertificateRetriever_108 : IssuingCertificateRetriever { - public _IssuingCertificateRetriever_108(String crlCertFileName, String rootCrlFileName) { + private sealed class _IssuingCertificateRetriever_107 : IssuingCertificateRetriever { + public _IssuingCertificateRetriever_107(String crlCertFileName, String rootCrlFileName) { this.crlCertFileName = crlCertFileName; this.rootCrlFileName = rootCrlFileName; } @@ -126,7 +126,7 @@ protected internal override Stream GetIssuerCertByURI(String uri) { private SignerProperties CreateSignerProperties() { SignerProperties signerProperties = new SignerProperties(); signerProperties.SetFieldName("Signature1"); - SignatureFieldAppearance appearance = new SignatureFieldAppearance(signerProperties.GetFieldName()).SetContent + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent ("Approval test signature.\nCreated by iText."); signerProperties.SetPageRect(new Rectangle(50, 650, 200, 100)).SetSignatureAppearance(appearance); return signerProperties; diff --git a/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesWithMissingCertTest.cs b/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesWithMissingCertTest.cs index d8265519b7..493d03d291 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesWithMissingCertTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesWithMissingCertTest.cs @@ -23,7 +23,6 @@ You should have received a copy of the GNU Affero General Public License using System; using System.Collections.Generic; using System.IO; -using System.Linq; using iText.Bouncycastleconnector; using iText.Commons.Bouncycastle; using iText.Commons.Bouncycastle.Cert; @@ -40,7 +39,6 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Signatures.Sign { [NUnit.Framework.Category("BouncyCastleIntegrationTest")] - [NUnit.Framework.TestFixtureSource("CreateParametersTestFixtureData")] public class PdfPadesWithMissingCertTest : ExtendedITextTest { private static readonly IBouncyCastleFactory FACTORY = BouncyCastleFactoryCreator.GetFactory(); @@ -55,37 +53,20 @@ public class PdfPadesWithMissingCertTest : ExtendedITextTest { private static readonly char[] PASSWORD = "testpassphrase".ToCharArray(); - private readonly String missingCertName1; - - private readonly String missingCertName2; - [NUnit.Framework.OneTimeSetUp] public static void Before() { CreateOrClearDestinationFolder(destinationFolder); } - public PdfPadesWithMissingCertTest(Object missingCertName1, Object missingCertName2) { - this.missingCertName1 = (String)missingCertName1; - this.missingCertName2 = (String)missingCertName2; - } - - public PdfPadesWithMissingCertTest(Object[] array) - : this(array[0], array[1]) { - } - public static IEnumerable CreateParameters() { return JavaUtil.ArraysAsList(new Object[] { "missing_cert1.cer", "missing_cert2.cer" }, new Object[] { "missing_cert1.crt" , "missing_cert2.crt" }, new Object[] { null, "missing_certs.p7b" }, new Object[] { "not_existing_file" , "not_existing_file" }, new Object[] { "missing_cert1.der", "missing_cert2.der" }); } - public static ICollection CreateParametersTestFixtureData() { - return CreateParameters().Select(array => new NUnit.Framework.TestFixtureData(array)).ToList(); - } - - [NUnit.Framework.Test] + [NUnit.Framework.TestCaseSource("CreateParameters")] [LogMessage(SignLogMessageConstant.UNABLE_TO_PARSE_AIA_CERT, Ignore = true)] - public virtual void MissingCertTest() { + public virtual void MissingCertTest(String missingCertName1, String missingCertName2) { String srcFileName = sourceFolder + "helloWorldDoc.pdf"; String signCertFileName = certsSrc + "sign_cert.pem"; String fistIntermediateCertFileName = certsSrc + "first_intermediate_cert.pem"; @@ -103,7 +84,7 @@ public virtual void MissingCertTest() { SignerProperties signerProperties = CreateSignerProperties(); MemoryStream outputStream = new MemoryStream(); PdfPadesSigner padesSigner = CreatePdfPadesSigner(srcFileName, outputStream); - IIssuingCertificateRetriever issuingCertificateRetriever = new _IssuingCertificateRetriever_118(firstMissingCertFileName + IIssuingCertificateRetriever issuingCertificateRetriever = new _IssuingCertificateRetriever_107(firstMissingCertFileName , secondMissingCertFileName); padesSigner.SetIssuingCertificateRetriever(issuingCertificateRetriever); padesSigner.SignWithBaselineBProfile(signerProperties, new IX509Certificate[] { signCert, rootCert }, signPrivateKey @@ -120,8 +101,8 @@ public virtual void MissingCertTest() { ); } - private sealed class _IssuingCertificateRetriever_118 : IssuingCertificateRetriever { - public _IssuingCertificateRetriever_118(String firstMissingCertFileName, String secondMissingCertFileName) { + private sealed class _IssuingCertificateRetriever_107 : IssuingCertificateRetriever { + public _IssuingCertificateRetriever_107(String firstMissingCertFileName, String secondMissingCertFileName) { this.firstMissingCertFileName = firstMissingCertFileName; this.secondMissingCertFileName = secondMissingCertFileName; } @@ -144,7 +125,7 @@ protected internal override Stream GetIssuerCertByURI(String uri) { private SignerProperties CreateSignerProperties() { SignerProperties signerProperties = new SignerProperties(); signerProperties.SetFieldName("Signature1"); - SignatureFieldAppearance appearance = new SignatureFieldAppearance(signerProperties.GetFieldName()).SetContent + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent ("Approval test signature.\nCreated by iText."); signerProperties.SetPageRect(new Rectangle(50, 650, 200, 100)).SetSignatureAppearance(appearance); return signerProperties; diff --git a/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesWithOcspCertificateTest.cs b/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesWithOcspCertificateTest.cs index bb3775f751..8a0e0e585c 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesWithOcspCertificateTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesWithOcspCertificateTest.cs @@ -75,7 +75,7 @@ public virtual void SignCertWithOcspTest() { IPrivateKey ocspPrivateKey = PemFileHelper.ReadFirstKey(ocspCertFileName, PASSWORD); SignerProperties signerProperties = CreateSignerProperties(); TestTsaClient testTsa = new TestTsaClient(JavaUtil.ArraysAsList(tsaChain), tsaPrivateKey); - AdvancedTestOcspClient ocspClient = new AdvancedTestOcspClient(null); + AdvancedTestOcspClient ocspClient = new AdvancedTestOcspClient(); ocspClient.AddBuilderForCertIssuer(signRsaCert, ocspCert, ocspPrivateKey); ocspClient.AddBuilderForCertIssuer(ocspCert, ocspCert, ocspPrivateKey); MemoryStream outputStream = new MemoryStream(); @@ -114,7 +114,7 @@ public virtual void SignCertWithoutOcspTest() { IPrivateKey ocspPrivateKey = PemFileHelper.ReadFirstKey(ocspCertFileName, PASSWORD); SignerProperties signerProperties = CreateSignerProperties(); TestTsaClient testTsa = new TestTsaClient(JavaUtil.ArraysAsList(tsaChain), tsaPrivateKey); - AdvancedTestOcspClient ocspClient = new AdvancedTestOcspClient(null); + AdvancedTestOcspClient ocspClient = new AdvancedTestOcspClient(); ocspClient.AddBuilderForCertIssuer((IX509Certificate)signRsaCert, (IX509Certificate)ocspCert, ocspPrivateKey ); ocspClient.AddBuilderForCertIssuer((IX509Certificate)ocspCert, (IX509Certificate)ocspCert, ocspPrivateKey); @@ -141,7 +141,7 @@ public virtual void SignCertWithOcspOcspCertSameAsSignCertTest() { IPrivateKey tsaPrivateKey = PemFileHelper.ReadFirstKey(tsaCertFileName, PASSWORD); SignerProperties signerProperties = CreateSignerProperties(); TestTsaClient testTsa = new TestTsaClient(JavaUtil.ArraysAsList(tsaChain), tsaPrivateKey); - AdvancedTestOcspClient ocspClient = new AdvancedTestOcspClient(null); + AdvancedTestOcspClient ocspClient = new AdvancedTestOcspClient(); ocspClient.AddBuilderForCertIssuer(signRsaCert, signRsaCert, signRsaPrivateKey); MemoryStream outputStream = new MemoryStream(); PdfPadesSigner padesSigner = CreatePdfPadesSigner(srcFileName, outputStream); @@ -166,7 +166,7 @@ private String GetCertName(IX509Certificate certificate) { private SignerProperties CreateSignerProperties() { SignerProperties signerProperties = new SignerProperties(); signerProperties.SetFieldName("Signature1"); - SignatureFieldAppearance appearance = new SignatureFieldAppearance(signerProperties.GetFieldName()).SetContent + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent ("Approval test signature.\nCreated by iText."); signerProperties.SetPageRect(new Rectangle(50, 650, 200, 100)).SetSignatureAppearance(appearance); return signerProperties; diff --git a/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesWithTimestampCertificateTest.cs b/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesWithTimestampCertificateTest.cs index 90d62eab86..73cb4b26b5 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesWithTimestampCertificateTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/sign/PdfPadesWithTimestampCertificateTest.cs @@ -73,7 +73,7 @@ public virtual void DifferentTimestampCertTest() { MemoryStream outputStream = new MemoryStream(); PdfPadesSigner padesSigner = CreatePdfPadesSigner(srcFileName, outputStream); TestTsaClient testTsa = new TestTsaClient(JavaUtil.ArraysAsList(tsaChain), tsaPrivateKey); - AdvancedTestOcspClient ocspClient = new AdvancedTestOcspClient(null); + AdvancedTestOcspClient ocspClient = new AdvancedTestOcspClient(); ocspClient.AddBuilderForCertIssuer((IX509Certificate)tsaChain[0], caCert, caPrivateKey); ocspClient.AddBuilderForCertIssuer((IX509Certificate)tsaChain[1], caCert, caPrivateKey); padesSigner.SetOcspClient(ocspClient); @@ -101,7 +101,7 @@ private String GetCertName(IX509Certificate certificate) { private SignerProperties CreateSignerProperties() { SignerProperties signerProperties = new SignerProperties(); signerProperties.SetFieldName("Signature1"); - SignatureFieldAppearance appearance = new SignatureFieldAppearance(signerProperties.GetFieldName()).SetContent + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent ("Approval test signature.\nCreated by iText."); signerProperties.SetPageRect(new Rectangle(50, 650, 200, 100)).SetSignatureAppearance(appearance); return signerProperties; diff --git a/itext.tests/itext.sign.tests/itext/signatures/sign/RSASSAPSSTest.cs b/itext.tests/itext.sign.tests/itext/signatures/sign/RSASSAPSSTest.cs index c9d3e108f9..6e67ab24e9 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/sign/RSASSAPSSTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/sign/RSASSAPSSTest.cs @@ -1,33 +1,33 @@ /* - This file is part of the iText (R) project. - Copyright (c) 1998-2024 Apryse Group NV - Authors: Apryse Software. - - This program is offered under a commercial and under the AGPL license. - For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. - - AGPL licensing: - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - */ +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ using System; using System.IO; using iText.Bouncycastleconnector; -using iText.Bouncycastlefips.Security; using iText.Commons.Bouncycastle; using iText.Commons.Bouncycastle.Cert; using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Utils; +using iText.Kernel.Crypto; using iText.Kernel.Exceptions; using iText.Kernel.Pdf; using iText.Signatures; @@ -35,13 +35,12 @@ You should have received a copy of the GNU Affero General Public License using iText.Test; namespace iText.Signatures.Sign { - [NUnit.Framework.Category("BouncyCastleIntegrationTest")] + [NUnit.Framework.Category("BouncyCastleUnitTest")] public class RSASSAPSSTest : ExtendedITextTest { - private static readonly IBouncyCastleFactory BOUNCY_CASTLE_FACTORY = BouncyCastleFactoryCreator.GetFactory(); + private static readonly IBouncyCastleFactory FACTORY = BouncyCastleFactoryCreator.GetFactory(); - private static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory( - NUnit.Framework.TestContext.CurrentContext.TestDirectory) - + "/resources/itext/signatures/sign/RSASSAPSSTest/"; + private static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + .CurrentContext.TestDirectory) + "/resources/itext/signatures/sign/RSASSAPSSTest/"; private static readonly String SOURCE_FILE = SOURCE_FOLDER + "helloWorldDoc.pdf"; @@ -58,76 +57,34 @@ public static void Before() { } [NUnit.Framework.Test] - public virtual void SignWithRsaSsaPssTest() - { + public virtual void SignWithRsaSsaPssTest() { String digestName = "SHA256"; String outFileName = "simplePssSignature.pdf"; String cmpFileName = "cmp_simplePssSignature.pdf"; - if ("BCFIPS".Equals(BOUNCY_CASTLE_FACTORY.GetProviderName())) - { - // Signer RSASSA-PSS not recognised in BCFIPS mode - NUnit.Framework.Assert.Catch(typeof(PdfException), () => - { - DoRoundTrip(digestName, "RSASSA-PSS", outFileName, - RSASSAPSSMechanismParams.CreateForDigestAlgorithm(digestName)); - }); - } - else - { - DoRoundTrip(digestName, "RSASSA-PSS", outFileName, - RSASSAPSSMechanismParams.CreateForDigestAlgorithm(digestName)); - NUnit.Framework.Assert.IsNull(SignaturesCompareTool.CompareSignatures(System.IO.Path.Combine( - DESTINATION_FOLDER - , outFileName).ToString(), System.IO.Path.Combine(SOURCE_FOLDER, cmpFileName).ToString())); - } + DoRoundTrip(digestName, "RSASSA-PSS", outFileName, RSASSAPSSMechanismParams.CreateForDigestAlgorithm(digestName + )); + NUnit.Framework.Assert.IsNull(SignaturesCompareTool.CompareSignatures(System.IO.Path.Combine(DESTINATION_FOLDER + , outFileName).ToString(), System.IO.Path.Combine(SOURCE_FOLDER, cmpFileName).ToString())); } [NUnit.Framework.Test] - public virtual void SignWithRsaSsaPssAlternativeNomenclatureTest() - { + public virtual void SignWithRsaSsaPssAlternativeNomenclatureTest() { String digestName = "SHA256"; String outFileName = "simplePssAlternativeNomenclatureSignature.pdf"; String cmpFileName = "cmp_simplePssSignature.pdf"; - - if ("BCFIPS".Equals(BOUNCY_CASTLE_FACTORY.GetProviderName())) - { - // Signer RSASSA-PSS not recognised in BCFIPS mode - NUnit.Framework.Assert.Catch(typeof(PdfException), () => - { - DoRoundTrip(digestName, + DoRoundTrip(digestName, //we should accept the "withRSA/PSS" convention as well "RSA/PSS", outFileName, RSASSAPSSMechanismParams.CreateForDigestAlgorithm(digestName)); - }); - } - else - { - DoRoundTrip(digestName, - //we should accept the "withRSA/PSS" convention as well - "RSA/PSS", outFileName, RSASSAPSSMechanismParams.CreateForDigestAlgorithm(digestName)); - NUnit.Framework.Assert.IsNull(SignaturesCompareTool.CompareSignatures(System.IO.Path.Combine( - DESTINATION_FOLDER - , outFileName).ToString(), System.IO.Path.Combine(SOURCE_FOLDER, cmpFileName).ToString())); - } + NUnit.Framework.Assert.IsNull(SignaturesCompareTool.CompareSignatures(System.IO.Path.Combine(DESTINATION_FOLDER + , outFileName).ToString(), System.IO.Path.Combine(SOURCE_FOLDER, cmpFileName).ToString())); } [NUnit.Framework.Test] public virtual void SignWithRsaSsaSha384PssTest() { String digestName = "SHA384"; String outFileName = "simplePssSignatureSha384.pdf"; - if ("BCFIPS".Equals(BOUNCY_CASTLE_FACTORY.GetProviderName())) - { - // Signer RSASSA-PSS not recognised in BCFIPS mode - NUnit.Framework.Assert.Catch(typeof(PdfException), () => - { - DoRoundTrip(digestName, "RSASSA-PSS", outFileName, - RSASSAPSSMechanismParams.CreateForDigestAlgorithm(digestName)); - }); - } - else - { - DoRoundTrip(digestName, "RSASSA-PSS", outFileName, - RSASSAPSSMechanismParams.CreateForDigestAlgorithm(digestName)); - } + DoRoundTrip(digestName, "RSASSA-PSS", outFileName, RSASSAPSSMechanismParams.CreateForDigestAlgorithm(digestName + )); } [NUnit.Framework.Test] @@ -135,26 +92,12 @@ public virtual void SignWithRsaSsaCustomSaltLengthTest() { String digestName = "SHA256"; String outFileName = "customSaltLength.pdf"; String cmpFileName = "cmp_simplePssSignature.pdf"; - - if ("BCFIPS".Equals(BOUNCY_CASTLE_FACTORY.GetProviderName())) { - // Signer RSASSA-PSS not recognised in BCFIPS mode - NUnit.Framework.Assert.Catch(typeof(PdfException), () => - { - DoRoundTrip(digestName, "RSASSA-PSS", outFileName, new RSASSAPSSMechanismParams( - BOUNCY_CASTLE_FACTORY.CreateASN1ObjectIdentifier - (DigestAlgorithms.GetAllowedDigest(digestName)), 40, 1)); - }); - } - else - { - DoRoundTrip(digestName, "RSASSA-PSS", outFileName, - new RSASSAPSSMechanismParams(BOUNCY_CASTLE_FACTORY.CreateASN1ObjectIdentifier - (DigestAlgorithms.GetAllowedDigest(digestName)), 40, 1)); - String cmpOut = SignaturesCompareTool.CompareSignatures(System.IO.Path.Combine(DESTINATION_FOLDER, - outFileName).ToString(), System.IO.Path.Combine(SOURCE_FOLDER, cmpFileName).ToString()); - NUnit.Framework.Assert.IsTrue(cmpOut.Contains("out: Integer(40)")); - NUnit.Framework.Assert.IsTrue(cmpOut.Contains("cmp: Integer(32)")); - } + DoRoundTrip(digestName, "RSASSA-PSS", outFileName, new RSASSAPSSMechanismParams(FACTORY.CreateASN1ObjectIdentifier + (DigestAlgorithms.GetAllowedDigest(digestName)), 40, 1)); + String cmpOut = SignaturesCompareTool.CompareSignatures(System.IO.Path.Combine(DESTINATION_FOLDER, outFileName + ).ToString(), System.IO.Path.Combine(SOURCE_FOLDER, cmpFileName).ToString()); + NUnit.Framework.Assert.IsTrue(cmpOut.Contains("out: Integer(40)")); + NUnit.Framework.Assert.IsTrue(cmpOut.Contains("cmp: Integer(32)")); } [NUnit.Framework.Test] @@ -164,6 +107,7 @@ public virtual void RejectMgfDigestDiscrepancy() { using (PdfReader r = new PdfReader(System.IO.Path.Combine(SOURCE_FOLDER, inFileName).ToString())) { using (PdfDocument pdfDoc = new PdfDocument(r)) { SignatureUtil u = new SignatureUtil(pdfDoc); + String provider = FACTORY.GetProviderName(); NUnit.Framework.Assert.Catch(typeof(PdfException), () => u.ReadSignatureData(SIGNATURE_FIELD)); } } @@ -179,16 +123,17 @@ private void DoRoundTrip(String digestAlgo, String signatureAlgo, String outFile private void DoSign(String digestAlgo, String signatureAlgo, String outFile, IApplicableSignatureParams @params ) { // write to a file for easier inspection when debugging - using (FileStream fos = FileUtil.GetFileOutputStream(outFile)) { - IX509Certificate root = ReadCertificate(System.IO.Path.Combine(SOURCE_FOLDER, "ca.crt")); - IX509Certificate signerCert = ReadCertificate(System.IO.Path.Combine(SOURCE_FOLDER, "rsa.crt")); + using (Stream fos = FileUtil.GetFileOutputStream(outFile)) { + IX509Certificate root = PemFileHelper.ReadFirstChain(SOURCE_FOLDER + "ca.pem")[0]; + IX509Certificate signerCert = PemFileHelper.ReadFirstChain(SOURCE_FOLDER + "rsa.pem")[0]; IX509Certificate[] signChain = new IX509Certificate[] { signerCert, root }; - IPrivateKey signPrivateKey = ReadPrivateKey(System.IO.Path.Combine(SOURCE_FOLDER, "rsa.key.pem")); + IPrivateKey signPrivateKey = PemFileHelper.ReadFirstKey(SOURCE_FOLDER + "rsa.key.pem", SAMPLE_KEY_PASSPHRASE + ); IExternalSignature pks = new PrivateKeySignature(signPrivateKey, digestAlgo, signatureAlgo, @params); - //IExternalSignature pks = new PrivateKeySignature(signPrivateKey, digestAlgo, @params); PdfSigner signer = new PdfSigner(new PdfReader(SOURCE_FILE), fos, new StampingProperties()); - signer.SetFieldName(SIGNATURE_FIELD); - signer.SignDetached(new BouncyCastleDigest(), pks, signChain, null, null, null, 0, PdfSigner.CryptoStandard.CMS); + signer.SetSignerProperties(new SignerProperties().SetFieldName(SIGNATURE_FIELD)); + signer.SignDetached(new BouncyCastleDigest(), pks, signChain, null, null, null, 0, PdfSigner.CryptoStandard + .CMS); } } @@ -197,24 +142,10 @@ private void DoVerify(String fileName) { using (PdfDocument pdfDoc = new PdfDocument(r)) { SignatureUtil u = new SignatureUtil(pdfDoc); PdfPKCS7 data = u.ReadSignatureData(SIGNATURE_FIELD); - NUnit.Framework.Assert.AreEqual(SecurityIDs.ID_RSASSA_PSS, data.GetSignatureMechanismOid()); + NUnit.Framework.Assert.AreEqual(OID.RSASSA_PSS, data.GetSignatureMechanismOid()); NUnit.Framework.Assert.IsTrue(data.VerifySignatureIntegrityAndAuthenticity()); } } } - - private IPrivateKey ReadPrivateKey(string path) { - try { - return PemFileHelper.ReadFirstKey(path, SAMPLE_KEY_PASSPHRASE); - } - catch (Exception e) { - throw new Exception("Reading key failed", e); - } - } - - private IX509Certificate ReadCertificate(string path) { - byte[] content = System.IO.File.ReadAllBytes(path); - return BOUNCY_CASTLE_FACTORY.CreateX509Certificate(content); - } } } diff --git a/itext.tests/itext.sign.tests/itext/signatures/sign/SequentialSignaturesTest.cs b/itext.tests/itext.sign.tests/itext/signatures/sign/SequentialSignaturesTest.cs index 8840d219e1..2d44ae85f7 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/sign/SequentialSignaturesTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/sign/SequentialSignaturesTest.cs @@ -24,6 +24,8 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Cert; using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Utils; +using iText.Forms.Form.Element; +using iText.Kernel.Crypto; using iText.Kernel.Geom; using iText.Kernel.Pdf; using iText.Signatures; @@ -61,9 +63,11 @@ public virtual void SequentialSignOfFileWithAnnots() { String signatureName = "Signature2"; PdfSigner signer = new PdfSigner(new PdfReader(srcFileName), FileUtil.GetFileOutputStream(outFileName), new StampingProperties().UseAppendMode()); - signer.SetFieldName(signatureName); - signer.GetSignatureAppearance().SetPageRect(new Rectangle(50, 350, 200, 100)).SetReason("Test").SetLocation - ("TestCity").SetLayer2Text("Approval test signature.\nCreated by iText."); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent + ("Approval test signature.\nCreated by iText."); + SignerProperties signerProperties = new SignerProperties().SetFieldName(signatureName).SetPageRect(new Rectangle + (50, 350, 200, 100)).SetReason("Test").SetLocation("TestCity").SetSignatureAppearance(appearance); + signer.SetSignerProperties(signerProperties); signer.SignDetached(new BouncyCastleDigest(), pks, signChain, null, null, null, 0, PdfSigner.CryptoStandard .CADES); TestSignUtils.BasicCheckSignedDoc(outFileName, signatureName); @@ -84,11 +88,12 @@ public virtual void SecondSignOfTaggedDocTest() { StampingProperties().UseAppendMode()); PdfDocument document = signer.GetDocument(); document.GetWriter().SetCompressionLevel(CompressionConstants.NO_COMPRESSION); - signer.SetFieldName(signatureName); - PdfSignatureAppearance appearance = signer.GetSignatureAppearance(); - appearance.SetPageNumber(1); - signer.GetSignatureAppearance().SetPageRect(new Rectangle(50, 550, 200, 100)).SetReason("Test2").SetLocation - ("TestCity2").SetLayer2Text("Approval test signature #2.\nCreated by iText."); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent + ("Approval test signature #2.\nCreated by iText."); + SignerProperties signerProperties = new SignerProperties().SetFieldName(signatureName).SetPageNumber(1).SetPageRect + (new Rectangle(50, 550, 200, 100)).SetReason("Test2").SetLocation("TestCity2").SetSignatureAppearance( + appearance); + signer.SetSignerProperties(signerProperties); signer.SignDetached(new BouncyCastleDigest(), pks, signChain, null, null, null, 0, PdfSigner.CryptoStandard .CADES); TestSignUtils.BasicCheckSignedDoc(outFileName, "Signature1"); diff --git a/itext.tests/itext.sign.tests/itext/signatures/sign/SignDeferredTest.cs b/itext.tests/itext.sign.tests/itext/signatures/sign/SignDeferredTest.cs index 85dbf55163..272031bc8b 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/sign/SignDeferredTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/sign/SignDeferredTest.cs @@ -27,6 +27,8 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Security; using iText.Commons.Utils; using iText.Forms.Fields; +using iText.Forms.Form.Element; +using iText.Kernel.Crypto; using iText.Kernel.Geom; using iText.Kernel.Pdf; using iText.Kernel.Utils; @@ -66,10 +68,12 @@ public virtual void PrepareDocForSignDeferredTest() { int estimatedSize = 8192; PdfReader reader = new PdfReader(input); PdfSigner signer = new PdfSigner(reader, FileUtil.GetFileOutputStream(output), new StampingProperties()); - PdfSignatureAppearance appearance = signer.GetSignatureAppearance(); - appearance.SetLayer2Text("Signature field which signing is deferred.").SetPageRect(new Rectangle(36, 600, - 200, 100)).SetPageNumber(1); - signer.SetFieldName(sigFieldName); + SignerProperties signerProperties = new SignerProperties().SetFieldName(sigFieldName); + signer.SetSignerProperties(signerProperties); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent + ("Signature field which signing is deferred."); + signerProperties.SetPageRect(new Rectangle(36, 600, 200, 100)).SetPageNumber(1).SetSignatureAppearance(appearance + ); IExternalSignatureContainer external = new ExternalBlankSignatureContainer(filter, subFilter); signer.SignExternalContainer(external, estimatedSize); // validate result @@ -84,10 +88,12 @@ public virtual void PrepareDocForSignDeferredNotEnoughSizeTest() { PdfName subFilter = PdfName.Adbe_pkcs7_detached; PdfReader reader = new PdfReader(input); PdfSigner signer = new PdfSigner(reader, new MemoryStream(), new StampingProperties()); - PdfSignatureAppearance appearance = signer.GetSignatureAppearance(); - appearance.SetLayer2Text("Signature field which signing is deferred.").SetPageRect(new Rectangle(36, 600, - 200, 100)).SetPageNumber(1); - signer.SetFieldName(sigFieldName); + SignerProperties signerProperties = new SignerProperties().SetFieldName(sigFieldName); + signer.SetSignerProperties(signerProperties); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent + ("Signature field which signing is deferred."); + signerProperties.SetPageRect(new Rectangle(36, 600, 200, 100)).SetPageNumber(1).SetSignatureAppearance(appearance + ); IExternalSignatureContainer external = new ExternalBlankSignatureContainer(filter, subFilter); // This size is definitely not enough int estimatedSize = -1; @@ -104,10 +110,12 @@ public virtual void PrepareDocForSignDeferredLittleSpaceTest() { PdfName subFilter = PdfName.Adbe_pkcs7_detached; PdfReader reader = new PdfReader(input); PdfSigner signer = new PdfSigner(reader, new MemoryStream(), new StampingProperties()); - PdfSignatureAppearance appearance = signer.GetSignatureAppearance(); - appearance.SetLayer2Text("Signature field which signing is deferred.").SetPageRect(new Rectangle(36, 600, - 200, 100)).SetPageNumber(1); - signer.SetFieldName(sigFieldName); + SignerProperties signerProperties = new SignerProperties().SetFieldName(sigFieldName); + signer.SetSignerProperties(signerProperties); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent + ("Signature field which signing is deferred."); + signerProperties.SetPageRect(new Rectangle(36, 600, 200, 100)).SetPageNumber(1).SetSignatureAppearance(appearance + ); IExternalSignatureContainer external = new ExternalBlankSignatureContainer(filter, subFilter); // This size is definitely not enough, however, the size check will pass. // The test will fail lately on an invalid key @@ -153,11 +161,13 @@ public virtual void CalcHashOnDocCreationThenDeferredSignTest01() { PdfReader reader = new PdfReader(input); MemoryStream baos = new MemoryStream(); PdfSigner signer = new PdfSigner(reader, baos, new StampingProperties()); - signer.SetCertificationLevel(PdfSigner.CERTIFIED_NO_CHANGES_ALLOWED); - PdfSignatureAppearance appearance = signer.GetSignatureAppearance(); - appearance.SetLayer2Text("Signature field which signing is deferred.").SetPageRect(new Rectangle(36, 600, - 200, 100)).SetPageNumber(1); - signer.SetFieldName(sigFieldName); + SignerProperties signerProperties = new SignerProperties().SetCertificationLevel(AccessPermissions.NO_CHANGES_PERMITTED + ).SetFieldName(sigFieldName); + signer.SetSignerProperties(signerProperties); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent + ("Signature field which signing is deferred."); + signerProperties.SetPageRect(new Rectangle(36, 600, 200, 100)).SetPageNumber(1).SetSignatureAppearance(appearance + ); SignDeferredTest.DigestCalcBlankSigner external = new SignDeferredTest.DigestCalcBlankSigner(filter, subFilter ); signer.SignExternalContainer(external, estimatedSize); diff --git a/itext.tests/itext.sign.tests/itext/signatures/sign/PdfSignatureAppearanceTest.cs b/itext.tests/itext.sign.tests/itext/signatures/sign/SignatureAppearanceTest.cs similarity index 58% rename from itext.tests/itext.sign.tests/itext/signatures/sign/PdfSignatureAppearanceTest.cs rename to itext.tests/itext.sign.tests/itext/signatures/sign/SignatureAppearanceTest.cs index 1469430e10..078ebc081b 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/sign/PdfSignatureAppearanceTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/sign/SignatureAppearanceTest.cs @@ -23,36 +23,45 @@ You should have received a copy of the GNU Affero General Public License using System; using System.Collections.Generic; using System.Text; +using iText.Bouncycastleconnector; +using iText.Commons.Bouncycastle; using iText.Commons.Bouncycastle.Cert; using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Utils; using iText.Forms; using iText.Forms.Fields; +using iText.Forms.Fields.Properties; +using iText.Forms.Form; using iText.Forms.Form.Element; using iText.IO.Image; using iText.Kernel.Colors; +using iText.Kernel.Crypto; using iText.Kernel.Geom; using iText.Kernel.Pdf; using iText.Kernel.Pdf.Canvas; using iText.Kernel.Pdf.Xobject; using iText.Kernel.Utils; +using iText.Layout; using iText.Layout.Borders; using iText.Layout.Properties; using iText.Signatures; using iText.Signatures.Testutils; using iText.Test; +using iText.Test.Attributes; namespace iText.Signatures.Sign { [NUnit.Framework.Category("BouncyCastleIntegrationTest")] - public class PdfSignatureAppearanceTest : ExtendedITextTest { + public class SignatureAppearanceTest : ExtendedITextTest { + private static readonly IBouncyCastleFactory FACTORY = BouncyCastleFactoryCreator.GetFactory(); + public static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext - .CurrentContext.TestDirectory) + "/resources/itext/signatures/sign/PdfSignatureAppearanceTest/"; + .CurrentContext.TestDirectory) + "/resources/itext/signatures/sign/SignatureAppearanceTest/"; public static readonly String DESTINATION_FOLDER = NUnit.Framework.TestContext.CurrentContext.TestDirectory - + "/test/itext/signatures/sign/PdfSignatureAppearanceTest/"; + + "/test/itext/signatures/sign/SignatureAppearanceTest/"; public static readonly String KEYSTORE_PATH = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext - .CurrentContext.TestDirectory) + "/resources/itext/signatures/sign/PdfSignatureAppearanceTest/test.pem"; + .CurrentContext.TestDirectory) + "/resources/itext/signatures/sign/SignatureAppearanceTest/test.pem"; public static readonly char[] PASSWORD = "testpassphrase".ToCharArray(); @@ -76,7 +85,7 @@ public virtual void TextAutoscaleTest01() { String fileName = "textAutoscaleTest01.pdf"; String dest = DESTINATION_FOLDER + fileName; Rectangle rect = new Rectangle(36, 648, 200, 100); - TestSignatureAppearanceAutoscale(dest, rect, PdfSignatureAppearance.RenderingMode.DESCRIPTION); + TestSignatureAppearanceAutoscale(dest, rect, null, null); AssertAppearanceFontSize(dest, 13.72f); } @@ -85,7 +94,7 @@ public virtual void TextAutoscaleTest02() { String fileName = "textAutoscaleTest02.pdf"; String dest = DESTINATION_FOLDER + fileName; Rectangle rect = new Rectangle(36, 648, 150, 50); - TestSignatureAppearanceAutoscale(dest, rect, PdfSignatureAppearance.RenderingMode.DESCRIPTION); + TestSignatureAppearanceAutoscale(dest, rect, null, null); AssertAppearanceFontSize(dest, 7.73f); } @@ -94,7 +103,7 @@ public virtual void TextAutoscaleTest03() { String fileName = "textAutoscaleTest03.pdf"; String dest = DESTINATION_FOLDER + fileName; Rectangle rect = new Rectangle(36, 648, 200, 100); - TestSignatureAppearanceAutoscale(dest, rect, PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION); + TestSignatureAppearanceAutoscale(dest, rect, "SignerName", null); AssertAppearanceFontSize(dest, 44.35f); } @@ -103,7 +112,7 @@ public virtual void TextAutoscaleTest04() { String fileName = "textAutoscaleTest04.pdf"; String dest = DESTINATION_FOLDER + fileName; Rectangle rect = new Rectangle(36, 648, 100, 50); - TestSignatureAppearanceAutoscale(dest, rect, PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION); + TestSignatureAppearanceAutoscale(dest, rect, "SignerName", null); AssertAppearanceFontSize(dest, 21.25f); } @@ -112,7 +121,7 @@ public virtual void TextAutoscaleTest05() { String fileName = "textAutoscaleTest05.pdf"; String dest = DESTINATION_FOLDER + fileName; Rectangle rect = new Rectangle(36, 648, 200, 100); - TestSignatureAppearanceAutoscale(dest, rect, PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION); + TestSignatureAppearanceAutoscale(dest, rect, null, ImageDataFactory.Create(SOURCE_FOLDER + "itext.png")); AssertAppearanceFontSize(dest, 12.77f); } @@ -121,7 +130,7 @@ public virtual void TextAutoscaleTest06() { String fileName = "textAutoscaleTest06.pdf"; String dest = DESTINATION_FOLDER + fileName; Rectangle rect = new Rectangle(36, 648, 100, 50); - TestSignatureAppearanceAutoscale(dest, rect, PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION); + TestSignatureAppearanceAutoscale(dest, rect, null, ImageDataFactory.Create(SOURCE_FOLDER + "itext.png")); AssertAppearanceFontSize(dest, 6.26f); } @@ -133,11 +142,12 @@ public virtual void TestSigningInAppendModeWithHybridDocument() { PdfSigner signer = new PdfSigner(new PdfReader(src), FileUtil.GetFileOutputStream(dest), new StampingProperties ().UseAppendMode()); String fieldName = "Sign1"; - SignatureFieldAppearance appearance = new SignatureFieldAppearance(fieldName).SetFontSize(13.8f); - signer.SetFieldName(fieldName); - signer.SetReason("Test").SetLocation("Nagpur").SetPageRect(new Rectangle(36, 748, 200, 100)).SetPageNumber - (1).SetSignatureAppearance(appearance); - signer.SetCertificationLevel(PdfSigner.NOT_CERTIFIED); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent + (new SignedAppearanceText()).SetFontSize(13.8f); + SignerProperties signerProperties = new SignerProperties().SetFieldName(fieldName).SetReason("Test").SetLocation + ("Nagpur").SetPageRect(new Rectangle(36, 748, 250, 100)).SetPageNumber(1).SetSignatureAppearance(appearance + ).SetCertificationLevel(AccessPermissions.UNSPECIFIED); + signer.SetSignerProperties(signerProperties); IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES ); @@ -145,7 +155,7 @@ public virtual void TestSigningInAppendModeWithHybridDocument() { new PdfDocument(new PdfReader(dest)).Close(); // Assert that the document can be rendered correctly NUnit.Framework.Assert.IsNull(new CompareTool().CompareVisually(dest, cmp, DESTINATION_FOLDER, "diff_", GetIgnoredAreaTestMap - (new Rectangle(36, 748, 200, 100)))); + (new Rectangle(36, 748, 250, 100)))); } [NUnit.Framework.Test] @@ -156,10 +166,11 @@ public virtual void FontColorTest01() { String src = SOURCE_FOLDER + "simpleDocument.pdf"; PdfSigner signer = new PdfSigner(new PdfReader(src), FileUtil.GetFileOutputStream(dest), new StampingProperties ()); - signer.SetFieldName("Signature1"); + SignerProperties signerProperties = new SignerProperties().SetFieldName("Signature1"); + signer.SetSignerProperties(signerProperties); // Creating the appearance - signer.SetPageRect(rect).SetSignatureAppearance(new SignatureFieldAppearance(signer.GetFieldName()).SetFontColor - (ColorConstants.RED).SetContent("Verified and signed by me.")); + signerProperties.SetPageRect(rect).SetSignatureAppearance(new SignatureFieldAppearance(SignerProperties.IGNORED_ID + ).SetFontColor(ColorConstants.RED).SetContent("Verified and signed by me.")); // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES @@ -169,14 +180,14 @@ public virtual void FontColorTest01() { } [NUnit.Framework.Test] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.CLIP_ELEMENT, Ignore = true)] public virtual void SignaturesOnRotatedPages() { StringBuilder assertionResults = new StringBuilder(); for (int i = 1; i <= 4; i++) { - TestSignatureOnRotatedPage(i, PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION, assertionResults - ); - TestSignatureOnRotatedPage(i, PdfSignatureAppearance.RenderingMode.GRAPHIC, assertionResults); - TestSignatureOnRotatedPage(i, PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION, assertionResults); - TestSignatureOnRotatedPage(i, PdfSignatureAppearance.RenderingMode.DESCRIPTION, assertionResults); + TestSignatureOnRotatedPage(i, true, false, true, assertionResults); + TestSignatureOnRotatedPage(i, false, false, true, assertionResults); + TestSignatureOnRotatedPage(i, true, true, false, assertionResults); + TestSignatureOnRotatedPage(i, true, false, false, assertionResults); } NUnit.Framework.Assert.AreEqual("", assertionResults.ToString()); } @@ -199,10 +210,11 @@ public virtual void SignExistingNotMergedFieldNotReusedAPTest() { String dest = DESTINATION_FOLDER + fileName; PdfReader reader = new PdfReader(src); PdfSigner signer = new PdfSigner(reader, FileUtil.GetFileOutputStream(dest), new StampingProperties()); - signer.SetCertificationLevel(PdfSigner.NOT_CERTIFIED); - signer.SetFieldName("Signature1"); - signer.SetReason("Test 1").SetLocation("TestCity").SetSignatureAppearance(new SignatureFieldAppearance(signer - .GetFieldName()).SetContent("Verified and signed by me.")); + SignerProperties signerProperties = new SignerProperties().SetFieldName("Signature1").SetCertificationLevel + (AccessPermissions.UNSPECIFIED).SetReason("Test 1").SetLocation("TestCity"); + signer.SetSignerProperties(signerProperties); + signerProperties.SetSignatureAppearance(new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent + ("Verified and signed by me.")); signer.GetSignatureField().SetReuseAppearance(false); IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES @@ -219,12 +231,13 @@ public virtual void SignExistingNotMergedFieldReusedAPTest() { String dest = DESTINATION_FOLDER + fileName; PdfReader reader = new PdfReader(src); PdfSigner signer = new PdfSigner(reader, FileUtil.GetFileOutputStream(dest), new StampingProperties()); - signer.SetCertificationLevel(PdfSigner.NOT_CERTIFIED); - signer.SetFieldName("Signature1"); - SignatureFieldAppearance appearance = new SignatureFieldAppearance(signer.GetFieldName()).SetContent("SIGNED" - ).SetFontColor(ColorConstants.GREEN); + SignerProperties signerProperties = new SignerProperties().SetCertificationLevel(AccessPermissions.UNSPECIFIED + ).SetFieldName("Signature1"); + signer.SetSignerProperties(signerProperties); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent + ("SIGNED").SetFontColor(ColorConstants.GREEN); appearance.SetProperty(Property.VERTICAL_ALIGNMENT, VerticalAlignment.MIDDLE); - signer.SetReason("Test 1").SetLocation("TestCity").SetSignatureAppearance(appearance); + signerProperties.SetReason("Test 1").SetLocation("TestCity").SetSignatureAppearance(appearance); signer.GetSignatureField().SetReuseAppearance(true); IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES @@ -241,10 +254,11 @@ public virtual void SignExistingNotMergedFieldReusedAPEntryNDicTest() { String dest = DESTINATION_FOLDER + fileName; PdfReader reader = new PdfReader(src); PdfSigner signer = new PdfSigner(reader, FileUtil.GetFileOutputStream(dest), new StampingProperties()); - signer.SetCertificationLevel(PdfSigner.NOT_CERTIFIED); - signer.SetFieldName("Signature1"); - signer.SetReason("Test 1").SetLocation("TestCity").SetSignatureAppearance(new SignatureFieldAppearance(signer - .GetFieldName()).SetContent("Verified and signed by me.")); + SignerProperties signerProperties = new SignerProperties().SetCertificationLevel(AccessPermissions.UNSPECIFIED + ).SetFieldName("Signature1").SetReason("Test 1").SetLocation("TestCity"); + signer.SetSignerProperties(signerProperties); + signerProperties.SetSignatureAppearance(new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent + ("Verified and signed by me.")); signer.GetSignatureField().SetReuseAppearance(true); IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES @@ -254,133 +268,33 @@ public virtual void SignExistingNotMergedFieldReusedAPEntryNDicTest() { } [NUnit.Framework.Test] - public virtual void Layer0Test() { - String src = SOURCE_FOLDER + "simpleDocument.pdf"; - String fileName = "layer0Test.pdf"; - String dest = DESTINATION_FOLDER + fileName; - PdfSigner signer = new PdfSigner(new PdfReader(src), FileUtil.GetFileOutputStream(dest), new StampingProperties - ()); - // Creating the appearance - PdfSignatureAppearance appearance = signer.GetSignatureAppearance(); - signer.SetFieldName("Signature1"); - Rectangle rect = new Rectangle(0, 600, 100, 100); - appearance.SetPageRect(rect); - // If we do not set any text, the text will be generated and the current date will be used, - // which we want to avoid because of visual comparison - appearance.SetLayer2Text("Hello"); - PdfFormXObject layer0 = appearance.GetLayer0(); - // Draw red rectangle with blue border - new PdfCanvas(layer0, signer.GetDocument()).SaveState().SetFillColor(ColorConstants.RED).SetStrokeColor(ColorConstants - .BLUE).Rectangle(0, 0, 100, 100).FillStroke().RestoreState(); - // Get the same layer once more, so that the logic when n0 is not null is triggered - layer0 = appearance.GetLayer0(); - // Draw yellow circle with black border - new PdfCanvas(layer0, signer.GetDocument()).SaveState().SetFillColor(ColorConstants.YELLOW).SetStrokeColor - (ColorConstants.BLACK).Circle(50, 50, 50).FillStroke().RestoreState(); - // Signing - IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); - signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES - ); - CompareSignatureAppearances(dest, SOURCE_FOLDER + "cmp_" + fileName); - } - - [NUnit.Framework.Test] - public virtual void Layer0WithImageTest() { - String src = SOURCE_FOLDER + "simpleDocument.pdf"; - String fileName = "layer0WithImageTest.pdf"; - String dest = DESTINATION_FOLDER + fileName; - PdfSigner signer = new PdfSigner(new PdfReader(src), FileUtil.GetFileOutputStream(dest), new StampingProperties - ()); - // Creating the appearance - PdfSignatureAppearance appearance = signer.GetSignatureAppearance(); - appearance.SetImage(ImageDataFactory.Create(SOURCE_FOLDER + "itext.png")); - signer.SetFieldName("Signature1"); - Rectangle rect = new Rectangle(0, 600, 100, 100); - appearance.SetPageRect(rect); - // If we do not set any text, the text will be generated and the current date will be used, - // which we want to avoid because of visual comparison - appearance.SetLayer2Text("Hello"); - // Signing - IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); - signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES - ); - CompareSignatureAppearances(dest, SOURCE_FOLDER + "cmp_" + fileName); - } - - [NUnit.Framework.Test] - public virtual void Layer0WithImageAndPositiveImageScaleTest() { - String src = SOURCE_FOLDER + "simpleDocument.pdf"; - String fileName = "layer0WithImageAndPositiveImageScaleTest.pdf"; - String dest = DESTINATION_FOLDER + fileName; - PdfSigner signer = new PdfSigner(new PdfReader(src), FileUtil.GetFileOutputStream(dest), new StampingProperties - ()); - // Creating the appearance - PdfSignatureAppearance appearance = signer.GetSignatureAppearance(); - appearance.SetImage(ImageDataFactory.Create(SOURCE_FOLDER + "itext.png")); - appearance.SetImageScale(1.5F); - signer.SetFieldName("Signature1"); - Rectangle rect = new Rectangle(0, 600, 100, 100); - appearance.SetPageRect(rect); - // If we do not set any text, the text will be generated and the current date will be used, - // which we want to avoid because of visual comparison - appearance.SetLayer2Text("Hello"); - // Signing - IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); - signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES - ); - CompareSignatureAppearances(dest, SOURCE_FOLDER + "cmp_" + fileName); - } - - [NUnit.Framework.Test] - public virtual void Layer0WithImageAndNegativeImageScaleTest() { - String src = SOURCE_FOLDER + "simpleDocument.pdf"; - String fileName = "layer0WithImageAndNegativeImageScale.pdf"; - String dest = DESTINATION_FOLDER + fileName; - PdfSigner signer = new PdfSigner(new PdfReader(src), FileUtil.GetFileOutputStream(dest), new StampingProperties - ()); - // Creating the appearance - PdfSignatureAppearance appearance = signer.GetSignatureAppearance(); - appearance.SetImage(ImageDataFactory.Create(SOURCE_FOLDER + "itext.png")); - appearance.SetImageScale(-15F); - signer.SetFieldName("Signature1"); - Rectangle rect = new Rectangle(0, 600, 100, 100); - appearance.SetPageRect(rect); - // If we do not set any text, the text will be generated and the current date will be used, - // which we want to avoid because of visual comparison - appearance.SetLayer2Text("Hello"); - // Signing - IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); - signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES - ); - CompareSignatureAppearances(dest, SOURCE_FOLDER + "cmp_" + fileName); - } - - [NUnit.Framework.Test] - public virtual void Layer2Test() { - String src = SOURCE_FOLDER + "simpleDocument.pdf"; - String fileName = "layer2Test.pdf"; - String dest = DESTINATION_FOLDER + fileName; - PdfSigner signer = new PdfSigner(new PdfReader(src), FileUtil.GetFileOutputStream(dest), new StampingProperties - ()); - // Creating the appearance - PdfSignatureAppearance appearance = signer.GetSignatureAppearance(); - signer.SetFieldName("Signature1"); - Rectangle rect = new Rectangle(0, 600, 100, 100); - appearance.SetPageRect(rect); - PdfFormXObject layer2 = appearance.GetLayer2(); - // Draw red rectangle with blue border - new PdfCanvas(layer2, signer.GetDocument()).SaveState().SetFillColor(ColorConstants.RED).SetStrokeColor(ColorConstants - .BLUE).Rectangle(0, 0, 100, 100).FillStroke().RestoreState(); - // Get the same layer once more, so that the logic when n2 is not null is triggered - layer2 = appearance.GetLayer2(); - // Draw yellow circle with black border - new PdfCanvas(layer2, signer.GetDocument()).SaveState().SetFillColor(ColorConstants.YELLOW).SetStrokeColor - (ColorConstants.BLACK).Circle(50, 50, 50).FillStroke().RestoreState(); - // Signing - IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); - signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES - ); - CompareSignatureAppearances(dest, SOURCE_FOLDER + "cmp_" + fileName); + public virtual void BackgroundImageTest() { + String outPdf = DESTINATION_FOLDER + "signatureFieldBackground.pdf"; + String cmpPdf = SOURCE_FOLDER + "cmp_signatureFieldBackground.pdf"; + using (Document document = new Document(new PdfDocument(new PdfWriter(outPdf)))) { + SignatureFieldAppearance field1 = new SignatureFieldAppearance("field1"); + field1.SetProperty(FormProperty.FORM_FIELD_FLATTEN, true); + field1.SetContent("scale -1").SetFontColor(ColorConstants.GREEN).SetFontSize(50).SetBorder(new SolidBorder + (ColorConstants.RED, 10)).SetHeight(200).SetWidth(300).SetProperty(Property.TEXT_ALIGNMENT, TextAlignment + .CENTER); + ApplyBackgroundImage(field1, ImageDataFactory.Create(SOURCE_FOLDER + "1.png"), -1); + document.Add(field1); + SignatureFieldAppearance field2 = new SignatureFieldAppearance("field2"); + field2.SetProperty(FormProperty.FORM_FIELD_FLATTEN, true); + field2.SetContent("scale 0").SetFontColor(ColorConstants.GREEN).SetFontSize(50).SetBorder(new SolidBorder( + ColorConstants.YELLOW, 10)).SetHeight(200).SetWidth(300).SetProperty(Property.TEXT_ALIGNMENT, TextAlignment + .CENTER); + ApplyBackgroundImage(field2, ImageDataFactory.Create(SOURCE_FOLDER + "1.png"), 0); + document.Add(field2); + SignatureFieldAppearance field3 = new SignatureFieldAppearance("field3"); + field3.SetProperty(FormProperty.FORM_FIELD_FLATTEN, true); + field3.SetContent("scale 0.5").SetFontColor(ColorConstants.GREEN).SetFontSize(50).SetBorder(new SolidBorder + (ColorConstants.GREEN, 10)).SetHeight(200).SetWidth(300).SetProperty(Property.TEXT_ALIGNMENT, TextAlignment + .CENTER); + ApplyBackgroundImage(field3, ImageDataFactory.Create(SOURCE_FOLDER + "1.png"), 0.5f); + document.Add(field3); + } + NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, DESTINATION_FOLDER)); } [NUnit.Framework.Test] @@ -396,11 +310,14 @@ public virtual void CreateAndSignSignatureFieldTest() { document.Close(); PdfSigner signer = new PdfSigner(new PdfReader(unsignedDoc), FileUtil.GetFileOutputStream(dest), new StampingProperties ()); - signer.SetFieldName(fieldName); + SignerProperties signerProperties = new SignerProperties().SetFieldName(fieldName); + signer.SetSignerProperties(signerProperties); // Creating the appearance - SignatureFieldAppearance appearance = new SignatureFieldAppearance(fieldName).SetContent("Test signature field appearance. Test signature field appearance. " - + "Test signature field appearance. Test signature field appearance"); - signer.SetReason("Appearance is tested").SetLocation("TestCity").SetSignatureAppearance(appearance); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent + ("Test signature field appearance. Test signature field appearance. " + "Test signature field appearance. Test signature field appearance" + ); + signerProperties.SetReason("Appearance is tested").SetLocation("TestCity").SetSignatureAppearance(appearance + ); // Signing IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES @@ -415,11 +332,14 @@ public virtual void SignExistedSignatureFieldTest() { String dest = DESTINATION_FOLDER + fileName; PdfSigner signer = new PdfSigner(new PdfReader(src), FileUtil.GetFileOutputStream(dest), new StampingProperties ()); - signer.SetFieldName("Signature1"); + SignerProperties signerProperties = new SignerProperties().SetFieldName("Signature1"); + signer.SetSignerProperties(signerProperties); // Creating the appearance - SignatureFieldAppearance appearance = new SignatureFieldAppearance(signer.GetFieldName()).SetContent("Test signature field appearance. Test signature field appearance. " - + "Test signature field appearance. Test signature field appearance"); - signer.SetReason("Appearance is tested").SetLocation("TestCity").SetSignatureAppearance(appearance); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent + ("Test signature field appearance. Test signature field appearance. " + "Test signature field appearance. Test signature field appearance" + ); + signerProperties.SetReason("Appearance is tested").SetLocation("TestCity").SetSignatureAppearance(appearance + ); signer.GetSignatureField().SetReuseAppearance(true); // Signing IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); @@ -433,37 +353,14 @@ public virtual void ReuseAppearanceTest() { // Field is not merged with widget and has /P key String src = SOURCE_FOLDER + "emptyFieldNotMerged.pdf"; String fileName = "reuseAppearance.pdf"; - TestReuseAppearance(src, fileName, false, true, false); - } - - [NUnit.Framework.Test] - public virtual void ReuseAppearanceDeprecatedTest() { - // Field is not merged with widget and has /P key - String src = SOURCE_FOLDER + "emptyFieldNotMerged.pdf"; - String fileName = "reuseAppearanceDeprecated.pdf"; - TestReuseAppearance(src, fileName, true, false, true); - } - - [NUnit.Framework.Test] - public virtual void ReuseAppearanceCompatibilityTest() { - // Field is not merged with widget and has /P key - String src = SOURCE_FOLDER + "emptyFieldNotMerged.pdf"; - String fileName = "reuseAppearanceCompatibility.pdf"; - TestReuseAppearance(src, fileName, true, true, false); + TestReuseAppearance(src, fileName); } [NUnit.Framework.Test] public virtual void FieldLayersTest() { String src = SOURCE_FOLDER + "noSignatureField.pdf"; String fileName = "fieldLayersTest.pdf"; - TestLayers(src, fileName, false); - } - - [NUnit.Framework.Test] - public virtual void DeprecatedLayersTest() { - String src = SOURCE_FOLDER + "noSignatureField.pdf"; - String fileName = "deprecatedLayersTest.pdf"; - TestLayers(src, fileName, true); + TestLayers(src, fileName); } [NUnit.Framework.Test] @@ -475,12 +372,14 @@ public virtual void SignatureFieldAppearanceTest() { String fieldName = "Signature1"; PdfSigner signer = new PdfSigner(new PdfReader(src), FileUtil.GetFileOutputStream(dest), new StampingProperties ()); - signer.SetFieldName(fieldName); - SignatureFieldAppearance appearance = new SignatureFieldAppearance(fieldName).SetContent("Signature field" - ).SetBackgroundColor(ColorConstants.GREEN).SetBorder(new SolidBorder(ColorConstants.LIGHT_GRAY, 3)).SetFontColor - (ColorConstants.DARK_GRAY).SetFontSize(20).SetTextAlignment(TextAlignment.CENTER); - signer.SetPageRect(new Rectangle(250, 500, 100, 100)).SetReason("Test 1").SetLocation("TestCity").SetSignatureAppearance - (appearance); + SignerProperties signerProperties = new SignerProperties().SetFieldName(fieldName); + signer.SetSignerProperties(signerProperties); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent + ("Signature field").SetBackgroundColor(ColorConstants.GREEN).SetBorder(new SolidBorder(ColorConstants. + LIGHT_GRAY, 3)).SetFontColor(ColorConstants.DARK_GRAY).SetFontSize(20).SetTextAlignment(TextAlignment. + CENTER); + signerProperties.SetPageRect(new Rectangle(250, 500, 100, 100)).SetReason("Test 1").SetLocation("TestCity" + ).SetSignatureAppearance(appearance); // Signing IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES @@ -496,13 +395,13 @@ public virtual void EmptySignatureAppearanceTest() { String outPdf = DESTINATION_FOLDER + "emptySignatureAppearance.pdf"; Rectangle rect = new Rectangle(36, 648, 200, 100); String fieldName = "Signature1"; - SignatureFieldAppearance appearance = new SignatureFieldAppearance(fieldName); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID); PdfSigner signer = new PdfSigner(new PdfReader(srcFile), FileUtil.GetFileOutputStream(outPdf), new StampingProperties ()); - signer.SetCertificationLevel(PdfSigner.NOT_CERTIFIED); - signer.SetFieldName(fieldName); - signer.SetReason("test reason").SetLocation("test location").SetSignatureAppearance(appearance); - signer.SetPageRect(rect); + SignerProperties signerProperties = new SignerProperties().SetCertificationLevel(AccessPermissions.UNSPECIFIED + ).SetFieldName(fieldName).SetReason("test reason").SetLocation("test location").SetSignatureAppearance + (appearance).SetPageRect(rect); + signer.SetSignerProperties(signerProperties); // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES @@ -525,34 +424,32 @@ private static void CompareSignatureAppearances(String outPdf, String cmpPdf) { } } - private void TestReuseAppearance(String src, String fileName, bool useDeprecated, bool fieldReuseAp, bool - deprecatedReuseAp) { + private void TestReuseAppearance(String src, String fileName) { String cmp = SOURCE_FOLDER + "cmp_" + fileName; String dest = DESTINATION_FOLDER + fileName; String fieldName = "Signature1"; PdfSigner signer = new PdfSigner(new PdfReader(src), FileUtil.GetFileOutputStream(dest), new StampingProperties ()); - signer.SetFieldName(fieldName); - signer.GetSignatureField().SetReuseAppearance(fieldReuseAp); - if (useDeprecated) { - signer.GetSignatureAppearance().SetReuseAppearance(deprecatedReuseAp); - } - signer.SetReason("Test 1").SetLocation("TestCity").SetSignatureAppearance(new SignatureFieldAppearance(fieldName - ).SetContent("New appearance").SetFontColor(ColorConstants.GREEN)); + SignerProperties signerProperties = new SignerProperties().SetFieldName(fieldName); + signer.SetSignerProperties(signerProperties); + signer.GetSignatureField().SetReuseAppearance(true); + signerProperties.SetReason("Test 1").SetLocation("TestCity").SetSignatureAppearance(new SignatureFieldAppearance + (SignerProperties.IGNORED_ID).SetContent("New appearance").SetFontColor(ColorConstants.GREEN)); IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES ); NUnit.Framework.Assert.IsNull(new CompareTool().CompareVisually(dest, cmp, DESTINATION_FOLDER, "diff_")); } - private void TestLayers(String src, String fileName, bool useDeprecated) { + private void TestLayers(String src, String fileName) { String dest = DESTINATION_FOLDER + fileName; String fieldName = "Signature1"; PdfSigner signer = new PdfSigner(new PdfReader(src), FileUtil.GetFileOutputStream(dest), new StampingProperties ()); - signer.SetFieldName(fieldName); - signer.SetPageRect(new Rectangle(250, 500, 100, 100)).SetReason("Test 1").SetLocation("TestCity").SetSignatureAppearance - (new SignatureFieldAppearance(fieldName)); + SignerProperties signerProperties = new SignerProperties().SetFieldName(fieldName).SetPageRect(new Rectangle + (250, 500, 100, 100)).SetReason("Test 1").SetLocation("TestCity").SetSignatureAppearance(new SignatureFieldAppearance + (SignerProperties.IGNORED_ID)); + signer.SetSignerProperties(signerProperties); PdfFormXObject layer0 = new PdfFormXObject(new Rectangle(0, 0, 100, 100)); // Draw pink rectangle with blue border new PdfCanvas(layer0, signer.GetDocument()).SaveState().SetFillColor(ColorConstants.PINK).SetStrokeColor(ColorConstants @@ -562,18 +459,6 @@ private void TestLayers(String src, String fileName, bool useDeprecated) { new PdfCanvas(layer2, signer.GetDocument()).SaveState().SetFillColor(ColorConstants.YELLOW).SetStrokeColor (ColorConstants.DARK_GRAY).Circle(50, 50, 50).FillStroke().RestoreState(); signer.GetSignatureField().SetBackgroundLayer(layer0).SetSignatureAppearanceLayer(layer2); - if (useDeprecated) { - // Creating the appearance - PdfSignatureAppearance appearance = signer.GetSignatureAppearance(); - PdfFormXObject deprecatedLayer0 = appearance.GetLayer0(); - // Draw yellow rectangle with gray border - new PdfCanvas(deprecatedLayer0, signer.GetDocument()).SaveState().SetFillColor(ColorConstants.YELLOW).SetStrokeColor - (ColorConstants.DARK_GRAY).Rectangle(0, 0, 100, 100).FillStroke().RestoreState(); - PdfFormXObject deprecatedLayer2 = appearance.GetLayer2(); - // Draw pink circle with blue border - new PdfCanvas(deprecatedLayer2, signer.GetDocument()).SaveState().SetFillColor(ColorConstants.PINK).SetStrokeColor - (ColorConstants.BLUE).Circle(50, 50, 50).FillStroke().RestoreState(); - } // Signing IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES @@ -581,18 +466,40 @@ private void TestLayers(String src, String fileName, bool useDeprecated) { CompareSignatureAppearances(dest, SOURCE_FOLDER + "cmp_" + fileName); } - private void TestSignatureOnRotatedPage(int pageNum, PdfSignatureAppearance.RenderingMode renderingMode, StringBuilder - assertionResults) { - String fileName = "signaturesOnRotatedPages" + pageNum + "_mode_" + renderingMode.ToString() + ".pdf"; + private void TestSignatureOnRotatedPage(int pageNum, bool useDescription, bool useSignerName, bool useImage + , StringBuilder assertionResults) { + String fileName = "signaturesOnRotatedPages" + pageNum + "_mode_"; String src = SOURCE_FOLDER + "documentWithRotatedPages.pdf"; + String signatureName = "Signature1"; + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID); + String description = "Digitally signed by Test User. All rights reserved. Take care!"; + if (useImage) { + if (useDescription) { + appearance.SetContent(description, ImageDataFactory.Create(SOURCE_FOLDER + "itext.png")); + fileName += "GRAPHIC_AND_DESCRIPTION.pdf"; + } + else { + appearance.SetContent(ImageDataFactory.Create(SOURCE_FOLDER + "itext.png")); + fileName += "GRAPHIC.pdf"; + } + } + else { + if (useSignerName) { + appearance.SetContent("signerName", description); + fileName += "NAME_AND_DESCRIPTION.pdf"; + } + else { + appearance.SetContent(description); + fileName += "DESCRIPTION.pdf"; + } + } String dest = DESTINATION_FOLDER + fileName; PdfSigner signer = new PdfSigner(new PdfReader(src), FileUtil.GetFileOutputStream(dest), new StampingProperties ().UseAppendMode()); - PdfSignatureAppearance appearance = signer.GetSignatureAppearance(); - appearance.SetLayer2Text("Digitally signed by Test User. All rights reserved. Take care!").SetPageRect(new - Rectangle(100, 100, 100, 50)).SetRenderingMode(renderingMode).SetSignatureGraphic(ImageDataFactory.Create - (SOURCE_FOLDER + "itext.png")).SetPageNumber(pageNum); - signer.SetCertificationLevel(PdfSigner.NOT_CERTIFIED); + SignerProperties signerProperties = new SignerProperties().SetFieldName(signatureName).SetPageRect(new Rectangle + (100, 100, 100, 50)).SetPageNumber(pageNum).SetSignatureAppearance(appearance).SetCertificationLevel(AccessPermissions + .UNSPECIFIED); + signer.SetSignerProperties(signerProperties); IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES ); @@ -611,22 +518,62 @@ private void TestSignatureOnRotatedPage(int pageNum, PdfSignatureAppearance.Rend } } - private void TestSignatureAppearanceAutoscale(String dest, Rectangle rect, PdfSignatureAppearance.RenderingMode - renderingMode) { + private void TestSignatureAppearanceAutoscale(String dest, Rectangle rect, String signerName, ImageData image + ) { String src = SOURCE_FOLDER + "simpleDocument.pdf"; PdfSigner signer = new PdfSigner(new PdfReader(src), FileUtil.GetFileOutputStream(dest), new StampingProperties ()); + SignerProperties signerProperties = new SignerProperties().SetFieldName("Signature1"); + signer.SetSignerProperties(signerProperties); // Creating the appearance - signer.GetSignatureAppearance().SetLayer2FontSize(0).SetReason("Test 1").SetLocation("TestCity").SetPageRect - (rect).SetRenderingMode(renderingMode).SetSignatureGraphic(ImageDataFactory.Create(SOURCE_FOLDER + "itext.png" - )); - signer.SetFieldName("Signature1"); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID); + if (image != null) { + appearance.SetContent(new SignedAppearanceText(), image); + } + else { + if (signerName != null) { + appearance.SetContent(signerName, new SignedAppearanceText()); + } + else { + appearance.SetContent(new SignedAppearanceText()); + } + } + appearance.SetFontSize(0); + signerProperties.SetReason("Test 1").SetLocation("TestCity").SetPageRect(rect).SetSignatureAppearance(appearance + ); // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES ); } +//\cond DO_NOT_DOCUMENT + internal virtual void ApplyBackgroundImage(SignatureFieldAppearance appearance, ImageData image, float imageScale + ) { + if (image != null) { + BackgroundRepeat repeat = new BackgroundRepeat(BackgroundRepeat.BackgroundRepeatValue.NO_REPEAT); + BackgroundPosition position = new BackgroundPosition().SetPositionX(BackgroundPosition.PositionX.CENTER).SetPositionY + (BackgroundPosition.PositionY.CENTER); + BackgroundSize size = new BackgroundSize(); + float EPS = 1e-5f; + if (Math.Abs(imageScale) < EPS) { + size.SetBackgroundSizeToValues(UnitValue.CreatePercentValue(100), UnitValue.CreatePercentValue(100)); + } + else { + if (imageScale < 0) { + size.SetBackgroundSizeToContain(); + } + else { + size.SetBackgroundSizeToValues(UnitValue.CreatePointValue(imageScale * image.GetWidth()), UnitValue.CreatePointValue + (imageScale * image.GetHeight())); + } + } + appearance.SetBackgroundImage(new BackgroundImage.Builder().SetImage(new PdfImageXObject(image)).SetBackgroundSize + (size).SetBackgroundRepeat(repeat).SetBackgroundPosition(position).Build()); + } + } +//\endcond + private static void AssertAppearanceFontSize(String filename, float expectedFontSize) { PdfDocument pdfDocument = new PdfDocument(new PdfReader(filename)); PdfAcroForm acroForm = PdfFormCreator.GetAcroForm(pdfDocument, false); diff --git a/itext.tests/itext.sign.tests/itext/signatures/sign/SignedAppearanceTextTest.cs b/itext.tests/itext.sign.tests/itext/signatures/sign/SignedAppearanceTextTest.cs index 751df93fcf..a085ae28a4 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/sign/SignedAppearanceTextTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/sign/SignedAppearanceTextTest.cs @@ -32,6 +32,7 @@ You should have received a copy of the GNU Affero General Public License using iText.IO.Font.Constants; using iText.IO.Image; using iText.Kernel.Colors; +using iText.Kernel.Crypto; using iText.Kernel.Font; using iText.Kernel.Geom; using iText.Kernel.Pdf; @@ -92,22 +93,47 @@ public virtual void DefaultSignedAppearanceTextTest() { String outPdf = DESTINATION_FOLDER + "defaultSignedAppearanceTextTest.pdf"; Rectangle rect = new Rectangle(36, 648, 200, 100); String fieldName = "Signature1"; - SignatureFieldAppearance appearance = new SignatureFieldAppearance(fieldName).SetContent(new SignedAppearanceText - ()); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent + (new SignedAppearanceText()); Sign(srcFile, fieldName, outPdf, "Test 1", "TestCity 1", rect, appearance); NUnit.Framework.Assert.IsNull(new CompareTool().CompareVisually(outPdf, cmpPdf, DESTINATION_FOLDER, "diff_" , GetTestMap(new Rectangle(36, 676, 200, 15)))); NUnit.Framework.Assert.IsNull(SignaturesCompareTool.CompareSignatures(outPdf, cmpPdf)); } + [NUnit.Framework.Test] + public virtual void NoReasonLocationSignDateInAppearanceTextTest() { + String srcFile = SOURCE_FOLDER + "simpleDocument.pdf"; + String cmpPdf = SOURCE_FOLDER + "cmp_noReasonLocationSignDateInAppearanceText.pdf"; + String outPdf = DESTINATION_FOLDER + "noReasonLocationSignDateInAppearanceText.pdf"; + Rectangle rect = new Rectangle(36, 648, 200, 100); + String fieldName = "Signature1"; + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent + (new SignedAppearanceText().SetReasonLine(null).SetLocationLine(null)); + PdfSigner signer = new PdfSigner(new PdfReader(srcFile), FileUtil.GetFileOutputStream(outPdf), new StampingProperties + ()); + SignerProperties signerProperties = new SignerProperties().SetCertificationLevel(AccessPermissions.UNSPECIFIED + ).SetFieldName(fieldName).SetReason("Test 1").SetLocation("TestCity 1").SetSignatureAppearance(appearance + ).SetClaimedSignDate((DateTime)TimestampConstants.UNDEFINED_TIMESTAMP_DATE).SetPageRect(rect); + signer.SetSignerProperties(signerProperties); + // Creating the signature + IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); + signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES + ); + NUnit.Framework.Assert.IsNull(new CompareTool().CompareVisually(outPdf, cmpPdf, DESTINATION_FOLDER, "diff_" + , GetTestMap(new Rectangle(36, 676, 200, 15)))); + NUnit.Framework.Assert.IsNull(SignaturesCompareTool.CompareSignatures(outPdf, cmpPdf)); + } + [NUnit.Framework.Test] public virtual void SignPDFADocumentWithoutSettingFont() { String srcFile = DESTINATION_FOLDER + "simplePDFA.pdf"; CreateSimplePDFADocument(srcFile).Close(); Rectangle rect = new Rectangle(50, 70, 400, 200); String fieldName = "Signature1"; - SignatureFieldAppearance appearance = new SignatureFieldAppearance(fieldName).SetContent(new SignedAppearanceText - ().SetSignedBy("Test").SetSignDate(DateTimeUtil.GetCurrentTime()).SetLocationLine("Test City")); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent + (new SignedAppearanceText().SetSignedBy("Test").SetSignDate(DateTimeUtil.GetCurrentTime()).SetLocationLine + ("Test City")); String outPdf = DESTINATION_FOLDER + "signPDFADocumentWithoutSettingFont.pdf"; Exception e = NUnit.Framework.Assert.Catch(typeof(Exception), () => { Sign(srcFile, fieldName, outPdf, "Test 1", "TestCity 1", rect, appearance); @@ -122,9 +148,9 @@ public virtual void SignPDFADocumentSettingBadFont() { CreateSimplePDFADocument(srcFile).Close(); Rectangle rect = new Rectangle(50, 70, 400, 200); String fieldName = "Signature1"; - SignatureFieldAppearance appearance = new SignatureFieldAppearance(fieldName).SetFont(PdfFontFactory.CreateFont - (StandardFonts.COURIER)).SetContent(new SignedAppearanceText().SetSignedBy("Test").SetSignDate(DateTimeUtil - .GetCurrentTime()).SetLocationLine("Test City")); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetFont(PdfFontFactory + .CreateFont(StandardFonts.COURIER)).SetContent(new SignedAppearanceText().SetSignedBy("Test").SetSignDate + (DateTimeUtil.GetCurrentTime()).SetLocationLine("Test City")); String outPdf = DESTINATION_FOLDER + "signPDFADocumentBadFont.pdf"; Exception e = NUnit.Framework.Assert.Catch(typeof(PdfAConformanceException), () => { Sign(srcFile, fieldName, outPdf, "Test 1", "TestCity 1", rect, appearance); @@ -146,9 +172,9 @@ public virtual void DefaultPdfATextTest() { PdfFont font = PdfFontFactory.CreateFont(FONT_FOLDER + "FreeSans.ttf", PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED ); String fieldName = "Signature1"; - SignatureFieldAppearance appearance = new SignatureFieldAppearance(fieldName).SetFont(font).SetContent(new - SignedAppearanceText().SetSignedBy("Test").SetSignDate(DateTimeUtil.GetCurrentTime()).SetLocationLine( - "Test City")); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetFont(font + ).SetContent(new SignedAppearanceText().SetSignedBy("Test").SetSignDate(DateTimeUtil.GetCurrentTime()) + .SetLocationLine("Test City")); Sign(srcFile, fieldName, outPdf, "Test 1", "TestCity 1", rect, appearance); NUnit.Framework.Assert.IsNull(new VeraPdfValidator().Validate(outPdf)); // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf\a validation on Android) @@ -175,9 +201,9 @@ public virtual void SignPdfAWithFormfieldAlreadyExistingTest() { Rectangle rect = new Rectangle(50, 200, 400, 100); PdfFont font1 = PdfFontFactory.CreateFont(FONT_FOLDER + "FreeSans.ttf", PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED ); - SignatureFieldAppearance appearance = new SignatureFieldAppearance(fieldName).SetFont(font1).SetContent(new - SignedAppearanceText().SetSignedBy("Test").SetSignDate(DateTimeUtil.GetCurrentTime()).SetLocationLine( - "Test City")); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetFont(font1 + ).SetContent(new SignedAppearanceText().SetSignedBy("Test").SetSignDate(DateTimeUtil.GetCurrentTime()) + .SetLocationLine("Test City")); Sign(srcFile, fieldName, outPdf, "Test 1", "TestCity 1", rect, appearance); NUnit.Framework.Assert.IsNull(new VeraPdfValidator().Validate(outPdf)); // Android-Conversion-Skip-Line (TODO DEVSIX-7377 introduce pdf\a validation on Android) @@ -189,7 +215,7 @@ private static Document CreateSimplePDFADocument(String filename) { String icmProfile = PDFA_FOLDER + "sRGB Color Space Profile.icm"; PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1" , FileUtil.GetInputStreamForFile(icmProfile)); - PdfDocument document = new PdfADocument(new PdfWriter(filename, writerProperties), PdfAConformanceLevel.PDF_A_4 + PdfDocument document = new PdfADocument(new PdfWriter(filename, writerProperties), PdfAConformance.PDF_A_4 , outputIntent); Document doc = new Document(document); PdfFont font = PdfFontFactory.CreateFont(FONT_FOLDER + "FreeSans.ttf", PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED @@ -206,8 +232,8 @@ public virtual void DefaultSignedAppearanceTextAndSignerTest() { String outPdf = DESTINATION_FOLDER + "defaultSignedAppearanceTextAndSignerTest.pdf"; Rectangle rect = new Rectangle(36, 648, 200, 100); String fieldName = "Signature2"; - SignatureFieldAppearance appearance = new SignatureFieldAppearance(fieldName).SetContent("", new SignedAppearanceText - ()); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent + ("", new SignedAppearanceText()); Sign(srcFile, fieldName, outPdf, "Test 2", "TestCity 2", rect, appearance); NUnit.Framework.Assert.IsNull(new CompareTool().CompareVisually(outPdf, cmpPdf, DESTINATION_FOLDER, "diff_" , GetTestMap(new Rectangle(136, 686, 100, 25)))); @@ -223,8 +249,8 @@ public virtual void DefaultSignedAppearanceTextWithImageTest() { String outPdf = DESTINATION_FOLDER + "defaultSignedAppearanceTextWithImageTest.pdf"; Rectangle rect = new Rectangle(36, 648, 300, 100); String fieldName = "Signature3"; - SignatureFieldAppearance appearance = new SignatureFieldAppearance(fieldName).SetContent(new SignedAppearanceText - (), ImageDataFactory.Create(imagePath)); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent + (new SignedAppearanceText(), ImageDataFactory.Create(imagePath)); Sign(srcFile, fieldName, outPdf, "Test 3", "TestCity 3", rect, appearance); NUnit.Framework.Assert.IsNull(new CompareTool().CompareVisually(outPdf, cmpPdf, DESTINATION_FOLDER, "diff_" , GetTestMap(new Rectangle(186, 681, 150, 36)))); @@ -240,9 +266,9 @@ public virtual void ModifiedSignedAppearanceTextTest() { String fieldName = "Signature4"; String reason = "Test 4"; String location = "TestCity 4"; - SignatureFieldAppearance appearance = new SignatureFieldAppearance(fieldName).SetContent(new SignedAppearanceText - ().SetSignedBy(" wrong signer ").SetReasonLine(" Signing reason: " + reason).SetLocationLine(" Signing location: " - + location).SetSignDate(DateTimeUtil.GetCurrentTime())); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent + (new SignedAppearanceText().SetSignedBy(" wrong signer ").SetReasonLine(" Signing reason: " + reason + ).SetLocationLine(" Signing location: " + location).SetSignDate(DateTimeUtil.GetCurrentTime())); Sign(srcFile, fieldName, outPdf, reason, location, rect, appearance); NUnit.Framework.Assert.IsNull(new CompareTool().CompareVisually(outPdf, cmpPdf, DESTINATION_FOLDER, "diff_" , GetTestMap(new Rectangle(36, 676, 200, 15)))); @@ -254,12 +280,12 @@ protected internal virtual void Sign(String src, String name, String dest, Strin PdfReader reader = new PdfReader(src); StampingProperties properties = new StampingProperties(); PdfSigner signer = new PdfSigner(reader, FileUtil.GetFileOutputStream(dest), properties); - signer.SetCertificationLevel(PdfSigner.NOT_CERTIFIED); - signer.SetFieldName(name); - signer.SetReason(reason).SetLocation(location).SetSignatureAppearance(appearance); + SignerProperties signerProperties = new SignerProperties().SetCertificationLevel(AccessPermissions.UNSPECIFIED + ).SetFieldName(name).SetReason(reason).SetLocation(location).SetSignatureAppearance(appearance); if (rectangleForNewField != null) { - signer.SetPageRect(rectangleForNewField); + signerProperties.SetPageRect(rectangleForNewField); } + signer.SetSignerProperties(signerProperties); // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES diff --git a/itext.tests/itext.sign.tests/itext/signatures/sign/SimpleSigningTest.cs b/itext.tests/itext.sign.tests/itext/signatures/sign/SimpleSigningTest.cs index b8c3cd416a..6fdf86fe33 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/sign/SimpleSigningTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/sign/SimpleSigningTest.cs @@ -25,6 +25,9 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Cert; using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Utils; +using iText.Forms.Fields.Properties; +using iText.Forms.Form.Element; +using iText.Kernel.Crypto; using iText.Kernel.Geom; using iText.Kernel.Pdf; using iText.Kernel.Utils; @@ -69,7 +72,7 @@ public virtual void PdfDocWithParagraphSigningTest() { Rectangle rect = new Rectangle(36, 648, 200, 100); String fieldName = "Signature1"; Sign(srcFile, fieldName, outPdf, chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CADES, "Test 1" - , "TestCity", rect, false, false, PdfSigner.NOT_CERTIFIED, 12f); + , "TestCity", rect, false, false, AccessPermissions.UNSPECIFIED, 12f); NUnit.Framework.Assert.IsNull(new CompareTool().CompareVisually(outPdf, cmpPdf, DESTINATION_FOLDER, "diff_" , GetTestMap(rect))); NUnit.Framework.Assert.IsNull(SignaturesCompareTool.CompareSignatures(outPdf, cmpPdf)); @@ -83,7 +86,7 @@ public virtual void SignWithoutPKeyTest() { Rectangle rect = new Rectangle(36, 648, 200, 100); String fieldName = "Signature1"; Sign(srcFile, fieldName, outPdf, chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CADES, "Test 1" - , "TestCity", rect, false, false, PdfSigner.NOT_CERTIFIED, 12f); + , "TestCity", rect, false, false, AccessPermissions.UNSPECIFIED, 12f); NUnit.Framework.Assert.IsNull(new CompareTool().CompareVisually(outPdf, cmpPdf, DESTINATION_FOLDER, "diff_" , GetTestMap(rect))); NUnit.Framework.Assert.IsNull(SignaturesCompareTool.CompareSignatures(outPdf, cmpPdf)); @@ -97,7 +100,7 @@ public virtual void SignIntoExistingFieldWithDotsTest() { Rectangle randomRect = new Rectangle(1, 1, 100, 100); String fieldName = "Signature1.1"; Sign(srcFile, fieldName, outPdf, chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CADES, "Test 1" - , "TestCity", randomRect, false, false, PdfSigner.NOT_CERTIFIED, 12f); + , "TestCity", randomRect, false, false, AccessPermissions.UNSPECIFIED, 12f); NUnit.Framework.Assert.IsNull(new CompareTool().CompareVisually(outPdf, cmpPdf, DESTINATION_FOLDER, "diff_" , GetTestMap(new Rectangle(163, 128, 430, 202)))); NUnit.Framework.Assert.IsNull(SignaturesCompareTool.CompareSignatures(outPdf, cmpPdf)); @@ -112,10 +115,11 @@ public virtual void SignWithTempFileTest() { PdfSigner signer = new PdfSigner(new PdfReader(srcFile), new PdfWriter(outPdf), DESTINATION_FOLDER + tempFileName , new StampingProperties()); Rectangle rect = new Rectangle(36, 648, 200, 100); - signer.SetCertificationLevel(PdfSigner.NOT_CERTIFIED); - signer.SetFieldName("Signature1"); + SignerProperties signerProperties = new SignerProperties().SetCertificationLevel(AccessPermissions.UNSPECIFIED + ).SetFieldName("Signature1"); + signer.SetSignerProperties(signerProperties); // Creating the appearance - CreateAppearance(signer, "Test 1", "TestCity", false, rect, 12f); + CreateAppearance(signer, "Signature1", "Test 1", "TestCity", false, rect, 12f); // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES @@ -127,18 +131,19 @@ public virtual void SignWithTempFileTest() { protected internal virtual void Sign(String src, String name, String dest, IX509Certificate[] chain, IPrivateKey pk, String digestAlgorithm, PdfSigner.CryptoStandard subfilter, String reason, String location, Rectangle - rectangleForNewField, bool setReuseAppearance, bool isAppendMode, int certificationLevel, float? fontSize - ) { + rectangleForNewField, bool setReuseAppearance, bool isAppendMode, AccessPermissions certificationLevel + , float? fontSize) { PdfReader reader = new PdfReader(src); StampingProperties properties = new StampingProperties(); if (isAppendMode) { properties.UseAppendMode(); } PdfSigner signer = new PdfSigner(reader, FileUtil.GetFileOutputStream(dest), properties); - signer.SetCertificationLevel(certificationLevel); - signer.SetFieldName(name); + SignerProperties signerProperties = new SignerProperties().SetCertificationLevel(certificationLevel).SetFieldName + (name); + signer.SetSignerProperties(signerProperties); // Creating the appearance - CreateAppearance(signer, reason, location, setReuseAppearance, rectangleForNewField, fontSize); + CreateAppearance(signer, name, reason, location, setReuseAppearance, rectangleForNewField, fontSize); // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm); signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, subfilter); @@ -150,16 +155,18 @@ private static IDictionary> GetTestMap(Rectangle ignoredAr return result; } - private static void CreateAppearance(PdfSigner signer, String reason, String location, bool setReuseAppearance - , Rectangle rectangleForNewField, float? fontSize) { - PdfSignatureAppearance appearance = signer.GetSignatureAppearance().SetReason(reason).SetLocation(location - ).SetReuseAppearance(setReuseAppearance); + private static void CreateAppearance(PdfSigner signer, String signatureName, String reason, String location + , bool setReuseAppearance, Rectangle rectangleForNewField, float? fontSize) { + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent + (new SignedAppearanceText()); + signer.GetSignerProperties().SetReason(reason).SetLocation(location).SetSignatureAppearance(appearance); if (rectangleForNewField != null) { - signer.SetPageRect(rectangleForNewField); + signer.GetSignerProperties().SetPageRect(rectangleForNewField); } if (fontSize != null) { - appearance.SetLayer2FontSize((float)fontSize); + appearance.SetFontSize((float)fontSize); } + signer.GetSignatureField().SetReuseAppearance(setReuseAppearance); } } } diff --git a/itext.tests/itext.sign.tests/itext/signatures/sign/TaggedPdfSigningTest.cs b/itext.tests/itext.sign.tests/itext/signatures/sign/TaggedPdfSigningTest.cs index 9346597276..4d684746d5 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/sign/TaggedPdfSigningTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/sign/TaggedPdfSigningTest.cs @@ -25,6 +25,9 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Cert; using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Utils; +using iText.Forms.Fields.Properties; +using iText.Forms.Form.Element; +using iText.Kernel.Crypto; using iText.Kernel.Geom; using iText.Kernel.Pdf; using iText.Kernel.Utils; @@ -95,30 +98,33 @@ protected internal virtual void Sign(String src, String name, String dest, IX509 pk, String digestAlgorithm, PdfSigner.CryptoStandard subfilter, String reason, String location, Rectangle rectangleForNewField, bool setReuseAppearance, bool isAppendMode) { Sign(src, name, dest, chain, pk, digestAlgorithm, subfilter, reason, location, rectangleForNewField, setReuseAppearance - , isAppendMode, PdfSigner.NOT_CERTIFIED, null); + , isAppendMode, AccessPermissions.UNSPECIFIED, null); } protected internal virtual void Sign(String src, String name, String dest, IX509Certificate[] chain, IPrivateKey pk, String digestAlgorithm, PdfSigner.CryptoStandard subfilter, String reason, String location, Rectangle - rectangleForNewField, bool setReuseAppearance, bool isAppendMode, int certificationLevel, float? fontSize - ) { + rectangleForNewField, bool setReuseAppearance, bool isAppendMode, AccessPermissions certificationLevel + , float? fontSize) { PdfReader reader = new PdfReader(src); StampingProperties properties = new StampingProperties(); if (isAppendMode) { properties.UseAppendMode(); } PdfSigner signer = new PdfSigner(reader, FileUtil.GetFileOutputStream(dest), properties); - signer.SetCertificationLevel(certificationLevel); + SignerProperties signerProperties = new SignerProperties().SetCertificationLevel(certificationLevel).SetFieldName + (name); + signer.SetSignerProperties(signerProperties); // Creating the appearance - PdfSignatureAppearance appearance = signer.GetSignatureAppearance().SetReason(reason).SetLocation(location - ).SetReuseAppearance(setReuseAppearance); + SignatureFieldAppearance appearance = new SignatureFieldAppearance(SignerProperties.IGNORED_ID).SetContent + (new SignedAppearanceText()); if (rectangleForNewField != null) { - appearance.SetPageRect(rectangleForNewField); + signerProperties.SetPageRect(rectangleForNewField); } if (fontSize != null) { - appearance.SetLayer2FontSize((float)fontSize); + appearance.SetFontSize((float)fontSize); } - signer.SetFieldName(name); + signerProperties.SetReason(reason).SetLocation(location).SetSignatureAppearance(appearance); + signer.GetSignatureField().SetReuseAppearance(setReuseAppearance); // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm); signer.SignDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, subfilter); diff --git a/itext.tests/itext.sign.tests/itext/signatures/sign/TimestampSigTest.cs b/itext.tests/itext.sign.tests/itext/signatures/sign/TimestampSigTest.cs index 74c131c4ec..cf04fd9bbe 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/sign/TimestampSigTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/sign/TimestampSigTest.cs @@ -72,12 +72,5 @@ public virtual void TimestampTest01() { TestSignUtils.BasicCheckSignedDoc(destinationFolder + "timestampTest01.pdf", "timestampSig1"); NUnit.Framework.Assert.IsNull(SignaturesCompareTool.CompareSignatures(outFileName, compareFile)); } - // TimeStampToken tsWrong = new TimeStampResponse(Files.readAllBytes(Paths.get("c:\\Users\\yulian\\Desktop\\myTs"))).getTimeStampToken(); - // - // JcaSimpleSignerInfoVerifierBuilder sigVerifBuilder = new JcaSimpleSignerInfoVerifierBuilder(); - // X509Certificate caCert = (X509Certificate)Pkcs12FileHelper.readFirstChain(p12FileName, password)[0]; - // SignerInformationVerifier signerInfoVerif = sigVerifBuilder.setProvider(BouncyCastleProvider.PROVIDER_NAME).build(caCert.getPublicKey()); - // boolean signatureValid = tsWrong.isSignatureValid(signerInfoVerif); - // } } diff --git a/itext.tests/itext.sign.tests/itext/signatures/sign/TwoPhaseSigningTest.cs b/itext.tests/itext.sign.tests/itext/signatures/sign/TwoPhaseSigningTest.cs index b64562c30e..93f90c7a01 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/sign/TwoPhaseSigningTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/sign/TwoPhaseSigningTest.cs @@ -31,6 +31,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Digest; using iText.Commons.Utils; using iText.IO.Source; +using iText.Kernel.Crypto; using iText.Kernel.Exceptions; using iText.Kernel.Pdf; using iText.Signatures.Cms; @@ -302,7 +303,7 @@ private byte[] PrepareDocumentAndCMS(FileInfo document, ByteArrayOutputStream pr // Phase 1.1 prepare the CMS CMSContainer cms = new CMSContainer(); SignerInfo signerInfo = new SignerInfo(); - //signerInfo.setSigningCertificateAndAddToSignedAttributes(chain[0], SecurityIDs.ID_SHA384); + //signerInfo.setSigningCertificateAndAddToSignedAttributes(chain[0], OID.ID_SHA384); signerInfo.SetSigningCertificate(chain[0]); // in the two phase scenario,; we don't have the private key! So we start from the signing certificate diff --git a/itext.tests/itext.sign.tests/itext/signatures/testutils/SignTestPortUtil.cs b/itext.tests/itext.sign.tests/itext/signatures/testutils/SignTestPortUtil.cs index 41b2c45dff..542a58424e 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/testutils/SignTestPortUtil.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/testutils/SignTestPortUtil.cs @@ -57,7 +57,7 @@ public static IOcspRequest GenerateOcspRequestWithNonce(ICertID id) { return gen.Build(); } - public static IDigest GetMessageDigest(String hashAlgorithm) { + public static IMessageDigest GetMessageDigest(String hashAlgorithm) { return FACTORY.CreateIDigest(hashAlgorithm); } diff --git a/itext.tests/itext.sign.tests/itext/signatures/testutils/SignaturesCompareTool.cs b/itext.tests/itext.sign.tests/itext/signatures/testutils/SignaturesCompareTool.cs index 57d6287592..6b0d4ba6a7 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/testutils/SignaturesCompareTool.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/testutils/SignaturesCompareTool.cs @@ -56,6 +56,8 @@ public class SignaturesCompareTool { private const String OID_OCSP_NONCE_EXTENSION = "1.3.6.1.5.5.7.48.1.2"; + private const String ID_ATTR_PDF_MAC_DATA = "1.0.32004.1.2"; + private static readonly IAsn1Dump DUMP = BOUNCY_CASTLE_FACTORY.CreateASN1Dump(); private static readonly ICollection IGNORED_OIDS; @@ -66,6 +68,7 @@ static SignaturesCompareTool() { tempSet.Add(OID_TST_INFO); tempSet.Add(OID_SIGNING_TIME); tempSet.Add(OID_OCSP_NONCE_EXTENSION); + tempSet.Add(ID_ATTR_PDF_MAC_DATA); IGNORED_OIDS = JavaCollectionsUtil.UnmodifiableSet(tempSet); } diff --git a/itext.tests/itext.sign.tests/itext/signatures/testutils/builder/TestTimestampTokenBuilder.cs b/itext.tests/itext.sign.tests/itext/signatures/testutils/builder/TestTimestampTokenBuilder.cs index d9ae17211f..8e45b8cba5 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/testutils/builder/TestTimestampTokenBuilder.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/testutils/builder/TestTimestampTokenBuilder.cs @@ -30,6 +30,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Math; using iText.Commons.Bouncycastle.Tsp; using iText.Commons.Utils; +using iText.Kernel.Crypto; namespace iText.Signatures.Testutils.Builder { public class TestTimestampTokenBuilder { diff --git a/itext.tests/itext.sign.tests/itext/signatures/testutils/client/AdvancedTestOcspClient.cs b/itext.tests/itext.sign.tests/itext/signatures/testutils/client/AdvancedTestOcspClient.cs index a8e1322eee..f06b8cccf0 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/testutils/client/AdvancedTestOcspClient.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/testutils/client/AdvancedTestOcspClient.cs @@ -42,8 +42,8 @@ public class AdvancedTestOcspClient : OcspClientBouncyCastle { private readonly IDictionary subjectNameToResponseBuilder = new LinkedDictionary (); - public AdvancedTestOcspClient(OCSPVerifier verifier) - : base(verifier) { + public AdvancedTestOcspClient() + : base() { } protected internal override Stream CreateRequestAndResponse(IX509Certificate checkCert, IX509Certificate rootCert diff --git a/itext.tests/itext.sign.tests/itext/signatures/testutils/client/TestTsaClient.cs b/itext.tests/itext.sign.tests/itext/signatures/testutils/client/TestTsaClient.cs index 7d21547297..bd2f0a1697 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/testutils/client/TestTsaClient.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/testutils/client/TestTsaClient.cs @@ -30,6 +30,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Tsp; using iText.Commons.Digest; using iText.Commons.Utils; +using iText.Kernel.Crypto; using iText.Signatures; using iText.Signatures.Testutils; using iText.Signatures.Testutils.Builder; @@ -54,8 +55,8 @@ public virtual int GetTokenSizeEstimate() { return 4096; } - public virtual IDigest GetMessageDigest() { - return (IDigest)SignTestPortUtil.GetMessageDigest(DIGEST_ALG); + public virtual IMessageDigest GetMessageDigest() { + return SignTestPortUtil.GetMessageDigest(DIGEST_ALG); } public virtual byte[] GetTimeStampToken(byte[] imprint) { diff --git a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/AssertValidationReport.cs b/itext.tests/itext.sign.tests/itext/signatures/validation/AssertValidationReport.cs similarity index 92% rename from itext.tests/itext.sign.tests/itext/signatures/validation/v1/AssertValidationReport.cs rename to itext.tests/itext.sign.tests/itext/signatures/validation/AssertValidationReport.cs index 88df2d6abe..c5dea8a100 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/AssertValidationReport.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/validation/AssertValidationReport.cs @@ -27,9 +27,9 @@ You should have received a copy of the GNU Affero General Public License using NUnit.Framework; using iText.Commons.Bouncycastle.Cert; using iText.Commons.Utils; -using iText.Signatures.Validation.V1.Report; +using iText.Signatures.Validation.Report; -namespace iText.Signatures.Validation.V1 { +namespace iText.Signatures.Validation { public class AssertValidationReport : IDisposable { private readonly ValidationReport report; @@ -41,9 +41,9 @@ private AssertValidationReport(ValidationReport report) { this.report = report; } - public static void AssertThat(ValidationReport report, Action c) { - iText.Signatures.Validation.V1.AssertValidationReport assertion = new iText.Signatures.Validation.V1.AssertValidationReport + iText.Signatures.Validation.AssertValidationReport assertion = new iText.Signatures.Validation.AssertValidationReport (report); c(assertion); assertion.DoAssert(); @@ -59,22 +59,22 @@ private void DoAssert() { } } - public virtual iText.Signatures.Validation.V1.AssertValidationReport HasNumberOfFailures(int i) { + public virtual iText.Signatures.Validation.AssertValidationReport HasNumberOfFailures(int i) { chain.SetNext(new AssertValidationReport.FailureCountCheck(i)); return this; } - public virtual iText.Signatures.Validation.V1.AssertValidationReport HasNumberOfLogs(int i) { + public virtual iText.Signatures.Validation.AssertValidationReport HasNumberOfLogs(int i) { chain.SetNext(new AssertValidationReport.LogCountCheck(i)); return this; } - public virtual iText.Signatures.Validation.V1.AssertValidationReport HasLogItem(ReportItem logItem) { + public virtual iText.Signatures.Validation.AssertValidationReport HasLogItem(ReportItem logItem) { chain.SetNext(new AssertValidationReport.LogItemCheck(logItem)); return this; } - public virtual iText.Signatures.Validation.V1.AssertValidationReport HasLogItem(Action c) { AssertValidationReport.AssertValidationReportLogItem asserter = new AssertValidationReport.AssertValidationReportLogItem (1, 1); @@ -83,8 +83,8 @@ public virtual iText.Signatures.Validation.V1.AssertValidationReport HasLogItem( return this; } - public virtual iText.Signatures.Validation.V1.AssertValidationReport HasLogItems(int minCount, int maxCount - , Action c) { + public virtual iText.Signatures.Validation.AssertValidationReport HasLogItems(int minCount, int maxCount, + Action c) { AssertValidationReport.AssertValidationReportLogItem asserter = new AssertValidationReport.AssertValidationReportLogItem (minCount, maxCount); c(asserter); @@ -92,12 +92,12 @@ public virtual iText.Signatures.Validation.V1.AssertValidationReport HasLogItems return this; } - public virtual iText.Signatures.Validation.V1.AssertValidationReport HasLogItems(int count, Action c) { return this.HasLogItems(count, count, c); } - public virtual iText.Signatures.Validation.V1.AssertValidationReport HasStatus(ValidationReport.ValidationResult + public virtual iText.Signatures.Validation.AssertValidationReport HasStatus(ValidationReport.ValidationResult expectedStatus) { chain.SetNext((new AssertValidationReport.StatusCheck(expectedStatus))); return this; diff --git a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/CRLValidatorTest.cs b/itext.tests/itext.sign.tests/itext/signatures/validation/CRLValidatorTest.cs similarity index 85% rename from itext.tests/itext.sign.tests/itext/signatures/validation/v1/CRLValidatorTest.cs rename to itext.tests/itext.sign.tests/itext/signatures/validation/CRLValidatorTest.cs index 931f6e4ff7..26f4e4c8eb 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/CRLValidatorTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/validation/CRLValidatorTest.cs @@ -31,16 +31,16 @@ You should have received a copy of the GNU Affero General Public License using iText.Signatures.Logs; using iText.Signatures.Testutils; using iText.Signatures.Testutils.Builder; -using iText.Signatures.Validation.V1.Context; -using iText.Signatures.Validation.V1.Mocks; -using iText.Signatures.Validation.V1.Report; +using iText.Signatures.Validation.Context; +using iText.Signatures.Validation.Mocks; +using iText.Signatures.Validation.Report; using iText.Test; -namespace iText.Signatures.Validation.V1 { +namespace iText.Signatures.Validation { [NUnit.Framework.Category("BouncyCastleUnitTest")] public class CRLValidatorTest : ExtendedITextTest { private static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext - .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/v1/CRLValidatorTest/"; + .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/CRLValidatorTest/"; private static readonly IBouncyCastleFactory FACTORY = BouncyCastleFactoryCreator.GetFactory(); @@ -69,8 +69,9 @@ public virtual void SetUp() { certificateRetriever = new IssuingCertificateRetriever(); SignatureValidationProperties parameters = new SignatureValidationProperties(); mockChainValidator = new MockChainValidator(); - validatorChainBuilder = new ValidatorChainBuilder().WithIssuingCertificateRetriever(certificateRetriever). - WithSignatureValidationProperties(parameters).WithCertificateChainValidator(mockChainValidator); + validatorChainBuilder = new ValidatorChainBuilder().WithIssuingCertificateRetrieverFactory(() => certificateRetriever + ).WithSignatureValidationProperties(parameters).WithCertificateChainValidatorFactory(() => mockChainValidator + ); } [NUnit.Framework.Test] @@ -82,6 +83,46 @@ public virtual void HappyPathTest() { AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.VALID)); } + [NUnit.Framework.Test] + public virtual void MultipleIssuersWithOneMatch() { + RetrieveTestResources("multipleCrlIssuerCandidates"); + byte[] crl = CreateCrl(crlIssuerCert, crlIssuerKey, TimeTestUtil.TEST_DATE_TIME.AddDays(-5), TimeTestUtil. + TEST_DATE_TIME.AddDays(+5)); + IX509Certificate candidateCrlIssuerCert1 = (IX509Certificate)PemFileHelper.ReadFirstChain(SOURCE_FOLDER + + "multipleCrlIssuerCandidates/crl-issuer-candidate1.cert.pem")[0]; + IX509Certificate candidateCrlIssuerCert2 = (IX509Certificate)PemFileHelper.ReadFirstChain(SOURCE_FOLDER + + "multipleCrlIssuerCandidates/crl-issuer-candidate2.cert.pem")[0]; + certificateRetriever.AddTrustedCertificates(JavaUtil.ArraysAsList(candidateCrlIssuerCert1, crlIssuerCert, + candidateCrlIssuerCert2)); + ValidationReport report = PerformValidation("multipleCrlIssuerCandidates", TimeTestUtil.TEST_DATE_TIME, crl + ); + AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.VALID)); + // expected the CRL validator to stop after correct issuer was found + NUnit.Framework.Assert.AreEqual(2, mockChainValidator.verificationCalls.Count); + } + + [NUnit.Framework.Test] + public virtual void MultipleIssuersWithNoMatch() { + RetrieveTestResources("multipleCrlIssuerCandidates"); + byte[] crl = CreateCrl(crlIssuerCert, crlIssuerKey, TimeTestUtil.TEST_DATE_TIME.AddDays(-5), TimeTestUtil. + TEST_DATE_TIME.AddDays(+5)); + IX509Certificate candidateCrlIssuerCert1 = (IX509Certificate)PemFileHelper.ReadFirstChain(SOURCE_FOLDER + + "multipleCrlIssuerCandidates/crl-issuer-candidate1.cert.pem")[0]; + IX509Certificate candidateCrlIssuerCert2 = (IX509Certificate)PemFileHelper.ReadFirstChain(SOURCE_FOLDER + + "multipleCrlIssuerCandidates/crl-issuer-candidate2.cert.pem")[0]; + certificateRetriever.AddTrustedCertificates(JavaUtil.ArraysAsList(candidateCrlIssuerCert1, candidateCrlIssuerCert2 + )); + IX509Certificate certificateUnderTest = (IX509Certificate)PemFileHelper.ReadFirstChain(SOURCE_FOLDER + "multipleCrlIssuerCandidates/sign.cert.pem" + )[0]; + ValidationReport result = new ValidationReport(); + ValidationContext context = new ValidationContext(ValidatorContext.REVOCATION_DATA_VALIDATOR, CertificateSource + .SIGNER_CERT, TimeBasedContext.PRESENT); + validatorChainBuilder.GetCRLValidator().Validate(result, context, certificateUnderTest, (IX509Crl)CertificateUtil + .ParseCrlFromStream(new MemoryStream(crl)), TimeTestUtil.TEST_DATE_TIME, TimeTestUtil.TEST_DATE_TIME); + AssertValidationReport.AssertThat(result, (a) => a.HasStatus(ValidationReport.ValidationResult.INDETERMINATE + )); + } + [NUnit.Framework.Test] public virtual void NextUpdateBeforeValidationTest() { RetrieveTestResources("happyPath"); @@ -206,7 +247,7 @@ public virtual void OnlySomeReasonsTest() { .SIGNER_CERT, TimeBasedContext.PRESENT); CRLValidator validator = validatorChainBuilder.GetCRLValidator(); validator.Validate(report, context, signCert, (IX509Crl)CertificateUtil.ParseCrlFromStream(new MemoryStream - (builder.MakeCrl())), TimeTestUtil.TEST_DATE_TIME); + (builder.MakeCrl())), TimeTestUtil.TEST_DATE_TIME, TimeTestUtil.TEST_DATE_TIME); AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.INDETERMINATE ).HasLogItem((al) => al.WithMessage(CRLValidator.ONLY_SOME_REASONS_CHECKED).WithCertificate(signCert)) ); @@ -227,12 +268,13 @@ public virtual void CheckLessReasonsTest() { ValidationReport report = new ValidationReport(); ValidationContext context = new ValidationContext(ValidatorContext.REVOCATION_DATA_VALIDATOR, CertificateSource .SIGNER_CERT, TimeBasedContext.PRESENT); + CRLValidator validator = validatorChainBuilder.GetCRLValidator(); // Validate full CRL. - validatorChainBuilder.GetCRLValidator().Validate(report, context, signCert, (IX509Crl)CertificateUtil.ParseCrlFromStream - (FileUtil.GetInputStreamForFile(fullCrlPath)), TimeTestUtil.TEST_DATE_TIME); + validator.Validate(report, context, signCert, (IX509Crl)CertificateUtil.ParseCrlFromStream(FileUtil.GetInputStreamForFile + (fullCrlPath)), TimeTestUtil.TEST_DATE_TIME, TimeTestUtil.TEST_DATE_TIME); // Validate CRL with onlySomeReasons. - validatorChainBuilder.GetCRLValidator().Validate(report, context, signCert, (IX509Crl)CertificateUtil.ParseCrlFromStream - (new MemoryStream(builder.MakeCrl())), TimeTestUtil.TEST_DATE_TIME); + validator.Validate(report, context, signCert, (IX509Crl)CertificateUtil.ParseCrlFromStream(new MemoryStream + (builder.MakeCrl())), TimeTestUtil.TEST_DATE_TIME, TimeTestUtil.TEST_DATE_TIME); AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.VALID)); } @@ -251,7 +293,7 @@ public virtual void RemoveFromCrlTest() { ValidationContext context = new ValidationContext(ValidatorContext.REVOCATION_DATA_VALIDATOR, CertificateSource .SIGNER_CERT, TimeBasedContext.PRESENT); validatorChainBuilder.GetCRLValidator().Validate(report, context, signCert, (IX509Crl)CertificateUtil.ParseCrlFromStream - (new MemoryStream(builder.MakeCrl())), TimeTestUtil.TEST_DATE_TIME); + (new MemoryStream(builder.MakeCrl())), TimeTestUtil.TEST_DATE_TIME, TimeTestUtil.TEST_DATE_TIME); AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.VALID).HasLogItem ((la) => la.WithCertificate(signCert).WithCheckName(CRLValidator.CRL_CHECK).WithMessage(CRLValidator.CERTIFICATE_IS_UNREVOKED ))); @@ -276,7 +318,7 @@ public virtual void FullCrlButDistributionPointWithReasonsTest() { ValidationContext context = new ValidationContext(ValidatorContext.REVOCATION_DATA_VALIDATOR, CertificateSource .SIGNER_CERT, TimeBasedContext.PRESENT); validatorChainBuilder.GetCRLValidator().Validate(report, context, cert, (IX509Crl)CertificateUtil.ParseCrlFromStream - (new MemoryStream(builder.MakeCrl())), checkDate); + (new MemoryStream(builder.MakeCrl())), checkDate, checkDate); AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.INDETERMINATE ).HasLogItem((la) => la.WithStatus(ReportItem.ReportItemStatus.INDETERMINATE).WithCertificate(cert).WithMessage (CRLValidator.ONLY_SOME_REASONS_CHECKED))); @@ -332,12 +374,12 @@ public virtual void CertificateRetrieverFailureTest() { byte[] crl = CreateCrl(crlIssuerCert, crlIssuerKey, TimeTestUtil.TEST_DATE_TIME.AddDays(-5), TimeTestUtil. TEST_DATE_TIME.AddDays(+5)); MockIssuingCertificateRetriever mockCertificateRetriever = new MockIssuingCertificateRetriever(); - mockCertificateRetriever.OngetCrlIssuerCertificatesDo((c) => { + mockCertificateRetriever.OngetCrlIssuerCertificatesByNameDo((c) => { throw new Exception("just testing"); } ); - validatorChainBuilder.WithIssuingCertificateRetriever(mockCertificateRetriever); - validatorChainBuilder.WithCRLValidator(new CRLValidator(validatorChainBuilder)); + validatorChainBuilder.WithIssuingCertificateRetrieverFactory(() => mockCertificateRetriever); + validatorChainBuilder.WithCRLValidatorFactory(() => new CRLValidator(validatorChainBuilder)); ValidationReport report = PerformValidation("happyPath", TimeTestUtil.TEST_DATE_TIME, crl); AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.INDETERMINATE ).HasLogItem((l) => l.WithMessage(CRLValidator.CRL_ISSUER_REQUEST_FAILED))); @@ -378,7 +420,7 @@ private ValidationReport CheckCrlScope(String crlPath) { ValidationContext context = new ValidationContext(ValidatorContext.REVOCATION_DATA_VALIDATOR, CertificateSource .SIGNER_CERT, TimeBasedContext.PRESENT); validatorChainBuilder.GetCRLValidator().Validate(report, context, signCert, (IX509Crl)CertificateUtil.ParseCrlFromStream - (FileUtil.GetInputStreamForFile(crlPath)), TimeTestUtil.TEST_DATE_TIME); + (FileUtil.GetInputStreamForFile(crlPath)), TimeTestUtil.TEST_DATE_TIME, TimeTestUtil.TEST_DATE_TIME); return report; } diff --git a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/CertificateChainValidatorTest.cs b/itext.tests/itext.sign.tests/itext/signatures/validation/CertificateChainValidatorTest.cs similarity index 97% rename from itext.tests/itext.sign.tests/itext/signatures/validation/v1/CertificateChainValidatorTest.cs rename to itext.tests/itext.sign.tests/itext/signatures/validation/CertificateChainValidatorTest.cs index 53e8366d2b..c2b98495a9 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/CertificateChainValidatorTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/validation/CertificateChainValidatorTest.cs @@ -24,20 +24,20 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Cert; using iText.Commons.Bouncycastle.Security; using iText.Commons.Utils; +using iText.Kernel.Crypto; using iText.Signatures; using iText.Signatures.Testutils; -using iText.Signatures.Testutils.Client; -using iText.Signatures.Validation.V1.Context; -using iText.Signatures.Validation.V1.Extensions; -using iText.Signatures.Validation.V1.Mocks; -using iText.Signatures.Validation.V1.Report; +using iText.Signatures.Validation.Context; +using iText.Signatures.Validation.Extensions; +using iText.Signatures.Validation.Mocks; +using iText.Signatures.Validation.Report; using iText.Test; -namespace iText.Signatures.Validation.V1 { +namespace iText.Signatures.Validation { [NUnit.Framework.Category("BouncyCastleUnitTest")] public class CertificateChainValidatorTest : ExtendedITextTest { private static readonly String CERTS_SRC = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext - .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/"; + .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/CertificateChainValidatorTest/"; private ValidatorChainBuilder validatorChainBuilder; @@ -55,8 +55,9 @@ public virtual void Setup() { mockRevocationDataValidator = new MockRevocationDataValidator(); properties = new SignatureValidationProperties(); certificateRetriever = new IssuingCertificateRetriever(); - validatorChainBuilder = new ValidatorChainBuilder().WithIssuingCertificateRetriever(certificateRetriever). - WithSignatureValidationProperties(properties).WithRevocationDataValidator(mockRevocationDataValidator); + validatorChainBuilder = new ValidatorChainBuilder().WithIssuingCertificateRetrieverFactory(() => certificateRetriever + ).WithSignatureValidationProperties(properties).WithRevocationDataValidatorFactory(() => mockRevocationDataValidator + ); } [NUnit.Framework.Test] @@ -524,7 +525,7 @@ public virtual void TrustStoreFailureTest() { throw new Exception("Test trust store failure"); } ); - validatorChainBuilder.WithIssuingCertificateRetriever(mockCertificateRetriever); + validatorChainBuilder.WithIssuingCertificateRetrieverFactory(() => mockCertificateRetriever); CertificateChainValidator validator = validatorChainBuilder.BuildCertificateChainValidator(); certificateRetriever.AddKnownCertificates(JavaCollectionsUtil.SingletonList(intermediateCert )); @@ -547,7 +548,7 @@ public virtual void IssuerRetrievalFailureTest() { throw new Exception("Test issuer retrieval failure"); } ); - validatorChainBuilder.WithIssuingCertificateRetriever(mockCertificateRetriever); + validatorChainBuilder.WithIssuingCertificateRetrieverFactory(() => mockCertificateRetriever); CertificateChainValidator validator = validatorChainBuilder.BuildCertificateChainValidator(); certificateRetriever.AddKnownCertificates(JavaCollectionsUtil.SingletonList(intermediateCert )); @@ -579,20 +580,6 @@ public virtual void RevocationValidationFailureTest() { ).HasLogItems(1, 10, (la) => la.WithMessage(CertificateChainValidator.REVOCATION_VALIDATION_FAILED))); } - [NUnit.Framework.Test] - public virtual void AddCrlClientPasstroughTest() { - CertificateChainValidator validator = validatorChainBuilder.BuildCertificateChainValidator(); - validator.AddCrlClient(new TestCrlClient()); - NUnit.Framework.Assert.AreEqual(1, mockRevocationDataValidator.crlClientsAdded.Count); - } - - [NUnit.Framework.Test] - public virtual void AddOcdpClientPasstroughTest() { - CertificateChainValidator validator = validatorChainBuilder.BuildCertificateChainValidator(); - validator.AddOcspClient(new TestOcspClient()); - NUnit.Framework.Assert.AreEqual(1, mockRevocationDataValidator.ocspClientsAdded.Count); - } - [NUnit.Framework.Test] public virtual void TestStopOnInvalidRevocationResultTest() { mockRevocationDataValidator.OnValidateDo((c) => c.report.AddReportItem(new ReportItem("test", "test", ReportItem.ReportItemStatus @@ -605,7 +592,7 @@ public virtual void TestStopOnInvalidRevocationResultTest() { properties.SetContinueAfterFailure(ValidatorContexts.All(), CertificateSources.All(), false); MockIssuingCertificateRetriever mockCertificateRetriever = new MockIssuingCertificateRetriever(certificateRetriever ); - validatorChainBuilder.WithIssuingCertificateRetriever(mockCertificateRetriever); + validatorChainBuilder.WithIssuingCertificateRetrieverFactory(() => mockCertificateRetriever); CertificateChainValidator validator = validatorChainBuilder.BuildCertificateChainValidator(); certificateRetriever.AddKnownCertificates(JavaCollectionsUtil.SingletonList(intermediateCert )); @@ -614,6 +601,7 @@ public virtual void TestStopOnInvalidRevocationResultTest() { ); AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.INVALID)); NUnit.Framework.Assert.AreEqual(0, mockCertificateRetriever.getCrlIssuerCertificatesCalls.Count); + NUnit.Framework.Assert.AreEqual(0, mockCertificateRetriever.getCrlIssuerCertificatesByNameCalls.Count); NUnit.Framework.Assert.AreEqual(1, mockRevocationDataValidator.calls.Count); } } diff --git a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest.cs b/itext.tests/itext.sign.tests/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest.cs similarity index 78% rename from itext.tests/itext.sign.tests/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest.cs rename to itext.tests/itext.sign.tests/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest.cs index c2d3d0f5ed..7fb6b362a1 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest.cs @@ -22,22 +22,20 @@ You should have received a copy of the GNU Affero General Public License */ using System; using System.Collections.Generic; -using System.Linq; using iText.Bouncycastleconnector; using iText.Commons.Bouncycastle; using iText.Commons.Utils; using iText.Kernel.Pdf; using iText.Signatures; -using iText.Signatures.Validation.V1.Context; -using iText.Signatures.Validation.V1.Report; +using iText.Signatures.Validation.Context; +using iText.Signatures.Validation.Report; using iText.Test; -namespace iText.Signatures.Validation.V1 { +namespace iText.Signatures.Validation { [NUnit.Framework.Category("BouncyCastleIntegrationTest")] - [NUnit.Framework.TestFixtureSource("CreateParametersTestFixtureData")] public class DocumentRevisionsValidatorIntegrationTest : ExtendedITextTest { private static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext - .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/"; + .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/"; private static readonly IBouncyCastleFactory FACTORY = BouncyCastleFactoryCreator.GetFactory(); @@ -46,37 +44,23 @@ public class DocumentRevisionsValidatorIntegrationTest : ExtendedITextTest { private readonly ValidationContext validationContext = new ValidationContext(ValidatorContext.DOCUMENT_REVISIONS_VALIDATOR , CertificateSource.SIGNER_CERT, TimeBasedContext.PRESENT); - private readonly bool continueValidationAfterFail; - [NUnit.Framework.OneTimeSetUp] public static void Before() { } - [NUnit.Framework.SetUp] - public virtual void SetUp() { + public virtual void SetUp(bool continueValidationAfterFail) { builder = new ValidatorChainBuilder(); builder.GetProperties().SetContinueAfterFailure(ValidatorContexts.All(), CertificateSources.All(), continueValidationAfterFail ); } - public DocumentRevisionsValidatorIntegrationTest(Object continueValidationAfterFail) { - this.continueValidationAfterFail = (bool)continueValidationAfterFail; - } - - public DocumentRevisionsValidatorIntegrationTest(Object[] array) - : this(array[0]) { - } - public static IEnumerable CreateParameters() { return JavaUtil.ArraysAsList(new Object[] { false }, new Object[] { true }); } - public static ICollection CreateParametersTestFixtureData() { - return CreateParameters().Select(array => new NUnit.Framework.TestFixtureData(array)).ToList(); - } - - [NUnit.Framework.Test] - public virtual void NoSignaturesDocTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void NoSignaturesDocTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "noSignaturesDoc.pdf"))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); ValidationReport report = validator.ValidateAllDocumentRevisions(validationContext, document); @@ -89,22 +73,22 @@ public virtual void NoSignaturesDocTest() { } } - [NUnit.Framework.Test] - public virtual void LinearizedDocTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void LinearizedDocTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "linearizedDoc.pdf"))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); ValidationReport report = validator.ValidateAllDocumentRevisions(validationContext, document); - AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.INDETERMINATE - ).HasNumberOfFailures(1).HasNumberOfLogs(1).HasLogItem((l) => l.WithCheckName(DocumentRevisionsValidator - .DOC_MDP_CHECK).WithMessage(DocumentRevisionsValidator.LINEARIZED_NOT_SUPPORTED).WithStatus(ReportItem.ReportItemStatus - .INDETERMINATE))); + AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.VALID).HasNumberOfFailures + (0).HasNumberOfLogs(0)); NUnit.Framework.Assert.AreEqual(AccessPermissions.ANNOTATION_MODIFICATION, validator.GetAccessPermissions( )); } } - [NUnit.Framework.Test] - public virtual void MultipleRevisionsDocumentWithoutPermissionsTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void MultipleRevisionsDocumentWithoutPermissionsTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "multipleRevisionsDocumentWithoutPermissions.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -115,8 +99,9 @@ public virtual void MultipleRevisionsDocumentWithoutPermissionsTest() { } } - [NUnit.Framework.Test] - public virtual void MultipleRevisionsDocumentWithPermissionsTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void MultipleRevisionsDocumentWithPermissionsTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "multipleRevisionsDocumentWithPermissions.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -127,8 +112,20 @@ public virtual void MultipleRevisionsDocumentWithPermissionsTest() { } } - [NUnit.Framework.Test] - public virtual void TwoCertificationSignaturesTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void EolNotIncludedIntoByteRangeTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); + using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "eolNotIncludedIntoByteRange.pdf" + ))) { + DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); + ValidationReport report = validator.ValidateAllDocumentRevisions(validationContext, document); + AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.VALID)); + } + } + + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void TwoCertificationSignaturesTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "twoCertificationSignatures.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -151,8 +148,9 @@ public virtual void TwoCertificationSignaturesTest() { } } - [NUnit.Framework.Test] - public virtual void SignatureNotFoundTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void SignatureNotFoundTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "signatureNotFound.pdf"))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); ValidationReport report = validator.ValidateAllDocumentRevisions(validationContext, document); @@ -165,8 +163,9 @@ public virtual void SignatureNotFoundTest() { } } - [NUnit.Framework.Test] - public virtual void DifferentFieldLockLevelsTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void DifferentFieldLockLevelsTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "differentFieldLockLevels.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -180,8 +179,9 @@ public virtual void DifferentFieldLockLevelsTest() { } } - [NUnit.Framework.Test] - public virtual void FieldLockLevelIncreaseTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void FieldLockLevelIncreaseTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "fieldLockLevelIncrease.pdf")) ) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -195,20 +195,25 @@ public virtual void FieldLockLevelIncreaseTest() { } } - [NUnit.Framework.Test] - public virtual void CertificationSignatureAfterApprovalTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void CertificationSignatureAfterApprovalTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "certificationSignatureAfterApproval.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); ValidationReport report = validator.ValidateAllDocumentRevisions(validationContext, document); - AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.VALID)); + AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.INDETERMINATE + ).HasNumberOfFailures(1).HasLogItem((l) => l.WithCheckName(DocumentRevisionsValidator.DOC_MDP_CHECK).WithMessage + (DocumentRevisionsValidator.NOT_ALLOWED_CERTIFICATION_SIGNATURE).WithStatus(ReportItem.ReportItemStatus + .INDETERMINATE))); NUnit.Framework.Assert.AreEqual(AccessPermissions.FORM_FIELDS_MODIFICATION, validator.GetAccessPermissions ()); } } - [NUnit.Framework.Test] - public virtual void FieldLockChildModificationAllowedTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void FieldLockChildModificationAllowedTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "fieldLockChildModificationAllowed.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -217,8 +222,9 @@ public virtual void FieldLockChildModificationAllowedTest() { } } - [NUnit.Framework.Test] - public virtual void FieldLockChildModificationNotAllowedTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void FieldLockChildModificationNotAllowedTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "fieldLockChildModificationNotAllowed.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -230,8 +236,9 @@ public virtual void FieldLockChildModificationNotAllowedTest() { } } - [NUnit.Framework.Test] - public virtual void FieldLockRootModificationAllowedTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void FieldLockRootModificationAllowedTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "fieldLockRootModificationAllowed.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -240,8 +247,9 @@ public virtual void FieldLockRootModificationAllowedTest() { } } - [NUnit.Framework.Test] - public virtual void FieldLockRootModificationNotAllowedTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void FieldLockRootModificationNotAllowedTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "fieldLockRootModificationNotAllowed.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -253,8 +261,9 @@ public virtual void FieldLockRootModificationNotAllowedTest() { } } - [NUnit.Framework.Test] - public virtual void FieldLockSequentialExcludeValuesTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void FieldLockSequentialExcludeValuesTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "fieldLockSequentialExcludeValues.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -266,8 +275,9 @@ public virtual void FieldLockSequentialExcludeValuesTest() { } } - [NUnit.Framework.Test] - public virtual void FieldLockSequentialIncludeValuesTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void FieldLockSequentialIncludeValuesTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "fieldLockSequentialIncludeValues.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -288,8 +298,9 @@ public virtual void FieldLockSequentialIncludeValuesTest() { } } - [NUnit.Framework.Test] - public virtual void FieldLockKidsRemovedAndAddedTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void FieldLockKidsRemovedAndAddedTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "fieldLockKidsRemovedAndAdded.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -310,8 +321,9 @@ public virtual void FieldLockKidsRemovedAndAddedTest() { } } - [NUnit.Framework.Test] - public virtual void PageAndParentIndirectReferenceModifiedTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void PageAndParentIndirectReferenceModifiedTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "pageAndParentIndirectReferenceModified.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -323,8 +335,9 @@ public virtual void PageAndParentIndirectReferenceModifiedTest() { } } - [NUnit.Framework.Test] - public virtual void LockedSignatureFieldModifiedTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void LockedSignatureFieldModifiedTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "lockedSignatureFieldModified.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -336,8 +349,9 @@ public virtual void LockedSignatureFieldModifiedTest() { } } - [NUnit.Framework.Test] - public virtual void LockedFieldRemoveAddKidsEntryTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void LockedFieldRemoveAddKidsEntryTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "lockedFieldRemoveAddKidsEntry.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -358,8 +372,9 @@ public virtual void LockedFieldRemoveAddKidsEntryTest() { } } - [NUnit.Framework.Test] - public virtual void RemovedLockedFieldTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void RemovedLockedFieldTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "removedLockedField.pdf"))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); ValidationReport report = validator.ValidateAllDocumentRevisions(validationContext, document); @@ -370,8 +385,9 @@ public virtual void RemovedLockedFieldTest() { } } - [NUnit.Framework.Test] - public virtual void DanglingWidgetAnnotationTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void DanglingWidgetAnnotationTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "danglingWidgetAnnotation.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -386,8 +402,9 @@ public virtual void DanglingWidgetAnnotationTest() { } } - [NUnit.Framework.Test] - public virtual void RemoveAllThePageAnnotationsTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void RemoveAllThePageAnnotationsTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "removeAllAnnots.pdf"))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); ValidationReport report = validator.ValidateAllDocumentRevisions(validationContext, document); @@ -398,8 +415,9 @@ public virtual void RemoveAllThePageAnnotationsTest() { } } - [NUnit.Framework.Test] - public virtual void RemoveAllTheFieldAnnotationsTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void RemoveAllTheFieldAnnotationsTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "removeFieldAnnots.pdf"))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); ValidationReport report = validator.ValidateAllDocumentRevisions(validationContext, document); @@ -410,8 +428,9 @@ public virtual void RemoveAllTheFieldAnnotationsTest() { } } - [NUnit.Framework.Test] - public virtual void SimpleTaggedDocTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void SimpleTaggedDocTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "simpleTaggedDoc.pdf"))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); ValidationReport report = validator.ValidateAllDocumentRevisions(validationContext, document); @@ -420,8 +439,9 @@ public virtual void SimpleTaggedDocTest() { } } - [NUnit.Framework.Test] - public virtual void TaggedDocAddAndRemoveAnnotationsTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void TaggedDocAddAndRemoveAnnotationsTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "taggedDocAddAndRemoveAnnotations.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -435,8 +455,9 @@ public virtual void TaggedDocAddAndRemoveAnnotationsTest() { } } - [NUnit.Framework.Test] - public virtual void TaggedDocRemoveStructTreeElementTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void TaggedDocRemoveStructTreeElementTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "taggedDocRemoveStructTreeElement.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -447,8 +468,31 @@ public virtual void TaggedDocRemoveStructTreeElementTest() { } } - [NUnit.Framework.Test] - public virtual void TaggedDocRemoveStructTreeAnnotationTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void OutlinesNotModifiedTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); + using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "outlinesNotModified.pdf"))) { + DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); + ValidationReport report = validator.ValidateAllDocumentRevisions(validationContext, document); + AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.VALID)); + } + } + + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void OutlinesModifiedTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); + using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "outlinesModified.pdf"))) { + DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); + ValidationReport report = validator.ValidateAllDocumentRevisions(validationContext, document); + AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.INVALID).HasNumberOfFailures + (1).HasLogItem((l) => l.WithCheckName(DocumentRevisionsValidator.DOC_MDP_CHECK).WithMessage(DocumentRevisionsValidator + .NOT_ALLOWED_CATALOG_CHANGES).WithStatus(ReportItem.ReportItemStatus.INVALID))); + } + } + + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void TaggedDocRemoveStructTreeAnnotationTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "taggedDocRemoveStructTreeAnnotation.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -459,8 +503,9 @@ public virtual void TaggedDocRemoveStructTreeAnnotationTest() { } } - [NUnit.Framework.Test] - public virtual void TaggedDocModifyAnnotationTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void TaggedDocModifyAnnotationTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "taggedDocModifyAnnotation.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -470,8 +515,9 @@ public virtual void TaggedDocModifyAnnotationTest() { } } - [NUnit.Framework.Test] - public virtual void TaggedDocModifyAnnotationAndStructElementTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void TaggedDocModifyAnnotationAndStructElementTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "taggedDocModifyAnnotationAndStructElement.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -484,8 +530,9 @@ public virtual void TaggedDocModifyAnnotationAndStructElementTest() { } } - [NUnit.Framework.Test] - public virtual void TaggedDocModifyAnnotationAndStructContentTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void TaggedDocModifyAnnotationAndStructContentTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "taggedDocModifyAnnotationAndStructContent.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -495,8 +542,9 @@ public virtual void TaggedDocModifyAnnotationAndStructContentTest() { } } - [NUnit.Framework.Test] - public virtual void TaggedDocModifyStructElementTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void TaggedDocModifyStructElementTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "taggedDocModifyStructElement.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -509,8 +557,9 @@ public virtual void TaggedDocModifyStructElementTest() { } } - [NUnit.Framework.Test] - public virtual void RemoveUnnamedFieldTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void RemoveUnnamedFieldTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "removeUnnamedField.pdf"))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); ValidationReport report = validator.ValidateAllDocumentRevisions(validationContext, document); @@ -525,8 +574,9 @@ public virtual void RemoveUnnamedFieldTest() { } } - [NUnit.Framework.Test] - public virtual void FullCompressionModeLevel1Test() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void FullCompressionModeLevel1Test(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "fullCompressionModeLevel1.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -537,8 +587,9 @@ public virtual void FullCompressionModeLevel1Test() { } } - [NUnit.Framework.Test] - public virtual void FullCompressionModeLevel2Test() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void FullCompressionModeLevel2Test(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "fullCompressionModeLevel2.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -550,8 +601,9 @@ public virtual void FullCompressionModeLevel2Test() { } } - [NUnit.Framework.Test] - public virtual void FullCompressionModeLevel3Test() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void FullCompressionModeLevel3Test(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "fullCompressionModeLevel3.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -562,5 +614,15 @@ public virtual void FullCompressionModeLevel3Test() { (0).HasNumberOfLogs(0)); } } + + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void PdfVersionAddedTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); + using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "pdfVersionAdded.pdf"))) { + DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); + ValidationReport report = validator.ValidateAllDocumentRevisions(validationContext, document); + AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.VALID)); + } + } } } diff --git a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/DocumentRevisionsValidatorTest.cs b/itext.tests/itext.sign.tests/itext/signatures/validation/DocumentRevisionsValidatorTest.cs similarity index 81% rename from itext.tests/itext.sign.tests/itext/signatures/validation/v1/DocumentRevisionsValidatorTest.cs rename to itext.tests/itext.sign.tests/itext/signatures/validation/DocumentRevisionsValidatorTest.cs index ef822edb58..d1142d4072 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/DocumentRevisionsValidatorTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/validation/DocumentRevisionsValidatorTest.cs @@ -22,22 +22,20 @@ You should have received a copy of the GNU Affero General Public License */ using System; using System.Collections.Generic; -using System.Linq; using iText.Bouncycastleconnector; using iText.Commons.Bouncycastle; using iText.Commons.Utils; using iText.Kernel.Pdf; using iText.Signatures; -using iText.Signatures.Validation.V1.Context; -using iText.Signatures.Validation.V1.Report; +using iText.Signatures.Validation.Context; +using iText.Signatures.Validation.Report; using iText.Test; -namespace iText.Signatures.Validation.V1 { +namespace iText.Signatures.Validation { [NUnit.Framework.Category("BouncyCastleUnitTest")] - [NUnit.Framework.TestFixtureSource("CreateParametersTestFixtureData")] public class DocumentRevisionsValidatorTest : ExtendedITextTest { private static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext - .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/"; + .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/"; private static readonly IBouncyCastleFactory FACTORY = BouncyCastleFactoryCreator.GetFactory(); @@ -46,37 +44,23 @@ public class DocumentRevisionsValidatorTest : ExtendedITextTest { private readonly ValidationContext validationContext = new ValidationContext(ValidatorContext.DOCUMENT_REVISIONS_VALIDATOR , CertificateSource.SIGNER_CERT, TimeBasedContext.PRESENT); - private readonly bool continueValidationAfterFail; - [NUnit.Framework.OneTimeSetUp] public static void Before() { } - [NUnit.Framework.SetUp] - public virtual void SetUp() { + public virtual void SetUp(bool continueValidationAfterFail) { builder = new ValidatorChainBuilder(); builder.GetProperties().SetContinueAfterFailure(ValidatorContexts.All(), CertificateSources.All(), continueValidationAfterFail ); } - public DocumentRevisionsValidatorTest(Object continueValidationAfterFail) { - this.continueValidationAfterFail = (bool)continueValidationAfterFail; - } - - public DocumentRevisionsValidatorTest(Object[] array) - : this(array[0]) { - } - public static IEnumerable CreateParameters() { return JavaUtil.ArraysAsList(new Object[] { false }, new Object[] { true }); } - public static ICollection CreateParametersTestFixtureData() { - return CreateParameters().Select(array => new NUnit.Framework.TestFixtureData(array)).ToList(); - } - - [NUnit.Framework.Test] - public virtual void MultipleRevisionsDocumentLevel1Test() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void MultipleRevisionsDocumentLevel1Test(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "multipleRevisionsDocument.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -101,8 +85,9 @@ public virtual void MultipleRevisionsDocumentLevel1Test() { } } - [NUnit.Framework.Test] - public virtual void HugeDocumentTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void HugeDocumentTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "hugeDocument.pdf"))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); validator.SetAccessPermissions(AccessPermissions.NO_CHANGES_PERMITTED); @@ -116,8 +101,9 @@ public virtual void HugeDocumentTest() { } } - [NUnit.Framework.Test] - public virtual void ExtensionsModificationsTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void ExtensionsModificationsTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "extensionsModifications.pdf") )) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -160,8 +146,9 @@ public virtual void ExtensionsModificationsTest() { } } - [NUnit.Framework.Test] - public virtual void CompletelyInvalidDocumentTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void CompletelyInvalidDocumentTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "completelyInvalidDocument.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -178,8 +165,9 @@ public virtual void CompletelyInvalidDocumentTest() { } } - [NUnit.Framework.Test] - public virtual void MakeFontDirectAndIndirectTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void MakeFontDirectAndIndirectTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "makeFontDirectAndIndirect.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -209,8 +197,9 @@ public virtual void MakeFontDirectAndIndirectTest() { } } - [NUnit.Framework.Test] - public virtual void RandomEntryAddedTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void RandomEntryAddedTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "randomEntryAdded.pdf"))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); validator.SetAccessPermissions(AccessPermissions.NO_CHANGES_PERMITTED); @@ -227,8 +216,9 @@ public virtual void RandomEntryAddedTest() { } } - [NUnit.Framework.Test] - public virtual void RandomEntryWithoutUsageTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void RandomEntryWithoutUsageTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "randomEntryWithoutUsage.pdf") )) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator().SetAccessPermissions(AccessPermissions @@ -246,8 +236,9 @@ public virtual void RandomEntryWithoutUsageTest() { } } - [NUnit.Framework.Test] - public virtual void ChangeExistingFontTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void ChangeExistingFontTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "changeExistingFont.pdf"))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); validator.SetAccessPermissions(AccessPermissions.NO_CHANGES_PERMITTED); @@ -263,8 +254,9 @@ public virtual void ChangeExistingFontTest() { } } - [NUnit.Framework.Test] - public virtual void ChangeExistingFontAndAddAsDssTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void ChangeExistingFontAndAddAsDssTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "changeExistingFontAndAddAsDss.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -282,8 +274,9 @@ public virtual void ChangeExistingFontAndAddAsDssTest() { } } - [NUnit.Framework.Test] - public virtual void FillInFieldAtLevel1Test() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void FillInFieldAtLevel1Test(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "fillInField.pdf"))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); validator.SetAccessPermissions(AccessPermissions.NO_CHANGES_PERMITTED); @@ -301,8 +294,9 @@ public virtual void FillInFieldAtLevel1Test() { } } - [NUnit.Framework.Test] - public virtual void MultipleRevisionsDocumentLevel2Test() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void MultipleRevisionsDocumentLevel2Test(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "multipleRevisionsDocument2.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -330,8 +324,9 @@ public virtual void MultipleRevisionsDocumentLevel2Test() { } } - [NUnit.Framework.Test] - public virtual void RemovePermissionsTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void RemovePermissionsTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "removePermissions.pdf"))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); validator.SetAccessPermissions(AccessPermissions.FORM_FIELDS_MODIFICATION); @@ -348,8 +343,9 @@ public virtual void RemovePermissionsTest() { } } - [NUnit.Framework.Test] - public virtual void RemoveDSSTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void RemoveDSSTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "removeDSS.pdf"))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); validator.SetAccessPermissions(AccessPermissions.FORM_FIELDS_MODIFICATION); @@ -366,8 +362,9 @@ public virtual void RemoveDSSTest() { } } - [NUnit.Framework.Test] - public virtual void RemoveAcroformTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void RemoveAcroformTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "removeAcroform.pdf"))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); validator.SetAccessPermissions(AccessPermissions.FORM_FIELDS_MODIFICATION); @@ -384,8 +381,9 @@ public virtual void RemoveAcroformTest() { } } - [NUnit.Framework.Test] - public virtual void RemoveFieldTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void RemoveFieldTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "removeField.pdf"))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); validator.SetAccessPermissions(AccessPermissions.FORM_FIELDS_MODIFICATION); @@ -402,8 +400,9 @@ public virtual void RemoveFieldTest() { } } - [NUnit.Framework.Test] - public virtual void RenameFieldTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void RenameFieldTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "renameField.pdf"))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); validator.SetAccessPermissions(AccessPermissions.FORM_FIELDS_MODIFICATION); @@ -421,8 +420,9 @@ public virtual void RenameFieldTest() { } } - [NUnit.Framework.Test] - public virtual void AddTextFieldTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void AddTextFieldTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "addTextField.pdf"))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); validator.SetAccessPermissions(AccessPermissions.FORM_FIELDS_MODIFICATION); @@ -441,8 +441,9 @@ public virtual void AddTextFieldTest() { } } - [NUnit.Framework.Test] - public virtual void AddUnsignedSignatureFieldTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void AddUnsignedSignatureFieldTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "addUnsignedSignatureField.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -462,8 +463,9 @@ public virtual void AddUnsignedSignatureFieldTest() { } } - [NUnit.Framework.Test] - public virtual void BrokenSignatureFieldDictionaryTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void BrokenSignatureFieldDictionaryTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "brokenSignatureFieldDictionary.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); @@ -484,8 +486,9 @@ public virtual void BrokenSignatureFieldDictionaryTest() { } } - [NUnit.Framework.Test] - public virtual void ModifyPageAnnotsTest() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void ModifyPageAnnotsTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "modifyPageAnnots.pdf"))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); validator.SetAccessPermissions(AccessPermissions.FORM_FIELDS_MODIFICATION); @@ -502,8 +505,66 @@ public virtual void ModifyPageAnnotsTest() { } } - [NUnit.Framework.Test] - public virtual void MultipleRevisionsDocumentLevel3Test() { + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void GotoReferencesModifiedStructTreeElemTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); + using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "gotoReferencesModifiedStructTreeElem.pdf" + ))) { + DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); + validator.SetAccessPermissions(AccessPermissions.FORM_FIELDS_MODIFICATION); + PdfRevisionsReader revisionsReader = new PdfRevisionsReader(document.GetReader()); + IList documentRevisions = revisionsReader.GetAllRevisions(); + ValidationReport validationReport = new ValidationReport(); + validator.ValidateRevision(documentRevisions[documentRevisions.Count - 2], documentRevisions[documentRevisions + .Count - 1], document, validationReport, validationContext); + AssertValidationReport.AssertThat(validationReport, (a) => a.HasStatus(ValidationReport.ValidationResult.VALID + )); + } + } + + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void CatalogReferenceInRandomPlaceTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); + using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "catalogReferenceInRandomPlace.pdf" + ))) { + DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); + validator.SetAccessPermissions(AccessPermissions.FORM_FIELDS_MODIFICATION); + PdfRevisionsReader revisionsReader = new PdfRevisionsReader(document.GetReader()); + IList documentRevisions = revisionsReader.GetAllRevisions(); + ValidationReport validationReport = new ValidationReport(); + validator.ValidateRevision(documentRevisions[documentRevisions.Count - 2], documentRevisions[documentRevisions + .Count - 1], document, validationReport, validationContext); + AssertValidationReport.AssertThat(validationReport, (a) => a.HasStatus(ValidationReport.ValidationResult.VALID + )); + validator.ValidateRevision(documentRevisions[documentRevisions.Count - 3], documentRevisions[documentRevisions + .Count - 2], document, validationReport, validationContext); + AssertValidationReport.AssertThat(validationReport, (a) => a.HasStatus(ValidationReport.ValidationResult.VALID + )); + } + } + + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void CatalogReferenceInRandomPlaceModifiedTest(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); + using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "catalogReferenceInRandomPlaceModified.pdf" + ))) { + DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); + validator.SetAccessPermissions(AccessPermissions.FORM_FIELDS_MODIFICATION); + PdfRevisionsReader revisionsReader = new PdfRevisionsReader(document.GetReader()); + IList documentRevisions = revisionsReader.GetAllRevisions(); + ValidationReport validationReport = new ValidationReport(); + validator.ValidateRevision(documentRevisions[documentRevisions.Count - 2], documentRevisions[documentRevisions + .Count - 1], document, validationReport, validationContext); + AssertValidationReport.AssertThat(validationReport, (a) => a.HasStatus(ValidationReport.ValidationResult.INVALID + ).HasNumberOfFailures(1).HasNumberOfLogs(1).HasLogItem((l) => l.WithCheckName(DocumentRevisionsValidator + .DOC_MDP_CHECK).WithMessage(DocumentRevisionsValidator.PAGE_MODIFIED).WithStatus(ReportItem.ReportItemStatus + .INVALID))); + } + } + + [NUnit.Framework.TestCaseSource("CreateParameters")] + public virtual void MultipleRevisionsDocumentLevel3Test(bool continueValidationAfterFail) { + SetUp(continueValidationAfterFail); using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "multipleRevisionsDocument3.pdf" ))) { DocumentRevisionsValidator validator = builder.BuildDocumentRevisionsValidator(); diff --git a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/OCSPValidatorIntegrationTest.cs b/itext.tests/itext.sign.tests/itext/signatures/validation/OCSPValidatorIntegrationTest.cs similarity index 93% rename from itext.tests/itext.sign.tests/itext/signatures/validation/v1/OCSPValidatorIntegrationTest.cs rename to itext.tests/itext.sign.tests/itext/signatures/validation/OCSPValidatorIntegrationTest.cs index f3f893cfe5..c258d771bb 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/OCSPValidatorIntegrationTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/validation/OCSPValidatorIntegrationTest.cs @@ -27,19 +27,20 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Cert; using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Utils; +using iText.Kernel.Crypto; using iText.Signatures; using iText.Signatures.Testutils; using iText.Signatures.Testutils.Builder; using iText.Signatures.Testutils.Client; -using iText.Signatures.Validation.V1.Context; -using iText.Signatures.Validation.V1.Report; +using iText.Signatures.Validation.Context; +using iText.Signatures.Validation.Report; using iText.Test; -namespace iText.Signatures.Validation.V1 { +namespace iText.Signatures.Validation { [NUnit.Framework.Category("BouncyCastleUnitTest")] public class OCSPValidatorIntegrationTest : ExtendedITextTest { private static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext - .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/v1/OCSPValidatorTest/"; + .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/OCSPValidatorTest/"; private static readonly IBouncyCastleFactory FACTORY = BouncyCastleFactoryCreator.GetFactory(); @@ -80,8 +81,8 @@ public static void Before() { public virtual void SetUp() { certificateRetriever = new IssuingCertificateRetriever(); parameters = new SignatureValidationProperties(); - validatorChainBuilder = new ValidatorChainBuilder().WithSignatureValidationProperties(parameters).WithIssuingCertificateRetriever - (certificateRetriever); + validatorChainBuilder = new ValidatorChainBuilder().WithSignatureValidationProperties(parameters).WithIssuingCertificateRetrieverFactory + (() => certificateRetriever); } [NUnit.Framework.Test] @@ -98,10 +99,11 @@ public virtual void ValidateResponderOcspNoCheckTest() { [NUnit.Framework.Test] public virtual void ValidateAuthorizedOCSPResponderWithOcspTest() { ValidationReport report = VerifyResponderWithOcsp(false); - AssertValidationReport.AssertThat(report, (a) => a.HasNumberOfFailures(0).HasNumberOfLogs(2).HasLogItems(2 - , (al) => al.WithCheckName(CertificateChainValidator.CERTIFICATE_CHECK).WithMessage(CertificateChainValidator - .CERTIFICATE_TRUSTED, (l) => ((CertificateReportItem)l).GetCertificate().GetSubjectDN())).HasStatus(ValidationReport.ValidationResult - .VALID)); + AssertValidationReport.AssertThat(report, (a) => a.HasNumberOfFailures(0).HasNumberOfLogs(2).HasLogItem((al + ) => al.WithCheckName(CertificateChainValidator.CERTIFICATE_CHECK).WithMessage(CertificateChainValidator + .CERTIFICATE_TRUSTED, (l) => ((CertificateReportItem)l).GetCertificate().GetSubjectDN())).HasLogItem(( + al) => al.WithCheckName(OCSPValidator.OCSP_CHECK).WithMessage(OCSPValidator.OCSP_RESPONDER_IS_CA)).HasStatus + (ValidationReport.ValidationResult.VALID)); } [NUnit.Framework.Test] @@ -222,8 +224,10 @@ private ValidationReport VerifyResponderWithOcsp(bool revokedOcsp) { if (revokedOcsp) { parameters.SetContinueAfterFailure(ValidatorContexts.All(), CertificateSources.All(), false); } - validatorChainBuilder.GetRevocationDataValidator().AddOcspClient(ocspClient); - validatorChainBuilder.GetRevocationDataValidator().AddOcspClient(ocspClient2); + RevocationDataValidator revocationDataValidator = validatorChainBuilder.GetRevocationDataValidator(); + revocationDataValidator.AddOcspClient(ocspClient); + revocationDataValidator.AddOcspClient(ocspClient2); + validatorChainBuilder.WithRevocationDataValidatorFactory(() => revocationDataValidator); OCSPValidator validator = validatorChainBuilder.BuildOCSPValidator(); validator.Validate(report, baseContext, checkCert, basicOCSPResp.GetResponses()[0], basicOCSPResp, checkDate , checkDate); diff --git a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/OCSPValidatorTest.cs b/itext.tests/itext.sign.tests/itext/signatures/validation/OCSPValidatorTest.cs similarity index 87% rename from itext.tests/itext.sign.tests/itext/signatures/validation/v1/OCSPValidatorTest.cs rename to itext.tests/itext.sign.tests/itext/signatures/validation/OCSPValidatorTest.cs index bdfe2fd09f..def5ead493 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/OCSPValidatorTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/validation/OCSPValidatorTest.cs @@ -21,6 +21,7 @@ You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ using System; +using System.Collections.Generic; using iText.Bouncycastleconnector; using iText.Commons.Bouncycastle; using iText.Commons.Bouncycastle.Asn1.Ocsp; @@ -32,16 +33,16 @@ You should have received a copy of the GNU Affero General Public License using iText.Signatures.Testutils; using iText.Signatures.Testutils.Builder; using iText.Signatures.Testutils.Client; -using iText.Signatures.Validation.V1.Context; -using iText.Signatures.Validation.V1.Mocks; -using iText.Signatures.Validation.V1.Report; +using iText.Signatures.Validation.Context; +using iText.Signatures.Validation.Mocks; +using iText.Signatures.Validation.Report; using iText.Test; -namespace iText.Signatures.Validation.V1 { +namespace iText.Signatures.Validation { [NUnit.Framework.Category("BouncyCastleUnitTest")] public class OCSPValidatorTest : ExtendedITextTest { private static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext - .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/v1/OCSPValidatorTest/"; + .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/OCSPValidatorTest/"; private static readonly IBouncyCastleFactory FACTORY = BouncyCastleFactoryCreator.GetFactory(); @@ -85,8 +86,8 @@ public virtual void SetUp() { certificateRetriever = new IssuingCertificateRetriever(); parameters = new SignatureValidationProperties(); mockCertificateChainValidator = new MockChainValidator(); - validatorChainBuilder = new ValidatorChainBuilder().WithSignatureValidationProperties(parameters).WithIssuingCertificateRetriever - (certificateRetriever).WithCertificateChainValidator(mockCertificateChainValidator); + validatorChainBuilder = new ValidatorChainBuilder().WithSignatureValidationProperties(parameters).WithIssuingCertificateRetrieverFactory + (() => certificateRetriever).WithCertificateChainValidatorFactory(() => mockCertificateChainValidator); } [NUnit.Framework.Test] @@ -96,6 +97,49 @@ public virtual void HappyPathTest() { AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.VALID)); } + [NUnit.Framework.Test] + public virtual void MultipleIssuerCandidatesHappyPathTest() { + IX509Certificate candidateOcspIssuerCert1 = (IX509Certificate)PemFileHelper.ReadFirstChain(SOURCE_FOLDER + + "candidate1-ocsp-issuer.cert.pem")[0]; + IX509Certificate candidateOcspIssuerCert2 = (IX509Certificate)PemFileHelper.ReadFirstChain(SOURCE_FOLDER + + "candidate2-ocsp-issuer.cert.pem")[0]; + certificateRetriever.AddTrustedCertificates(JavaUtil.ArraysAsList(candidateOcspIssuerCert1, responderCert, + candidateOcspIssuerCert2)); + TestOcspResponseBuilder builder = new TestOcspResponseBuilder(responderCert, ocspRespPrivateKey); + builder.SetOcspCertsChain(new IX509Certificate[] { caCert }); + TestOcspClient ocspClient = new TestOcspClient().AddBuilderForCertIssuer(caCert, builder); + IBasicOcspResponse basicOCSPResp = FACTORY.CreateBasicOCSPResponse(FACTORY.CreateASN1Primitive(ocspClient. + GetEncoded(checkCert, caCert, null))); + ValidationReport report = new ValidationReport(); + certificateRetriever.AddTrustedCertificates(JavaCollectionsUtil.SingletonList(caCert)); + OCSPValidator validator = validatorChainBuilder.BuildOCSPValidator(); + validator.Validate(report, baseContext, checkCert, basicOCSPResp.GetResponses()[0], basicOCSPResp, TimeTestUtil + .TEST_DATE_TIME, TimeTestUtil.TEST_DATE_TIME); + AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.VALID)); + } + + [NUnit.Framework.Test] + public virtual void MultipleIssuerCandidatesFailingTest() { + IX509Certificate candidateOcspIssuerCert1 = (IX509Certificate)PemFileHelper.ReadFirstChain(SOURCE_FOLDER + + "candidate1-ocsp-issuer.cert.pem")[0]; + IX509Certificate candidateOcspIssuerCert2 = (IX509Certificate)PemFileHelper.ReadFirstChain(SOURCE_FOLDER + + "candidate2-ocsp-issuer.cert.pem")[0]; + certificateRetriever.AddTrustedCertificates(JavaUtil.ArraysAsList(candidateOcspIssuerCert1, candidateOcspIssuerCert2 + )); + TestOcspResponseBuilder builder = new TestOcspResponseBuilder(responderCert, ocspRespPrivateKey); + builder.SetOcspCertsChain(new IX509Certificate[] { caCert }); + TestOcspClient ocspClient = new TestOcspClient().AddBuilderForCertIssuer(caCert, builder); + IBasicOcspResponse basicOCSPResp = FACTORY.CreateBasicOCSPResponse(FACTORY.CreateASN1Primitive(ocspClient. + GetEncoded(checkCert, caCert, null))); + ValidationReport report = new ValidationReport(); + certificateRetriever.AddTrustedCertificates(JavaCollectionsUtil.SingletonList(caCert)); + OCSPValidator validator = validatorChainBuilder.BuildOCSPValidator(); + validator.Validate(report, baseContext, checkCert, basicOCSPResp.GetResponses()[0], basicOCSPResp, TimeTestUtil + .TEST_DATE_TIME, TimeTestUtil.TEST_DATE_TIME); + AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.INDETERMINATE + )); + } + [NUnit.Framework.Test] public virtual void OcpsIssuerChainValidationsUsesCorrectParametersTest() { DateTime checkDate = TimeTestUtil.TEST_DATE_TIME; @@ -165,8 +209,9 @@ public virtual void IssuersDoNotMatchTest() { IBasicOcspResponse basicOCSPResp = FACTORY.CreateBasicOCSPResponse(FACTORY.CreateASN1Primitive(ocspClient. GetEncoded(checkCert, caCert, null))); ValidationReport report = new ValidationReport(); - validatorChainBuilder.WithIssuingCertificateRetriever(new OCSPValidatorTest.TestIssuingCertificateRetriever - (wrongRootCertFileName)); + OCSPValidatorTest.TestIssuingCertificateRetriever wrongRootCertificateRetriever = new OCSPValidatorTest.TestIssuingCertificateRetriever + (wrongRootCertFileName); + validatorChainBuilder.WithIssuingCertificateRetrieverFactory(() => wrongRootCertificateRetriever); OCSPValidator validator = validatorChainBuilder.BuildOCSPValidator(); validator.Validate(report, baseContext, checkCert, basicOCSPResp.GetResponses()[0], basicOCSPResp, TimeTestUtil .TEST_DATE_TIME, TimeTestUtil.TEST_DATE_TIME); @@ -383,7 +428,7 @@ public virtual void CertExpiredAfterArchiveCutoffDateTest() { public virtual void CertificateRetrieverRetrieveIssuerCertificateFailureTest() { DateTime checkDate = TimeTestUtil.TEST_DATE_TIME; MockIssuingCertificateRetriever mockCertificateRetriever = new MockIssuingCertificateRetriever(); - validatorChainBuilder.WithIssuingCertificateRetriever(mockCertificateRetriever); + validatorChainBuilder.WithIssuingCertificateRetrieverFactory(() => mockCertificateRetriever); mockCertificateRetriever.OnRetrieveIssuerCertificateDo((c) => { throw new Exception("Test retrieveMissingCertificates failure"); } @@ -398,7 +443,7 @@ public virtual void CertificateRetrieverRetrieveOCSPResponderCertificateFailureT DateTime checkDate = TimeTestUtil.TEST_DATE_TIME; MockIssuingCertificateRetriever mockCertificateRetriever = new MockIssuingCertificateRetriever(certificateRetriever ); - validatorChainBuilder.WithIssuingCertificateRetriever(mockCertificateRetriever); + validatorChainBuilder.WithIssuingCertificateRetrieverFactory(() => mockCertificateRetriever); mockCertificateRetriever.OnRetrieveOCSPResponderCertificateDo((c) => { throw new Exception("Test retrieveMissingCertificates failure"); } @@ -413,11 +458,17 @@ public virtual void CertificateRetrieverIsCertificateTrustedFailureTest() { DateTime checkDate = TimeTestUtil.TEST_DATE_TIME; MockIssuingCertificateRetriever mockCertificateRetriever = new MockIssuingCertificateRetriever(certificateRetriever ); - validatorChainBuilder.WithIssuingCertificateRetriever(mockCertificateRetriever); + validatorChainBuilder.WithIssuingCertificateRetrieverFactory(() => mockCertificateRetriever); mockCertificateRetriever.OnIsCertificateTrustedDo((c) => { throw new Exception("Test isCertificateTrusted failure"); } ); + MockTrustedCertificatesStore mockTrustStore = new MockTrustedCertificatesStore(); + mockTrustStore.OnIsCertificateTrustedForOcspDo((c) => { + throw new Exception("Test isCertificateTrusted failure"); + } + ); + mockCertificateRetriever.OnGetTrustedCertificatesStoreDo(() => mockTrustStore); ValidationReport report = ValidateTest(checkDate); AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.INDETERMINATE ).HasLogItem((l) => l.WithMessage(OCSPValidator.OCSP_RESPONDER_TRUST_NOT_RETRIEVED))); @@ -428,7 +479,7 @@ public virtual void CertificateRetrieverIsCertificateTrustedForOcspFailureTest() DateTime checkDate = TimeTestUtil.TEST_DATE_TIME; MockIssuingCertificateRetriever mockCertificateRetriever = new MockIssuingCertificateRetriever(certificateRetriever ); - validatorChainBuilder.WithIssuingCertificateRetriever(mockCertificateRetriever); + validatorChainBuilder.WithIssuingCertificateRetrieverFactory(() => mockCertificateRetriever); mockCertificateRetriever.OnIsCertificateTrustedDo((c) => false); MockTrustedCertificatesStore mockTrustedStore = new MockTrustedCertificatesStore(certificateRetriever.GetTrustedCertificatesStore ()); @@ -499,8 +550,8 @@ public TestIssuingCertificateRetriever(String issuerPath) this.issuerCertificate = PemFileHelper.ReadFirstChain(issuerPath)[0]; } - public override IX509Certificate RetrieveIssuerCertificate(IX509Certificate certificate) { - return issuerCertificate; + public override IList RetrieveIssuerCertificate(IX509Certificate certificate) { + return JavaCollectionsUtil.SingletonList((IX509Certificate)issuerCertificate); } } } diff --git a/itext.tests/itext.sign.tests/itext/signatures/validation/RevocationDataValidatorIntegrationTest.cs b/itext.tests/itext.sign.tests/itext/signatures/validation/RevocationDataValidatorIntegrationTest.cs new file mode 100644 index 0000000000..c36d9d19de --- /dev/null +++ b/itext.tests/itext.sign.tests/itext/signatures/validation/RevocationDataValidatorIntegrationTest.cs @@ -0,0 +1,190 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using iText.Bouncycastleconnector; +using iText.Commons.Bouncycastle; +using iText.Commons.Bouncycastle.Cert; +using iText.Commons.Bouncycastle.Crypto; +using iText.Commons.Utils; +using iText.Signatures; +using iText.Signatures.Testutils; +using iText.Signatures.Testutils.Builder; +using iText.Signatures.Testutils.Client; +using iText.Signatures.Validation.Context; +using iText.Signatures.Validation.Report; +using iText.Test; + +namespace iText.Signatures.Validation { + [NUnit.Framework.Category("BouncyCastleUnitTest")] + public class RevocationDataValidatorIntegrationTest : ExtendedITextTest { + private static readonly IBouncyCastleFactory FACTORY = BouncyCastleFactoryCreator.GetFactory(); + + private static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/RevocationDataValidatorTest/"; + + private static readonly String CRL_TEST_SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext + .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/CRLValidatorTest/"; + + private static readonly char[] PASSWORD = "testpassphrase".ToCharArray(); + + private static IX509Certificate caCert; + + private static IPrivateKey caPrivateKey; + + private static IX509Certificate checkCert; + + private static IX509Certificate responderCert; + + private static IPrivateKey ocspRespPrivateKey; + + private IssuingCertificateRetriever certificateRetriever; + + private SignatureValidationProperties parameters; + + private ValidatorChainBuilder validatorChainBuilder; + + private readonly ValidationContext baseContext = new ValidationContext(ValidatorContext.SIGNATURE_VALIDATOR + , CertificateSource.SIGNER_CERT, TimeBasedContext.PRESENT); + + [NUnit.Framework.OneTimeSetUp] + public static void Before() { + String rootCertFileName = SOURCE_FOLDER + "rootCert.pem"; + String checkCertFileName = SOURCE_FOLDER + "signCert.pem"; + String ocspResponderCertFileName = SOURCE_FOLDER + "ocspResponderCert.pem"; + caCert = (IX509Certificate)PemFileHelper.ReadFirstChain(rootCertFileName)[0]; + caPrivateKey = PemFileHelper.ReadFirstKey(rootCertFileName, PASSWORD); + checkCert = (IX509Certificate)PemFileHelper.ReadFirstChain(checkCertFileName)[0]; + responderCert = (IX509Certificate)PemFileHelper.ReadFirstChain(ocspResponderCertFileName)[0]; + ocspRespPrivateKey = PemFileHelper.ReadFirstKey(ocspResponderCertFileName, PASSWORD); + } + + [NUnit.Framework.SetUp] + public virtual void SetUp() { + certificateRetriever = new IssuingCertificateRetriever(); + parameters = new SignatureValidationProperties(); + validatorChainBuilder = new ValidatorChainBuilder().WithIssuingCertificateRetrieverFactory(() => certificateRetriever + ).WithSignatureValidationProperties(parameters); + } + + [NUnit.Framework.Test] + public virtual void CrlWithOnlySomeReasonsTest() { + TestCrlBuilder builder1 = new TestCrlBuilder(caCert, caPrivateKey); + builder1.AddExtension(FACTORY.CreateExtensions().GetIssuingDistributionPoint(), true, FACTORY.CreateIssuingDistributionPoint + (null, false, false, FACTORY.CreateReasonFlags(CRLValidator.ALL_REASONS - 31), false, false)); + TestCrlBuilder builder2 = new TestCrlBuilder(caCert, caPrivateKey); + builder2.AddExtension(FACTORY.CreateExtensions().GetIssuingDistributionPoint(), true, FACTORY.CreateIssuingDistributionPoint + (null, false, false, FACTORY.CreateReasonFlags(31), false, false)); + TestCrlClient crlClient = new TestCrlClient().AddBuilderForCertIssuer(builder1).AddBuilderForCertIssuer(builder2 + ); + TestOcspResponseBuilder ocspBuilder = new TestOcspResponseBuilder(responderCert, ocspRespPrivateKey); + ocspBuilder.SetProducedAt(TimeTestUtil.TEST_DATE_TIME.AddDays(-100)); + certificateRetriever.SetTrustedCertificates(JavaCollectionsUtil.SingletonList(caCert)); + parameters.SetRevocationOnlineFetching(ValidatorContexts.All(), CertificateSources.All(), TimeBasedContexts + .All(), SignatureValidationProperties.OnlineFetching.NEVER_FETCH); + ValidationReport report = new ValidationReport(); + RevocationDataValidator validator = validatorChainBuilder.BuildRevocationDataValidator(); + validator.AddOcspClient(new TestOcspClient().AddBuilderForCertIssuer(caCert, ocspBuilder)).AddCrlClient(crlClient + ); + validator.Validate(report, baseContext, checkCert, TimeTestUtil.TEST_DATE_TIME); + AssertValidationReport.AssertThat(report, (a) => a.HasNumberOfFailures(0).HasLogItem((la) => la.WithCertificate + (checkCert).WithStatus(ReportItem.ReportItemStatus.INFO).WithMessage(CRLValidator.ONLY_SOME_REASONS_CHECKED + ))); + } + + [NUnit.Framework.Test] + public virtual void CrlSignerIsValidatedCertificate() { + String rootCertFileName = CRL_TEST_SOURCE_FOLDER + "happyPath/ca.cert.pem"; + String crlSignerKeyFileName = CRL_TEST_SOURCE_FOLDER + "keys/crl-key.pem"; + String crlSignerFileName = CRL_TEST_SOURCE_FOLDER + "happyPath/crl-issuer.cert.pem"; + String checkCertFileName = CRL_TEST_SOURCE_FOLDER + "happyPath/sign.cert.pem"; + IX509Certificate caCert = (IX509Certificate)PemFileHelper.ReadFirstChain(rootCertFileName)[0]; + IX509Certificate crlSigner = (IX509Certificate)PemFileHelper.ReadFirstChain(crlSignerFileName)[0]; + IPrivateKey crlPrivateKey = PemFileHelper.ReadFirstKey(crlSignerKeyFileName, PASSWORD); + IX509Certificate checkCert = (IX509Certificate)PemFileHelper.ReadFirstChain(checkCertFileName)[0]; + certificateRetriever.AddTrustedCertificates(JavaCollectionsUtil.SingletonList(caCert)); + certificateRetriever.AddKnownCertificates(JavaCollectionsUtil.SingletonList(crlSigner)); + DateTime checkDate = TimeTestUtil.TEST_DATE_TIME; + DateTime revocationDate = checkDate.AddDays(-1); + TestCrlBuilder builder = new TestCrlBuilder(crlSigner, crlPrivateKey, checkDate); + builder.SetNextUpdate(checkDate.AddDays(10)); + //builder.addCrlEntry(caCert, revocationDate, FACTORY.createCRLReason().getKeyCompromise()); + //TestCrlClientWrapper crlClient = new TestCrlClientWrapper(new TestCrlClient().addBuilderForCertIssuer(builder)); + ValidationCrlClient crlClient = (ValidationCrlClient)parameters.GetCrlClients()[0]; + crlClient.AddCrl((IX509Crl)CertificateUtil.ParseCrlFromBytes(builder.MakeCrl()), checkDate, TimeBasedContext + .HISTORICAL); + ValidationReport report = new ValidationReport(); + certificateRetriever.AddTrustedCertificates(JavaCollectionsUtil.SingletonList(caCert)); + parameters.SetRevocationOnlineFetching(ValidatorContexts.All(), CertificateSources.All(), TimeBasedContexts + .All(), SignatureValidationProperties.OnlineFetching.FETCH_IF_NO_OTHER_DATA_AVAILABLE); + parameters.SetFreshness(ValidatorContexts.All(), CertificateSources.All(), TimeBasedContexts.All(), TimeSpan.FromDays + (0)); + RevocationDataValidator validator = validatorChainBuilder.BuildRevocationDataValidator(); + validatorChainBuilder.WithRevocationDataValidatorFactory(() => validator); + validator.Validate(report, baseContext, crlSigner, checkDate); + AssertValidationReport.AssertThat(report, (a) => a.HasNumberOfFailures(1).HasLogItem((l) => l.WithMessage( + CRLValidator.CERTIFICATE_IN_ISSUER_CHAIN))); + } + + [NUnit.Framework.Test] + public virtual void CrlSignerIssuerIsValidatedCertificate() { + String rootCertFileName = CRL_TEST_SOURCE_FOLDER + "crlSignerInValidatedChain/ca.cert.pem"; + String intermediateFileName = CRL_TEST_SOURCE_FOLDER + "crlSignerInValidatedChain/intermediate.cert.pem"; + String intermediate2FileName = CRL_TEST_SOURCE_FOLDER + "crlSignerInValidatedChain/intermediate2.cert.pem"; + String crlSignerKeyFileName = CRL_TEST_SOURCE_FOLDER + "keys/crl-key.pem"; + String crlSignerFileName = CRL_TEST_SOURCE_FOLDER + "crlSignerInValidatedChain/crl-issuer.cert.pem"; + String checkCertFileName = CRL_TEST_SOURCE_FOLDER + "crlSignerInValidatedChain/sign.cert.pem"; + IX509Certificate caCert = (IX509Certificate)PemFileHelper.ReadFirstChain(rootCertFileName)[0]; + IX509Certificate intermediateCert = (IX509Certificate)PemFileHelper.ReadFirstChain(intermediateFileName)[0 + ]; + IX509Certificate intermediate2Cert = (IX509Certificate)PemFileHelper.ReadFirstChain(intermediate2FileName) + [0]; + IX509Certificate crlSigner = (IX509Certificate)PemFileHelper.ReadFirstChain(crlSignerFileName)[0]; + IPrivateKey crlPrivateKey = PemFileHelper.ReadFirstKey(crlSignerKeyFileName, PASSWORD); + IX509Certificate checkCert = (IX509Certificate)PemFileHelper.ReadFirstChain(checkCertFileName)[0]; + certificateRetriever.AddTrustedCertificates(JavaCollectionsUtil.SingletonList(caCert)); + certificateRetriever.AddKnownCertificates(JavaCollectionsUtil.SingletonList(crlSigner)); + certificateRetriever.AddKnownCertificates(JavaCollectionsUtil.SingletonList(intermediateCert)); + certificateRetriever.AddKnownCertificates(JavaCollectionsUtil.SingletonList(intermediate2Cert)); + DateTime checkDate = TimeTestUtil.TEST_DATE_TIME; + DateTime revocationDate = checkDate.AddDays(-1); + TestCrlBuilder builder = new TestCrlBuilder(crlSigner, crlPrivateKey, checkDate); + builder.SetNextUpdate(checkDate.AddDays(10)); + //builder.addCrlEntry(caCert, revocationDate, FACTORY.createCRLReason().getKeyCompromise()); + //TestCrlClientWrapper crlClient = new TestCrlClientWrapper(new TestCrlClient().addBuilderForCertIssuer(builder)); + ValidationCrlClient crlClient = (ValidationCrlClient)parameters.GetCrlClients()[0]; + crlClient.AddCrl((IX509Crl)CertificateUtil.ParseCrlFromBytes(builder.MakeCrl()), checkDate, TimeBasedContext + .HISTORICAL); + ValidationReport report = new ValidationReport(); + //certificateRetriever.addTrustedCertificates(Collections.singletonList(caCert)); + parameters.SetRevocationOnlineFetching(ValidatorContexts.All(), CertificateSources.All(), TimeBasedContexts + .All(), SignatureValidationProperties.OnlineFetching.FETCH_IF_NO_OTHER_DATA_AVAILABLE); + parameters.SetFreshness(ValidatorContexts.All(), CertificateSources.All(), TimeBasedContexts.All(), TimeSpan.FromDays + (0)); + RevocationDataValidator validator = validatorChainBuilder.BuildRevocationDataValidator(); + validatorChainBuilder.WithRevocationDataValidatorFactory(() => validator); + validator.Validate(report, baseContext, intermediateCert, checkDate); + AssertValidationReport.AssertThat(report, (a) => a.HasNumberOfFailures(1).HasLogItem((l) => l.WithMessage( + CRLValidator.CERTIFICATE_IN_ISSUER_CHAIN))); + } + } +} diff --git a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/RevocationDataValidatorTest.cs b/itext.tests/itext.sign.tests/itext/signatures/validation/RevocationDataValidatorTest.cs similarity index 93% rename from itext.tests/itext.sign.tests/itext/signatures/validation/v1/RevocationDataValidatorTest.cs rename to itext.tests/itext.sign.tests/itext/signatures/validation/RevocationDataValidatorTest.cs index 6421d3462e..a497b715b9 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/RevocationDataValidatorTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/validation/RevocationDataValidatorTest.cs @@ -33,19 +33,19 @@ You should have received a copy of the GNU Affero General Public License using iText.Signatures.Testutils; using iText.Signatures.Testutils.Builder; using iText.Signatures.Testutils.Client; -using iText.Signatures.Validation.V1.Context; -using iText.Signatures.Validation.V1.Mocks; -using iText.Signatures.Validation.V1.Report; +using iText.Signatures.Validation.Context; +using iText.Signatures.Validation.Mocks; +using iText.Signatures.Validation.Report; using iText.Test; using iText.Test.Attributes; -namespace iText.Signatures.Validation.V1 { +namespace iText.Signatures.Validation { [NUnit.Framework.Category("BouncyCastleUnitTest")] public class RevocationDataValidatorTest : ExtendedITextTest { private static readonly IBouncyCastleFactory FACTORY = BouncyCastleFactoryCreator.GetFactory(); private static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext - .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/v1/RevocationDataValidatorTest/"; + .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/RevocationDataValidatorTest/"; private static readonly char[] PASSWORD = "testpassphrase".ToCharArray(); @@ -96,9 +96,9 @@ public virtual void SetUp() { mockCrlValidator = new MockCrlValidator(); mockOCSPValidator = new MockOCSPValidator(); mockParameters = new MockSignatureValidationProperties(parameters); - validatorChainBuilder = new ValidatorChainBuilder().WithIssuingCertificateRetriever(certificateRetriever). - WithSignatureValidationProperties(mockParameters).WithCRLValidator(mockCrlValidator).WithOCSPValidator - (mockOCSPValidator); + validatorChainBuilder = new ValidatorChainBuilder().WithIssuingCertificateRetrieverFactory(() => certificateRetriever + ).WithSignatureValidationProperties(mockParameters).WithCRLValidatorFactory(() => mockCrlValidator).WithOCSPValidatorFactory + (() => mockOCSPValidator); } [NUnit.Framework.Test] @@ -250,6 +250,32 @@ public virtual void ValidityAssuredTest() { .VALIDITY_ASSURED).WithCertificate(certificate))); } + [NUnit.Framework.Test] + public virtual void NoRevAvailTest() { + String checkCertFileName = SOURCE_FOLDER + "noRevAvailCertWithoutCA.pem"; + IX509Certificate certificate = (IX509Certificate)PemFileHelper.ReadFirstChain(checkCertFileName)[0]; + DateTime checkDate = TimeTestUtil.TEST_DATE_TIME; + ValidationReport report = new ValidationReport(); + RevocationDataValidator validator = validatorChainBuilder.BuildRevocationDataValidator(); + validator.Validate(report, baseContext, certificate, checkDate); + AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.VALID).HasLogItem + ((la) => la.WithCheckName(RevocationDataValidator.REVOCATION_DATA_CHECK).WithMessage(RevocationDataValidator + .NO_REV_AVAILABLE, (m) => certificate.GetSubjectDN()).WithCertificate(certificate))); + } + + [NUnit.Framework.Test] + public virtual void NoRevAvailWithCATest() { + String checkCertFileName = SOURCE_FOLDER + "noRevAvailCert.pem"; + IX509Certificate certificate = (IX509Certificate)PemFileHelper.ReadFirstChain(checkCertFileName)[0]; + DateTime checkDate = TimeTestUtil.TEST_DATE_TIME; + ValidationReport report = new ValidationReport(); + RevocationDataValidator validator = validatorChainBuilder.BuildRevocationDataValidator(); + validator.Validate(report, baseContext, certificate, checkDate); + AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.INDETERMINATE + ).HasLogItem((la) => la.WithCheckName(RevocationDataValidator.REVOCATION_DATA_CHECK).WithMessage(RevocationDataValidator + .NO_REV_AVAILABLE_CA, (m) => certificate.GetSubjectDN()).WithCertificate(certificate))); + } + [NUnit.Framework.Test] public virtual void SelfSignedCertificateIsNotValidatedTest() { DateTime checkDate = TimeTestUtil.TEST_DATE_TIME; @@ -385,7 +411,7 @@ public virtual void CrlEncodingErrorTest() { parameters.SetFreshness(ValidatorContexts.All(), CertificateSources.All(), TimeBasedContexts.All(), TimeSpan.FromDays (2)); RevocationDataValidator validator = validatorChainBuilder.BuildRevocationDataValidator(); - validator.AddCrlClient(new _ICrlClient_516(crl)).Validate(report, baseContext, checkCert, TimeTestUtil.TEST_DATE_TIME + validator.AddCrlClient(new _ICrlClient_557(crl)).Validate(report, baseContext, checkCert, TimeTestUtil.TEST_DATE_TIME ); AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.INDETERMINATE ).HasLogItem((la) => la.WithCheckName(RevocationDataValidator.REVOCATION_DATA_CHECK).WithMessage(MessageFormatUtil @@ -394,8 +420,8 @@ public virtual void CrlEncodingErrorTest() { ))); } - private sealed class _ICrlClient_516 : ICrlClient { - public _ICrlClient_516(byte[] crl) { + private sealed class _ICrlClient_557 : ICrlClient { + public _ICrlClient_557(byte[] crl) { this.crl = crl; } @@ -493,7 +519,7 @@ public virtual void ResponsesFromValidationClientArePassedTest() { mockCrlValidator.OnCallDo((c) => NUnit.Framework.Assert.AreEqual(crlGeneration, c.responseGenerationDate)); ValidationReport report = new ValidationReport(); RevocationDataValidator validator = validatorChainBuilder.GetRevocationDataValidator(); - ValidationOcspClient ocspClient = new _ValidationOcspClient_635(); + ValidationOcspClient ocspClient = new _ValidationOcspClient_676(); TestOcspResponseBuilder ocspBuilder = new TestOcspResponseBuilder(responderCert, ocspRespPrivateKey); byte[] ocspResponseBytes = new TestOcspClient().AddBuilderForCertIssuer(caCert, ocspBuilder).GetEncoded(checkCert , caCert, null); @@ -501,7 +527,7 @@ public virtual void ResponsesFromValidationClientArePassedTest() { )); ocspClient.AddResponse(basicOCSPResp, ocspGeneration, TimeBasedContext.HISTORICAL); validator.AddOcspClient(ocspClient); - ValidationCrlClient crlClient = new _ValidationCrlClient_650(); + ValidationCrlClient crlClient = new _ValidationCrlClient_691(); TestCrlBuilder crlBuilder = new TestCrlBuilder(caCert, caPrivateKey, checkDate); byte[] crlResponseBytes = new List(new TestCrlClient().AddBuilderForCertIssuer(crlBuilder).GetEncoded (checkCert, null))[0]; @@ -511,8 +537,8 @@ public virtual void ResponsesFromValidationClientArePassedTest() { validator.Validate(report, baseContext, checkCert, checkDate); } - private sealed class _ValidationOcspClient_635 : ValidationOcspClient { - public _ValidationOcspClient_635() { + private sealed class _ValidationOcspClient_676 : ValidationOcspClient { + public _ValidationOcspClient_676() { } public override byte[] GetEncoded(IX509Certificate checkCert, IX509Certificate issuerCert, String url) { @@ -521,8 +547,8 @@ public override byte[] GetEncoded(IX509Certificate checkCert, IX509Certificate i } } - private sealed class _ValidationCrlClient_650 : ValidationCrlClient { - public _ValidationCrlClient_650() { + private sealed class _ValidationCrlClient_691 : ValidationCrlClient { + public _ValidationCrlClient_691() { } public override ICollection GetEncoded(IX509Certificate checkCert, String url) { @@ -588,18 +614,18 @@ public virtual void TimeBasedContextProperlySetOnlineClientsTest() { RevocationDataValidator validator = validatorChainBuilder.GetRevocationDataValidator(); TestOcspResponseBuilder ocspBuilder = new TestOcspResponseBuilder(responderCert, ocspRespPrivateKey); TestOcspClient testOcspClient = new TestOcspClient().AddBuilderForCertIssuer(caCert, ocspBuilder); - OcspClientBouncyCastle ocspClient = new _OcspClientBouncyCastle_729(testOcspClient); + OcspClientBouncyCastle ocspClient = new _OcspClientBouncyCastle_770(testOcspClient); validator.AddOcspClient(ocspClient); TestCrlBuilder crlBuilder = new TestCrlBuilder(caCert, caPrivateKey, checkDate); TestCrlClient testCrlClient = new TestCrlClient().AddBuilderForCertIssuer(crlBuilder); - CrlClientOnline crlClient = new _CrlClientOnline_739(testCrlClient); + CrlClientOnline crlClient = new _CrlClientOnline_780(testCrlClient); validator.AddCrlClient(crlClient); validator.Validate(report, baseContext.SetTimeBasedContext(TimeBasedContext.HISTORICAL), checkCert, checkDate ); } - private sealed class _OcspClientBouncyCastle_729 : OcspClientBouncyCastle { - public _OcspClientBouncyCastle_729(TestOcspClient testOcspClient) { + private sealed class _OcspClientBouncyCastle_770 : OcspClientBouncyCastle { + public _OcspClientBouncyCastle_770(TestOcspClient testOcspClient) { this.testOcspClient = testOcspClient; } @@ -610,8 +636,8 @@ public override byte[] GetEncoded(IX509Certificate checkCert, IX509Certificate r private readonly TestOcspClient testOcspClient; } - private sealed class _CrlClientOnline_739 : CrlClientOnline { - public _CrlClientOnline_739(TestCrlClient testCrlClient) { + private sealed class _CrlClientOnline_780 : CrlClientOnline { + public _CrlClientOnline_780(TestCrlClient testCrlClient) { this.testCrlClient = testCrlClient; } @@ -700,14 +726,14 @@ public virtual void CertificateRetrieverRetrieveIssuerCertificateFailureTest() { throw new Exception("Test retrieveIssuerCertificate failure"); } ); - validatorChainBuilder.WithIssuingCertificateRetriever(mockCertificateRetreiver); + validatorChainBuilder.WithIssuingCertificateRetrieverFactory(() => mockCertificateRetreiver); RevocationDataValidator validator = validatorChainBuilder.BuildRevocationDataValidator(); validator.AddOcspClient(ocspClient); ReportItem reportItem = new ReportItem("validator", "message", ReportItem.ReportItemStatus.INFO); mockOCSPValidator.OnCallDo((c) => c.report.AddReportItem(reportItem)); validator.Validate(report, baseContext, checkCert, checkDate); AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.INDETERMINATE - ).HasLogItem((l) => l.WithMessage(RevocationDataValidator.ISSUER_RETRIEVAL_FAILED))); + ).HasLogItem((l) => l.WithMessage(RevocationDataValidator.UNABLE_TO_RETRIEVE_REV_DATA_ONLINE))); } [NUnit.Framework.Test] diff --git a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/SignatureValidationPropertiesTest.cs b/itext.tests/itext.sign.tests/itext/signatures/validation/SignatureValidationPropertiesTest.cs similarity index 98% rename from itext.tests/itext.sign.tests/itext/signatures/validation/v1/SignatureValidationPropertiesTest.cs rename to itext.tests/itext.sign.tests/itext/signatures/validation/SignatureValidationPropertiesTest.cs index 2a2d53a1ca..2a5fd81b85 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/SignatureValidationPropertiesTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/validation/SignatureValidationPropertiesTest.cs @@ -22,11 +22,11 @@ You should have received a copy of the GNU Affero General Public License */ using System; using iText.Commons.Utils; -using iText.Signatures.Validation.V1.Context; -using iText.Signatures.Validation.V1.Extensions; +using iText.Signatures.Validation.Context; +using iText.Signatures.Validation.Extensions; using iText.Test; -namespace iText.Signatures.Validation.V1 { +namespace iText.Signatures.Validation { [NUnit.Framework.Category("UnitTest")] public class SignatureValidationPropertiesTest : ExtendedITextTest { [NUnit.Framework.Test] diff --git a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/SignatureValidatorIntegrationTest.cs b/itext.tests/itext.sign.tests/itext/signatures/validation/SignatureValidatorIntegrationTest.cs similarity index 68% rename from itext.tests/itext.sign.tests/itext/signatures/validation/v1/SignatureValidatorIntegrationTest.cs rename to itext.tests/itext.sign.tests/itext/signatures/validation/SignatureValidatorIntegrationTest.cs index dcdee4f480..4720a7400c 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/SignatureValidatorIntegrationTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/validation/SignatureValidatorIntegrationTest.cs @@ -22,29 +22,33 @@ You should have received a copy of the GNU Affero General Public License */ using System; using System.Collections.Generic; +using NUnit.Framework; using iText.Bouncycastleconnector; using iText.Commons.Bouncycastle; using iText.Commons.Bouncycastle.Cert; using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Utils; +using iText.Kernel.Crypto; +using iText.Kernel.Logs; using iText.Kernel.Pdf; using iText.Signatures; using iText.Signatures.Testutils; using iText.Signatures.Testutils.Builder; using iText.Signatures.Testutils.Client; -using iText.Signatures.Validation.V1.Context; -using iText.Signatures.Validation.V1.Mocks; -using iText.Signatures.Validation.V1.Report; +using iText.Signatures.Validation.Context; +using iText.Signatures.Validation.Mocks; +using iText.Signatures.Validation.Report; using iText.Test; +using iText.Test.Attributes; -namespace iText.Signatures.Validation.V1 { +namespace iText.Signatures.Validation { [NUnit.Framework.Category("BouncyCastleIntegrationTest")] public class SignatureValidatorIntegrationTest : ExtendedITextTest { private static readonly String CERTS_SRC = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext - .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/certs/"; + .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/certs/"; private static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext - .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/"; + .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/"; private static readonly IBouncyCastleFactory FACTORY = BouncyCastleFactoryCreator.GetFactory(); @@ -64,7 +68,7 @@ public static void Before() { public virtual void SetUp() { parameters = new SignatureValidationProperties(); certificateRetriever = new IssuingCertificateRetriever(); - builder = new ValidatorChainBuilder().WithIssuingCertificateRetriever(certificateRetriever).WithSignatureValidationProperties + builder = new ValidatorChainBuilder().WithIssuingCertificateRetrieverFactory(() => certificateRetriever).WithSignatureValidationProperties (parameters); } @@ -78,11 +82,65 @@ public virtual void ValidLatestSignatureTest() { certificateRetriever.SetTrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); AddRevDataClients(); SignatureValidator signatureValidator = builder.BuildSignatureValidator(document); - report = signatureValidator.ValidateLatestSignature(document); + report = signatureValidator.ValidateSignatures(); + } + AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.VALID).HasLogItem + ((al) => al.WithCertificate(rootCert).WithCheckName(CertificateChainValidator.CERTIFICATE_CHECK).WithMessage + (CertificateChainValidator.CERTIFICATE_TRUSTED, (i) => rootCert.GetSubjectDN())).HasLogItem((al) => al + .WithCheckName(OCSPValidator.OCSP_CHECK).WithMessage(OCSPValidator.OCSP_RESPONDER_TRUSTED)).HasLogItem + ((al) => al.WithCheckName(OCSPValidator.OCSP_CHECK).WithMessage(OCSPValidator.OCSP_RESPONDER_IS_CA))); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void ValidateSignatureInEncryptedDocumentTest() { + String chainName = CERTS_SRC + "signCertRsa01.pem"; + IX509Certificate[] certificateChain = PemFileHelper.ReadFirstChain(chainName); + IX509Certificate rootCert = (IX509Certificate)certificateChain[1]; + ValidationReport report; + using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "encryptedDoc.pdf", new ReaderProperties + ().SetPassword("123".GetBytes(iText.Commons.Utils.EncodingUtil.ISO_8859_1))))) { + SignatureValidator signatureValidator = builder.BuildSignatureValidator(document); + report = signatureValidator.ValidateSignatures(); } - AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.VALID).HasLogItems - (3, (al) => al.WithCertificate(rootCert).WithCheckName(CertificateChainValidator.CERTIFICATE_CHECK).WithMessage - (CertificateChainValidator.CERTIFICATE_TRUSTED, (i) => rootCert.GetSubjectDN()))); + NUnit.Framework.Assert.AreEqual(2, report.GetFailures().Count); + AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.INDETERMINATE + ).HasLogItem((al) => al.WithCertificate(rootCert).WithCheckName(CertificateChainValidator.CERTIFICATE_CHECK + ).WithMessage(CertificateChainValidator.ISSUER_MISSING, (i) => rootCert.GetSubjectDN())).HasLogItem((al + ) => al.WithCheckName(RevocationDataValidator.REVOCATION_DATA_CHECK).WithMessage(RevocationDataValidator + .NO_REVOCATION_DATA)).HasLogItem((al) => al.WithCheckName(RevocationDataValidator.REVOCATION_DATA_CHECK + ).WithMessage(RevocationDataValidator.SELF_SIGNED_CERTIFICATE))); + } + + [NUnit.Framework.Test] + [LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)] + public virtual void ValidateSignatureInEncryptedPubKeyDocumentTest() { + try { + BouncyCastleFactoryCreator.GetFactory().IsEncryptionFeatureSupported(0, true); + } + catch (Exception) { + NUnit.Framework.Assume.That(false); + } + String chainName = CERTS_SRC + "signCertRsa01.pem"; + IX509Certificate[] certificateChain = PemFileHelper.ReadFirstChain(chainName); + IX509Certificate rootCert = (IX509Certificate)certificateChain[1]; + ValidationReport report; + IX509Certificate certificate = CryptoUtil.ReadPublicCertificate(FileUtil.GetInputStreamForFile(CERTS_SRC + + "SHA256withRSA.cer")); + IPrivateKey privateKey = PemFileHelper.ReadFirstKey(CERTS_SRC + "SHA256withRSA.key", PASSWORD); + ReaderProperties properties = new ReaderProperties().SetPublicKeySecurityParams(certificate, privateKey); + using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "encryptedPublicKeyDocTest.pdf" + , properties))) { + SignatureValidator signatureValidator = builder.BuildSignatureValidator(document); + report = signatureValidator.ValidateSignatures(); + } + NUnit.Framework.Assert.AreEqual(2, report.GetFailures().Count); + AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.INDETERMINATE + ).HasLogItem((al) => al.WithCertificate(rootCert).WithCheckName(CertificateChainValidator.CERTIFICATE_CHECK + ).WithMessage(CertificateChainValidator.ISSUER_MISSING, (i) => rootCert.GetSubjectDN())).HasLogItem((al + ) => al.WithCheckName(RevocationDataValidator.REVOCATION_DATA_CHECK).WithMessage(RevocationDataValidator + .NO_REVOCATION_DATA)).HasLogItem((al) => al.WithCheckName(RevocationDataValidator.REVOCATION_DATA_CHECK + ).WithMessage(RevocationDataValidator.SELF_SIGNED_CERTIFICATE))); } [NUnit.Framework.Test] @@ -102,15 +160,14 @@ public virtual void ShortValidityCertsWithOcspTest() { SignatureValidator signatureValidator = builder.BuildSignatureValidator(document); report = signatureValidator.ValidateSignatures(); } - // ocsp validation date is wrong but why AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.VALID).HasLogItem ((al) => al.WithCheckName(DocumentRevisionsValidator.DOC_MDP_CHECK).WithMessage(DocumentRevisionsValidator .UNEXPECTED_ENTRY_IN_XREF, (i) => 30)).HasLogItem((al) => al.WithCheckName(SignatureValidator.SIGNATURE_VERIFICATION ).WithMessage(SignatureValidator.VALIDATING_SIGNATURE_NAME, (i) => "timestampSig1")).HasLogItem((al) => al.WithCheckName(SignatureValidator.SIGNATURE_VERIFICATION).WithMessage(SignatureValidator.VALIDATING_SIGNATURE_NAME - , (i) => "Signature1")).HasLogItems(2, (al) => al.WithCertificate(rootCert).WithCheckName(CertificateChainValidator + , (i) => "Signature1")).HasLogItem((al) => al.WithCertificate(rootCert).WithCheckName(CertificateChainValidator .CERTIFICATE_CHECK).WithMessage(CertificateChainValidator.CERTIFICATE_TRUSTED, (i) => rootCert.GetSubjectDN - ())).HasLogItems(4, (al) => al.WithCertificate(tsRootCert).WithCheckName(CertificateChainValidator.CERTIFICATE_CHECK + ())).HasLogItems(2, (al) => al.WithCertificate(tsRootCert).WithCheckName(CertificateChainValidator.CERTIFICATE_CHECK ).WithMessage(CertificateChainValidator.CERTIFICATE_TRUSTED, (i) => tsRootCert.GetSubjectDN()))); } @@ -176,6 +233,70 @@ public virtual void ValidateMultipleDocumentsTest() { NUnit.Framework.Assert.AreEqual(2, validationOcspClient.GetResponses().Count); } + [NUnit.Framework.Test] + public virtual void ValidateSingleSignatureTest1() { + String rootCertName = CERTS_SRC + "root_cert.pem"; + IX509Certificate rootCert = (IX509Certificate)PemFileHelper.ReadFirstChain(rootCertName)[0]; + ValidationReport report1; + ValidationReport report2; + using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "validateSingleSignature1.pdf" + ))) { + certificateRetriever.SetTrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + AddRevDataClients(); + SignatureValidator signatureValidator1 = builder.BuildSignatureValidator(document); + report1 = signatureValidator1.ValidateSignature("Signature1"); + SignatureValidator signatureValidator2 = builder.BuildSignatureValidator(document); + report2 = signatureValidator2.ValidateSignature("Signature2"); + } + // Signature1 set access permissions to level 3, Signature2 - to level 1, after that annotation was added. + AssertValidationReport.AssertThat(report1, (a) => a.HasStatus(ValidationReport.ValidationResult.VALID).HasNumberOfLogs + (4).HasNumberOfFailures(0).HasLogItem((al) => al.WithCheckName(DocumentRevisionsValidator.DOC_MDP_CHECK + ).WithMessage(DocumentRevisionsValidator.UNEXPECTED_ENTRY_IN_XREF, (i) => 17).WithStatus(ReportItem.ReportItemStatus + .INFO)).HasLogItem((al) => al.WithCheckName(SignatureValidator.SIGNATURE_VERIFICATION).WithMessage(SignatureValidator + .VALIDATING_SIGNATURE_NAME, (p) => "Signature1")).HasLogItem((al) => al.WithCertificate(rootCert).WithCheckName + (CertificateChainValidator.CERTIFICATE_CHECK).WithMessage(CertificateChainValidator.CERTIFICATE_TRUSTED + , (i) => rootCert.GetSubjectDN())).HasLogItem((al) => al.WithCheckName(OCSPValidator.OCSP_CHECK).WithMessage + (OCSPValidator.OCSP_RESPONDER_IS_CA))); + AssertValidationReport.AssertThat(report2, (a) => a.HasStatus(ValidationReport.ValidationResult.INVALID).HasNumberOfLogs + (4).HasNumberOfFailures(1).HasLogItem((al) => al.WithCheckName(DocumentRevisionsValidator.DOC_MDP_CHECK + ).WithMessage(DocumentRevisionsValidator.PAGE_ANNOTATIONS_MODIFIED).WithStatus(ReportItem.ReportItemStatus + .INVALID)).HasLogItem((al) => al.WithCheckName(SignatureValidator.SIGNATURE_VERIFICATION).WithMessage( + SignatureValidator.VALIDATING_SIGNATURE_NAME, (p) => "Signature2")).HasLogItem((al) => al.WithCertificate + (rootCert).WithCheckName(CertificateChainValidator.CERTIFICATE_CHECK).WithMessage(CertificateChainValidator + .CERTIFICATE_TRUSTED, (i) => rootCert.GetSubjectDN())).HasLogItem((al) => al.WithCheckName(OCSPValidator + .OCSP_CHECK).WithMessage(OCSPValidator.OCSP_RESPONDER_IS_CA))); + } + + [NUnit.Framework.Test] + public virtual void ValidateSingleSignatureTest2() { + String rootCertName = CERTS_SRC + "root_cert.pem"; + IX509Certificate rootCert = (IX509Certificate)PemFileHelper.ReadFirstChain(rootCertName)[0]; + ValidationReport report1; + ValidationReport report2; + using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "validateSingleSignature2.pdf" + ))) { + certificateRetriever.SetTrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); + AddRevDataClients(); + SignatureValidator signatureValidator1 = builder.BuildSignatureValidator(document); + report1 = signatureValidator1.ValidateSignature("Signature1"); + SignatureValidator signatureValidator2 = builder.BuildSignatureValidator(document); + report2 = signatureValidator2.ValidateSignature("Signature2"); + } + // Signature1 set access permissions to level 1, after that annotation was added and then Signature2 applied. + AssertValidationReport.AssertThat(report1, (a) => a.HasStatus(ValidationReport.ValidationResult.INVALID).HasNumberOfFailures + (3).HasLogItem((al) => al.WithCheckName(DocumentRevisionsValidator.DOC_MDP_CHECK).WithMessage(DocumentRevisionsValidator + .PAGE_ANNOTATIONS_MODIFIED).WithStatus(ReportItem.ReportItemStatus.INVALID)).HasLogItem((al) => al.WithCheckName + (DocumentRevisionsValidator.DOC_MDP_CHECK).WithMessage(DocumentRevisionsValidator.UNEXPECTED_FORM_FIELD + , (p) => "Signature2").WithStatus(ReportItem.ReportItemStatus.INVALID)).HasLogItem((al) => al.WithCheckName + (DocumentRevisionsValidator.DOC_MDP_CHECK).WithMessage(DocumentRevisionsValidator.NOT_ALLOWED_ACROFORM_CHANGES + ).WithStatus(ReportItem.ReportItemStatus.INVALID)).HasLogItem((al) => al.WithCheckName(SignatureValidator + .SIGNATURE_VERIFICATION).WithMessage(SignatureValidator.VALIDATING_SIGNATURE_NAME, (p) => "Signature1" + ))); + AssertValidationReport.AssertThat(report2, (a) => a.HasStatus(ValidationReport.ValidationResult.VALID).HasNumberOfFailures + (0).HasLogItem((al) => al.WithCheckName(SignatureValidator.SIGNATURE_VERIFICATION).WithMessage(SignatureValidator + .VALIDATING_SIGNATURE_NAME, (p) => "Signature2"))); + } + [NUnit.Framework.Test] public virtual void RetrieveRevocationDataFromTheSignatureContainerTest() { String rootCertName = CERTS_SRC + "rootRsa.pem"; @@ -244,15 +365,17 @@ public virtual void LatestSignatureIsTimestampTest() { ocspBuilder.SetThisUpdate(DateTimeUtil.GetCalendar(currentDate.AddDays(3))); ocspBuilder.SetNextUpdate(DateTimeUtil.GetCalendar(currentDate.AddDays(30))); TestOcspClient ocspClient = new TestOcspClient().AddBuilderForCertIssuer(rootCert, ocspBuilder); - builder.GetRevocationDataValidator().AddOcspClient(ocspClient); + RevocationDataValidator revocationDataValidator = builder.BuildRevocationDataValidator(); + revocationDataValidator.AddOcspClient(ocspClient); + builder.WithRevocationDataValidatorFactory(() => revocationDataValidator); parameters.SetRevocationOnlineFetching(ValidatorContexts.All(), CertificateSources.All(), TimeBasedContexts .All(), SignatureValidationProperties.OnlineFetching.NEVER_FETCH).SetFreshness(ValidatorContexts.All() , CertificateSources.All(), TimeBasedContexts.All(), TimeSpan.FromDays(-2)); SignatureValidator signatureValidator = builder.BuildSignatureValidator(document); report = signatureValidator.ValidateLatestSignature(document); } - AssertValidationReport.AssertThat(report, (a) => a.HasNumberOfFailures(0).HasNumberOfLogs(3).HasLogItems(2 - , (la) => la.WithCheckName(CertificateChainValidator.CERTIFICATE_CHECK).WithMessage(CertificateChainValidator + AssertValidationReport.AssertThat(report, (a) => a.HasNumberOfFailures(0).HasNumberOfLogs(3).HasLogItem((la + ) => la.WithCheckName(CertificateChainValidator.CERTIFICATE_CHECK).WithMessage(CertificateChainValidator .CERTIFICATE_TRUSTED, (l) => rootCert.GetSubjectDN()).WithCertificate(rootCert))); } @@ -293,9 +416,11 @@ public virtual void CertificatesNotInLatestSignatureButSetAsKnownTest() { SignatureValidator signatureValidator = builder.BuildSignatureValidator(document); report = signatureValidator.ValidateLatestSignature(document); } - AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.VALID).HasLogItems - (3, (al) => al.WithCheckName(CertificateChainValidator.CERTIFICATE_CHECK).WithMessage(CertificateChainValidator - .CERTIFICATE_TRUSTED, (i) => rootCert.GetSubjectDN()).WithCertificate(rootCert))); + AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.VALID).HasLogItem + ((al) => al.WithCheckName(CertificateChainValidator.CERTIFICATE_CHECK).WithMessage(CertificateChainValidator + .CERTIFICATE_TRUSTED, (i) => rootCert.GetSubjectDN()).WithCertificate(rootCert)).HasLogItem((al) => al + .WithCheckName(OCSPValidator.OCSP_CHECK).WithMessage(OCSPValidator.OCSP_RESPONDER_TRUSTED)).HasLogItem + ((al) => al.WithCheckName(OCSPValidator.OCSP_CHECK).WithMessage(OCSPValidator.OCSP_RESPONDER_IS_CA))); } [NUnit.Framework.Test] @@ -327,7 +452,7 @@ public virtual void ValidateMultipleSignaturesUsingLastKnownPoETest() { using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "signatureSigningCertExpired.pdf" ))) { SignatureValidator signatureValidator = new ValidatorChainBuilder().WithTrustedCertificates(JavaUtil.ArraysAsList - (trustedCerts)).WithRevocationDataValidator(new MockRevocationDataValidator()).BuildSignatureValidator + (trustedCerts)).WithRevocationDataValidatorFactory(() => new MockRevocationDataValidator()).BuildSignatureValidator (document); ValidationReport report = signatureValidator.ValidateSignatures(); AssertValidationReport.AssertThat(report, (r) => r.HasStatus(ValidationReport.ValidationResult.VALID).HasNumberOfLogs @@ -346,8 +471,8 @@ public virtual void StopAfterTimestampChainValidationFailureTest() { using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "validDocWithTimestamp.pdf"))) { SignatureValidator signatureValidator = new ValidatorChainBuilder().WithSignatureValidationProperties(new SignatureValidationProperties().SetContinueAfterFailure(ValidatorContexts.All(), CertificateSources.All - (), false)).WithRevocationDataValidator(new MockRevocationDataValidator()).BuildSignatureValidator(document - ); + (), false)).WithRevocationDataValidatorFactory(() => new MockRevocationDataValidator()).BuildSignatureValidator + (document); ValidationReport report = signatureValidator.ValidateSignatures(); AssertValidationReport.AssertThat(report, (r) => r.HasStatus(ValidationReport.ValidationResult.INDETERMINATE ).HasNumberOfLogs(3).HasNumberOfFailures(2).HasLogItem((l) => l.WithCheckName(SignatureValidator.SIGNATURE_VERIFICATION @@ -375,7 +500,9 @@ private void AddRevDataClients() { builder2.SetNextUpdate(DateTimeUtil.GetCalendar(currentDate.AddDays(30))); TestOcspClient ocspClient = new TestOcspClient().AddBuilderForCertIssuer(rootCert, builder1).AddBuilderForCertIssuer (intermediateCert, builder2); - builder.GetRevocationDataValidator().AddOcspClient(ocspClient); + RevocationDataValidator revocationDataValidator = builder.GetRevocationDataValidator().AddOcspClient(ocspClient + ); + builder.WithRevocationDataValidatorFactory(() => revocationDataValidator); parameters.SetRevocationOnlineFetching(ValidatorContexts.All(), CertificateSources.All(), TimeBasedContexts .All(), SignatureValidationProperties.OnlineFetching.NEVER_FETCH); } diff --git a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/SignatureValidatorTest.cs b/itext.tests/itext.sign.tests/itext/signatures/validation/SignatureValidatorTest.cs similarity index 92% rename from itext.tests/itext.sign.tests/itext/signatures/validation/v1/SignatureValidatorTest.cs rename to itext.tests/itext.sign.tests/itext/signatures/validation/SignatureValidatorTest.cs index b89645c76d..2c9b15ef3b 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/SignatureValidatorTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/validation/SignatureValidatorTest.cs @@ -29,23 +29,24 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Bouncycastle.Security; using iText.Commons.Utils; +using iText.Kernel.Exceptions; using iText.Kernel.Pdf; using iText.Signatures.Testutils; using iText.Signatures.Testutils.Builder; using iText.Signatures.Testutils.Client; -using iText.Signatures.Validation.V1.Context; -using iText.Signatures.Validation.V1.Mocks; -using iText.Signatures.Validation.V1.Report; +using iText.Signatures.Validation.Context; +using iText.Signatures.Validation.Mocks; +using iText.Signatures.Validation.Report; using iText.Test; -namespace iText.Signatures.Validation.V1 { +namespace iText.Signatures.Validation { [NUnit.Framework.Category("BouncyCastleUnitTest")] public class SignatureValidatorTest : ExtendedITextTest { private static readonly String CERTS_SRC = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext - .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/v1/SignatureValidatorTest/certs/"; + .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/SignatureValidatorTest/certs/"; private static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext - .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/v1/SignatureValidatorTest/"; + .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/SignatureValidatorTest/"; private static readonly IBouncyCastleFactory FACTORY = BouncyCastleFactoryCreator.GetFactory(); @@ -71,9 +72,10 @@ public virtual void SetUp() { parameters = new SignatureValidationProperties(); mockCertificateRetriever = new MockIssuingCertificateRetriever(); mockDocumentRevisionsValidator = new MockDocumentRevisionsValidator(); - builder = new ValidatorChainBuilder().WithIssuingCertificateRetriever(mockCertificateRetriever).WithSignatureValidationProperties - (parameters).WithCertificateChainValidator(mockCertificateChainValidator).WithRevocationDataValidator( - new MockRevocationDataValidator()).WithDocumentRevisionsValidator(mockDocumentRevisionsValidator); + builder = new ValidatorChainBuilder().WithIssuingCertificateRetrieverFactory(() => mockCertificateRetriever + ).WithSignatureValidationProperties(parameters).WithCertificateChainValidatorFactory(() => mockCertificateChainValidator + ).WithRevocationDataValidatorFactory(() => new MockRevocationDataValidator()).WithDocumentRevisionsValidatorFactory + (() => mockDocumentRevisionsValidator); } [NUnit.Framework.Test] @@ -367,8 +369,6 @@ public virtual void TimeStampChainValidatorFailureTest() { String chainName = CERTS_SRC + "validCertsChain.pem"; IX509Certificate[] certificateChain = PemFileHelper.ReadFirstChain(chainName); IX509Certificate rootCert = (IX509Certificate)certificateChain[2]; - IX509Certificate intermediateCert = (IX509Certificate)certificateChain[1]; - IX509Certificate signCert = (IX509Certificate)certificateChain[0]; using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "timestampSignatureDoc.pdf"))) { mockCertificateRetriever.SetTrustedCertificates(JavaCollectionsUtil.SingletonList(rootCert)); mockCertificateChainValidator.OnCallDo((c) => { @@ -453,5 +453,32 @@ public virtual void DocumentRevisionValidatorFailureTest() { ))); } } + + [NUnit.Framework.Test] + public virtual void ThrowExceptionOnTheSecondValidationAttempt() { + using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "timestampSignatureDoc.pdf"))) { + SignatureValidator signatureValidator = builder.BuildSignatureValidator(document); + signatureValidator.ValidateSignatures(); + Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => signatureValidator.ValidateSignatures + ()); + NUnit.Framework.Assert.AreEqual(SignatureValidator.VALIDATION_PERFORMED, exception.Message); + exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => signatureValidator.ValidateSignature( + "Signature1")); + NUnit.Framework.Assert.AreEqual(SignatureValidator.VALIDATION_PERFORMED, exception.Message); + } + } + + [NUnit.Framework.Test] + public virtual void SignatureWithSpecifiedNameNotFound() { + ValidationReport report; + using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "timestampSignatureDoc.pdf"))) { + SignatureValidator signatureValidator = builder.BuildSignatureValidator(document); + report = signatureValidator.ValidateSignature("Invalid signature name"); + } + AssertValidationReport.AssertThat(report, (a) => a.HasStatus(ValidationReport.ValidationResult.INDETERMINATE + ).HasNumberOfLogs(1).HasNumberOfFailures(1).HasLogItem((l) => l.WithCheckName(SignatureValidator.SIGNATURE_VERIFICATION + ).WithMessage(SignatureValidator.SIGNATURE_NOT_FOUND, (p) => "Invalid signature name").WithStatus(ReportItem.ReportItemStatus + .INDETERMINATE))); + } } } diff --git a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/ValidationMetaInfoEventsTest.cs b/itext.tests/itext.sign.tests/itext/signatures/validation/ValidationMetaInfoEventsTest.cs similarity index 97% rename from itext.tests/itext.sign.tests/itext/signatures/validation/v1/ValidationMetaInfoEventsTest.cs rename to itext.tests/itext.sign.tests/itext/signatures/validation/ValidationMetaInfoEventsTest.cs index 90022451c4..f909ceb387 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/ValidationMetaInfoEventsTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/validation/ValidationMetaInfoEventsTest.cs @@ -27,14 +27,14 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Actions.Contexts; using iText.Kernel.Actions.Events; using iText.Kernel.Pdf; -using iText.Signatures.Validation.V1.Context; +using iText.Signatures.Validation.Context; using iText.Test; -namespace iText.Signatures.Validation.V1 { +namespace iText.Signatures.Validation { [NUnit.Framework.Category("IntegrationTest")] public class ValidationMetaInfoEventsTest : ExtendedITextTest { private static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext - .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/v1/ValidationMetaInfoEventsTest/"; + .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/ValidationMetaInfoEventsTest/"; private static ValidationMetaInfoEventsTest.StoreEventsHandler handler; diff --git a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/context/ValidationContextTest.cs b/itext.tests/itext.sign.tests/itext/signatures/validation/context/ValidationContextTest.cs similarity index 99% rename from itext.tests/itext.sign.tests/itext/signatures/validation/v1/context/ValidationContextTest.cs rename to itext.tests/itext.sign.tests/itext/signatures/validation/context/ValidationContextTest.cs index 6ab6384e90..7575fc3cbb 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/context/ValidationContextTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/validation/context/ValidationContextTest.cs @@ -22,7 +22,7 @@ You should have received a copy of the GNU Affero General Public License */ using iText.Test; -namespace iText.Signatures.Validation.V1.Context { +namespace iText.Signatures.Validation.Context { [NUnit.Framework.Category("UnitTest")] public class ValidationContextTest : ExtendedITextTest { [NUnit.Framework.Test] diff --git a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/extensions/CertificateExtensionTest.cs b/itext.tests/itext.sign.tests/itext/signatures/validation/extensions/CertificateExtensionTest.cs similarity index 98% rename from itext.tests/itext.sign.tests/itext/signatures/validation/v1/extensions/CertificateExtensionTest.cs rename to itext.tests/itext.sign.tests/itext/signatures/validation/extensions/CertificateExtensionTest.cs index 6e6d5b29d2..d5bf2500eb 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/extensions/CertificateExtensionTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/validation/extensions/CertificateExtensionTest.cs @@ -24,15 +24,15 @@ You should have received a copy of the GNU Affero General Public License using iText.Bouncycastleconnector; using iText.Commons.Bouncycastle; using iText.Commons.Bouncycastle.Cert; -using iText.Signatures; +using iText.Kernel.Crypto; using iText.Signatures.Testutils; using iText.Test; -namespace iText.Signatures.Validation.V1.Extensions { +namespace iText.Signatures.Validation.Extensions { [NUnit.Framework.Category("BouncyCastleUnitTest")] public class CertificateExtensionTest : ExtendedITextTest { private static readonly String certsSrc = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext - .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/v1/extensions/CertificateExtensionTest/"; + .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/extensions/CertificateExtensionTest/"; private static readonly IBouncyCastleFactory FACTORY = BouncyCastleFactoryCreator.GetFactory(); diff --git a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/extensions/ExtendedKeyUsageExtensionTest.cs b/itext.tests/itext.sign.tests/itext/signatures/validation/extensions/ExtendedKeyUsageExtensionTest.cs similarity index 98% rename from itext.tests/itext.sign.tests/itext/signatures/validation/v1/extensions/ExtendedKeyUsageExtensionTest.cs rename to itext.tests/itext.sign.tests/itext/signatures/validation/extensions/ExtendedKeyUsageExtensionTest.cs index 74c7c593f5..de699abb3f 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/extensions/ExtendedKeyUsageExtensionTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/validation/extensions/ExtendedKeyUsageExtensionTest.cs @@ -26,11 +26,11 @@ You should have received a copy of the GNU Affero General Public License using iText.Signatures.Testutils; using iText.Test; -namespace iText.Signatures.Validation.V1.Extensions { +namespace iText.Signatures.Validation.Extensions { [NUnit.Framework.Category("BouncyCastleUnitTest")] public class ExtendedKeyUsageExtensionTest : ExtendedITextTest { private static readonly String certsSrc = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext - .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/v1/extensions/ExtendedKeyUsageExtensionTest/"; + .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/extensions/ExtendedKeyUsageExtensionTest/"; [NUnit.Framework.Test] public virtual void ExtendedKeyUsageNotSetExpectedTest() { diff --git a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/extensions/KeyUsageExtensionTest.cs b/itext.tests/itext.sign.tests/itext/signatures/validation/extensions/KeyUsageExtensionTest.cs similarity index 98% rename from itext.tests/itext.sign.tests/itext/signatures/validation/v1/extensions/KeyUsageExtensionTest.cs rename to itext.tests/itext.sign.tests/itext/signatures/validation/extensions/KeyUsageExtensionTest.cs index 6f2878bf73..c246b82a9b 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/extensions/KeyUsageExtensionTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/validation/extensions/KeyUsageExtensionTest.cs @@ -26,11 +26,11 @@ You should have received a copy of the GNU Affero General Public License using iText.Signatures.Testutils; using iText.Test; -namespace iText.Signatures.Validation.V1.Extensions { +namespace iText.Signatures.Validation.Extensions { [NUnit.Framework.Category("BouncyCastleUnitTest")] public class KeyUsageExtensionTest : ExtendedITextTest { private static readonly String certsSrc = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext - .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/v1/extensions/KeyUsageExtensionTest/"; + .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/extensions/KeyUsageExtensionTest/"; [NUnit.Framework.Test] public virtual void KeyUsageNotSetExpectedTest() { diff --git a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/mocks/MockChainValidator.cs b/itext.tests/itext.sign.tests/itext/signatures/validation/mocks/MockChainValidator.cs similarity index 93% rename from itext.tests/itext.sign.tests/itext/signatures/validation/v1/mocks/MockChainValidator.cs rename to itext.tests/itext.sign.tests/itext/signatures/validation/mocks/MockChainValidator.cs index 1c8666ba2f..daffccc471 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/mocks/MockChainValidator.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/validation/mocks/MockChainValidator.cs @@ -23,11 +23,11 @@ You should have received a copy of the GNU Affero General Public License using System; using System.Collections.Generic; using iText.Commons.Bouncycastle.Cert; -using iText.Signatures.Validation.V1; -using iText.Signatures.Validation.V1.Context; -using iText.Signatures.Validation.V1.Report; +using iText.Signatures.Validation; +using iText.Signatures.Validation.Context; +using iText.Signatures.Validation.Report; -namespace iText.Signatures.Validation.V1.Mocks { +namespace iText.Signatures.Validation.Mocks { public class MockChainValidator : CertificateChainValidator { public IList verificationCalls = new List(); diff --git a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/mocks/MockCrlValidator.cs b/itext.tests/itext.sign.tests/itext/signatures/validation/mocks/MockCrlValidator.cs similarity index 92% rename from itext.tests/itext.sign.tests/itext/signatures/validation/v1/mocks/MockCrlValidator.cs rename to itext.tests/itext.sign.tests/itext/signatures/validation/mocks/MockCrlValidator.cs index eef76029d1..e6f4c51eda 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/mocks/MockCrlValidator.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/validation/mocks/MockCrlValidator.cs @@ -24,11 +24,11 @@ You should have received a copy of the GNU Affero General Public License using System.Collections.Generic; using iText.Commons.Bouncycastle.Cert; using iText.Commons.Utils; -using iText.Signatures.Validation.V1; -using iText.Signatures.Validation.V1.Context; -using iText.Signatures.Validation.V1.Report; +using iText.Signatures.Validation; +using iText.Signatures.Validation.Context; +using iText.Signatures.Validation.Report; -namespace iText.Signatures.Validation.V1.Mocks { +namespace iText.Signatures.Validation.Mocks { public class MockCrlValidator : CRLValidator { public readonly IList calls = new List (); @@ -37,7 +37,7 @@ public class MockCrlValidator : CRLValidator { /// /// Creates new - /// + /// /// instance. /// public MockCrlValidator() diff --git a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/mocks/MockDocumentRevisionsValidator.cs b/itext.tests/itext.sign.tests/itext/signatures/validation/mocks/MockDocumentRevisionsValidator.cs similarity index 94% rename from itext.tests/itext.sign.tests/itext/signatures/validation/v1/mocks/MockDocumentRevisionsValidator.cs rename to itext.tests/itext.sign.tests/itext/signatures/validation/mocks/MockDocumentRevisionsValidator.cs index bd1825cb16..153e34b3c2 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/mocks/MockDocumentRevisionsValidator.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/validation/mocks/MockDocumentRevisionsValidator.cs @@ -23,11 +23,11 @@ You should have received a copy of the GNU Affero General Public License using System; using System.Collections.Generic; using iText.Kernel.Pdf; -using iText.Signatures.Validation.V1; -using iText.Signatures.Validation.V1.Context; -using iText.Signatures.Validation.V1.Report; +using iText.Signatures.Validation; +using iText.Signatures.Validation.Context; +using iText.Signatures.Validation.Report; -namespace iText.Signatures.Validation.V1.Mocks { +namespace iText.Signatures.Validation.Mocks { public class MockDocumentRevisionsValidator : DocumentRevisionsValidator { public Action onCallHandler; diff --git a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/mocks/MockIssuingCertificateRetriever.cs b/itext.tests/itext.sign.tests/itext/signatures/validation/mocks/MockIssuingCertificateRetriever.cs similarity index 74% rename from itext.tests/itext.sign.tests/itext/signatures/validation/v1/mocks/MockIssuingCertificateRetriever.cs rename to itext.tests/itext.sign.tests/itext/signatures/validation/mocks/MockIssuingCertificateRetriever.cs index 58cd6c56fa..aedc046b96 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/mocks/MockIssuingCertificateRetriever.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/validation/mocks/MockIssuingCertificateRetriever.cs @@ -25,10 +25,11 @@ You should have received a copy of the GNU Affero General Public License using System.IO; using iText.Commons.Bouncycastle.Asn1.Ocsp; using iText.Commons.Bouncycastle.Cert; +using iText.Commons.Utils; using iText.Signatures; -using iText.Signatures.Validation.V1; +using iText.Signatures.Validation; -namespace iText.Signatures.Validation.V1.Mocks { +namespace iText.Signatures.Validation.Mocks { public class MockIssuingCertificateRetriever : IssuingCertificateRetriever { private readonly IssuingCertificateRetriever wrapped; @@ -36,6 +37,8 @@ public class MockIssuingCertificateRetriever : IssuingCertificateRetriever { public IList getCrlIssuerCertificatesCalls = new List(); + public IList getCrlIssuerCertificatesByNameCalls = new List(); + public IList retrieveIssuerCertificateCalls = new List(); public IList retrieveOCSPResponderCertificateCalls = new List(); @@ -59,9 +62,11 @@ public class MockIssuingCertificateRetriever : IssuingCertificateRetriever { private Func getCrlIssuerCertificatesHandler; + private Func getCrlIssuerCertificatesByNameHandler; + private Func retrieveIssuerCertificateHandler; - private Func retrieveOCSPResponderCertificateHandler; + private Func> retrieveOCSPResponderCertificateHandler; private Action> setTrustedCertificatesHandler; @@ -105,10 +110,22 @@ public override IX509Certificate[] GetCrlIssuerCertificates(IX509Crl crl) { return new IX509Certificate[0]; } - public override IX509Certificate RetrieveIssuerCertificate(IX509Certificate certificate) { + public override IX509Certificate[][] GetCrlIssuerCertificatesByName(IX509Crl crl) { + getCrlIssuerCertificatesByNameCalls.Add(crl); + if (getCrlIssuerCertificatesByNameHandler != null) { + return getCrlIssuerCertificatesByNameHandler.Invoke(crl); + } + if (wrapped != null) { + return wrapped.GetCrlIssuerCertificatesByName(crl); + } + return new IX509Certificate[0][]; + } + + public override IList RetrieveIssuerCertificate(IX509Certificate certificate) { retrieveIssuerCertificateCalls.Add(certificate); if (retrieveIssuerCertificateHandler != null) { - return retrieveIssuerCertificateHandler.Invoke(certificate); + return JavaCollectionsUtil.SingletonList((IX509Certificate)retrieveIssuerCertificateHandler.Invoke(certificate + )); } if (wrapped != null) { return wrapped.RetrieveIssuerCertificate(certificate); @@ -116,13 +133,14 @@ public override IX509Certificate RetrieveIssuerCertificate(IX509Certificate cert return null; } - public override IX509Certificate RetrieveOCSPResponderCertificate(IBasicOcspResponse ocspResp) { + public override ICollection RetrieveOCSPResponderByNameCertificate(IBasicOcspResponse ocspResp + ) { retrieveOCSPResponderCertificateCalls.Add(ocspResp); if (retrieveOCSPResponderCertificateHandler != null) { return retrieveOCSPResponderCertificateHandler.Invoke(ocspResp); } if (wrapped != null) { - return wrapped.RetrieveOCSPResponderCertificate(ocspResp); + return wrapped.RetrieveOCSPResponderByNameCertificate(ocspResp); } return null; } @@ -190,61 +208,67 @@ protected internal override Stream GetIssuerCertByURI(String uri) { return null; } - public virtual iText.Signatures.Validation.V1.Mocks.MockIssuingCertificateRetriever OnRetrieveMissingCertificatesDo + public virtual iText.Signatures.Validation.Mocks.MockIssuingCertificateRetriever OnRetrieveMissingCertificatesDo (Func callback) { retrieveMissingCertificatesHandler = callback; return this; } - public virtual iText.Signatures.Validation.V1.Mocks.MockIssuingCertificateRetriever OngetCrlIssuerCertificatesDo + public virtual iText.Signatures.Validation.Mocks.MockIssuingCertificateRetriever OngetCrlIssuerCertificatesDo (Func callback) { getCrlIssuerCertificatesHandler = callback; return this; } - public virtual iText.Signatures.Validation.V1.Mocks.MockIssuingCertificateRetriever OnRetrieveIssuerCertificateDo + public virtual iText.Signatures.Validation.Mocks.MockIssuingCertificateRetriever OngetCrlIssuerCertificatesByNameDo + (Func callback) { + getCrlIssuerCertificatesByNameHandler = callback; + return this; + } + + public virtual iText.Signatures.Validation.Mocks.MockIssuingCertificateRetriever OnRetrieveIssuerCertificateDo (Func callback) { retrieveIssuerCertificateHandler = callback; return this; } - public virtual iText.Signatures.Validation.V1.Mocks.MockIssuingCertificateRetriever OnRetrieveOCSPResponderCertificateDo - (Func callback) { + public virtual iText.Signatures.Validation.Mocks.MockIssuingCertificateRetriever OnRetrieveOCSPResponderCertificateDo + (Func> callback) { retrieveOCSPResponderCertificateHandler = callback; return this; } - public virtual iText.Signatures.Validation.V1.Mocks.MockIssuingCertificateRetriever OnSetTrustedCertificatesDo + public virtual iText.Signatures.Validation.Mocks.MockIssuingCertificateRetriever OnSetTrustedCertificatesDo (Action> callback) { setTrustedCertificatesHandler = callback; return this; } - public virtual iText.Signatures.Validation.V1.Mocks.MockIssuingCertificateRetriever OnAddKnownCertificatesDo - (Action> callback) { + public virtual iText.Signatures.Validation.Mocks.MockIssuingCertificateRetriever OnAddKnownCertificatesDo( + Action> callback) { addKnownCertificatesHandler = callback; return this; } - public virtual iText.Signatures.Validation.V1.Mocks.MockIssuingCertificateRetriever OnAddTrustedCertificatesDo + public virtual iText.Signatures.Validation.Mocks.MockIssuingCertificateRetriever OnAddTrustedCertificatesDo (Action> callback) { addTrustedCertificatesHandler = callback; return this; } - public virtual iText.Signatures.Validation.V1.Mocks.MockIssuingCertificateRetriever OnIsCertificateTrustedDo - (Func callback) { + public virtual iText.Signatures.Validation.Mocks.MockIssuingCertificateRetriever OnIsCertificateTrustedDo( + Func callback) { isCertificateTrustedDoHandler = callback; return this; } - public virtual iText.Signatures.Validation.V1.Mocks.MockIssuingCertificateRetriever OnGetTrustedCertificatesStoreDo + public virtual iText.Signatures.Validation.Mocks.MockIssuingCertificateRetriever OnGetTrustedCertificatesStoreDo (Func callBack) { getTrustedCertificatesStoreHandler = callBack; return this; } - public virtual iText.Signatures.Validation.V1.Mocks.MockIssuingCertificateRetriever OnGetIssuerCertByURIHandlerDo + public virtual iText.Signatures.Validation.Mocks.MockIssuingCertificateRetriever OnGetIssuerCertByURIHandlerDo (Func callBack) { getIssuerCertByURIHandler = callBack; return this; diff --git a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/mocks/MockOCSPValidator.cs b/itext.tests/itext.sign.tests/itext/signatures/validation/mocks/MockOCSPValidator.cs similarity index 93% rename from itext.tests/itext.sign.tests/itext/signatures/validation/v1/mocks/MockOCSPValidator.cs rename to itext.tests/itext.sign.tests/itext/signatures/validation/mocks/MockOCSPValidator.cs index 9699408b77..d27c63fbac 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/mocks/MockOCSPValidator.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/validation/mocks/MockOCSPValidator.cs @@ -26,11 +26,11 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Cert; using iText.Commons.Bouncycastle.Cert.Ocsp; using iText.Commons.Utils; -using iText.Signatures.Validation.V1; -using iText.Signatures.Validation.V1.Context; -using iText.Signatures.Validation.V1.Report; +using iText.Signatures.Validation; +using iText.Signatures.Validation.Context; +using iText.Signatures.Validation.Report; -namespace iText.Signatures.Validation.V1.Mocks { +namespace iText.Signatures.Validation.Mocks { public class MockOCSPValidator : OCSPValidator { public readonly IList calls = new List(); @@ -39,7 +39,7 @@ public class MockOCSPValidator : OCSPValidator { /// /// Creates new - /// + /// /// instance. /// public MockOCSPValidator() diff --git a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/mocks/MockRevocationDataValidator.cs b/itext.tests/itext.sign.tests/itext/signatures/validation/mocks/MockRevocationDataValidator.cs similarity index 85% rename from itext.tests/itext.sign.tests/itext/signatures/validation/v1/mocks/MockRevocationDataValidator.cs rename to itext.tests/itext.sign.tests/itext/signatures/validation/mocks/MockRevocationDataValidator.cs index 4cbab47d6e..6b22286fc0 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/mocks/MockRevocationDataValidator.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/validation/mocks/MockRevocationDataValidator.cs @@ -24,11 +24,11 @@ You should have received a copy of the GNU Affero General Public License using System.Collections.Generic; using iText.Commons.Bouncycastle.Cert; using iText.Signatures; -using iText.Signatures.Validation.V1; -using iText.Signatures.Validation.V1.Context; -using iText.Signatures.Validation.V1.Report; +using iText.Signatures.Validation; +using iText.Signatures.Validation.Context; +using iText.Signatures.Validation.Report; -namespace iText.Signatures.Validation.V1.Mocks { +namespace iText.Signatures.Validation.Mocks { public class MockRevocationDataValidator : RevocationDataValidator { public IList crlClientsAdded = new List(); @@ -45,7 +45,7 @@ public class MockRevocationDataValidator : RevocationDataValidator { /// /// Creates new - /// + /// /// instance to validate certificate revocation data. /// public MockRevocationDataValidator() @@ -78,19 +78,19 @@ public override void Validate(ValidationReport report, ValidationContext context } } - public virtual iText.Signatures.Validation.V1.Mocks.MockRevocationDataValidator OnValidateDo(Action callBack) { onValidateHandler = callBack; return this; } - public virtual iText.Signatures.Validation.V1.Mocks.MockRevocationDataValidator OnAddCerlClientDo(Action callBack) { onAddCrlClientHandler = callBack; return this; } - public virtual iText.Signatures.Validation.V1.Mocks.MockRevocationDataValidator OnAddOCSPClientDo(Action callBack) { onAddOCSPClientHandler = callBack; return this; diff --git a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/mocks/MockSignatureValidationProperties.cs b/itext.tests/itext.sign.tests/itext/signatures/validation/mocks/MockSignatureValidationProperties.cs similarity index 88% rename from itext.tests/itext.sign.tests/itext/signatures/validation/v1/mocks/MockSignatureValidationProperties.cs rename to itext.tests/itext.sign.tests/itext/signatures/validation/mocks/MockSignatureValidationProperties.cs index 6b2a18223c..b9187fcd9b 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/mocks/MockSignatureValidationProperties.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/validation/mocks/MockSignatureValidationProperties.cs @@ -22,11 +22,11 @@ You should have received a copy of the GNU Affero General Public License */ using System; using System.Collections.Generic; -using iText.Signatures.Validation.V1; -using iText.Signatures.Validation.V1.Context; -using iText.Signatures.Validation.V1.Extensions; +using iText.Signatures.Validation; +using iText.Signatures.Validation.Context; +using iText.Signatures.Validation.Extensions; -namespace iText.Signatures.Validation.V1.Mocks { +namespace iText.Signatures.Validation.Mocks { /// This mock class wrapper a real SignatureValidationProperties instance. /// /// This mock class wrapper a real SignatureValidationProperties instance. @@ -101,25 +101,25 @@ public override SignatureValidationProperties.OnlineFetching GetRevocationOnline return wrappedProperties.GetRevocationOnlineFetching(validationContext); } - public virtual iText.Signatures.Validation.V1.Mocks.MockSignatureValidationProperties AddContinueAfterFailureResponse + public virtual iText.Signatures.Validation.Mocks.MockSignatureValidationProperties AddContinueAfterFailureResponse (bool value) { continueAfterFailureResponses.Add(value); return this; } - public virtual iText.Signatures.Validation.V1.Mocks.MockSignatureValidationProperties AddFreshnessResponse - (TimeSpan freshness) { + public virtual iText.Signatures.Validation.Mocks.MockSignatureValidationProperties AddFreshnessResponse(TimeSpan + freshness) { freshnessResponses.Add(freshness); return this; } - public virtual iText.Signatures.Validation.V1.Mocks.MockSignatureValidationProperties AddRequiredExtensionsResponses + public virtual iText.Signatures.Validation.Mocks.MockSignatureValidationProperties AddRequiredExtensionsResponses (IList requiredExtensions) { requiredExtensionsResponses.Add(requiredExtensions); return this; } - public virtual iText.Signatures.Validation.V1.Mocks.MockSignatureValidationProperties AddRevocationOnlineFetchingResponse + public virtual iText.Signatures.Validation.Mocks.MockSignatureValidationProperties AddRevocationOnlineFetchingResponse (SignatureValidationProperties.OnlineFetching value) { revocationOnlineFetchingResponses.Add(value); return this; diff --git a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/mocks/MockTrustedCertificatesStore.cs b/itext.tests/itext.sign.tests/itext/signatures/validation/mocks/MockTrustedCertificatesStore.cs similarity index 71% rename from itext.tests/itext.sign.tests/itext/signatures/validation/v1/mocks/MockTrustedCertificatesStore.cs rename to itext.tests/itext.sign.tests/itext/signatures/validation/mocks/MockTrustedCertificatesStore.cs index 87b622e7a1..929b6f7e02 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/mocks/MockTrustedCertificatesStore.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/validation/mocks/MockTrustedCertificatesStore.cs @@ -23,9 +23,9 @@ You should have received a copy of the GNU Affero General Public License using System; using System.Collections.Generic; using iText.Commons.Bouncycastle.Cert; -using iText.Signatures.Validation.V1; +using iText.Signatures.Validation; -namespace iText.Signatures.Validation.V1.Mocks { +namespace iText.Signatures.Validation.Mocks { public class MockTrustedCertificatesStore : TrustedCertificatesStore { private readonly TrustedCertificatesStore wrapped; @@ -63,17 +63,17 @@ public class MockTrustedCertificatesStore : TrustedCertificatesStore { private Func isCertificateTrustedForCAHandler; - private Func getGenerallyTrustedCertificateHandler; + private Func> getGenerallyTrustedCertificateHandler; - private Func getCertificateTrustedForOcspHandler; + private Func> getCertificateTrustedForOcspHandler; - private Func getCertificateTrustedForCrlHandler; + private Func> getCertificateTrustedForCrlHandler; - private Func getCertificateTrustedForTimestampHandler; + private Func> getCertificateTrustedForTimestampHandler; - private Func getCertificateTrustedForCAHandler; + private Func> getCertificateTrustedForCAHandler; - private Func getKnownCertificateHandler; + private Func> getKnownCertificateHandler; private Func> getAllTrustedCertificatesHandler; @@ -140,68 +140,68 @@ public override bool IsCertificateTrustedForCA(IX509Certificate certificate) { return true; } - public override IX509Certificate GetGenerallyTrustedCertificate(String certificateName) { + public override ICollection GetGenerallyTrustedCertificates(String certificateName) { getGenerallyTrustedCertificateCalls.Add(certificateName); if (getGenerallyTrustedCertificateHandler != null) { return getGenerallyTrustedCertificateHandler.Invoke(certificateName); } if (wrapped != null) { - return wrapped.GetGenerallyTrustedCertificate(certificateName); + return wrapped.GetGenerallyTrustedCertificates(certificateName); } return null; } - public override IX509Certificate GetCertificateTrustedForOcsp(String certificateName) { + public override ICollection GetCertificatesTrustedForOcsp(String certificateName) { getCertificateTrustedForOcspCalls.Add(certificateName); if (getCertificateTrustedForOcspHandler != null) { return getCertificateTrustedForOcspHandler.Invoke(certificateName); } if (wrapped != null) { - return wrapped.GetCertificateTrustedForOcsp(certificateName); + return wrapped.GetCertificatesTrustedForOcsp(certificateName); } return null; } - public override IX509Certificate GetCertificateTrustedForCrl(String certificateName) { + public override ICollection GetCertificatesTrustedForCrl(String certificateName) { getCertificateTrustedForCrlCalls.Add(certificateName); if (getCertificateTrustedForCrlHandler != null) { return getCertificateTrustedForCrlHandler.Invoke(certificateName); } if (wrapped != null) { - return wrapped.GetCertificateTrustedForCrl(certificateName); + return wrapped.GetCertificatesTrustedForCrl(certificateName); } return null; } - public override IX509Certificate GetCertificateTrustedForTimestamp(String certificateName) { + public override ICollection GetCertificatesTrustedForTimestamp(String certificateName) { getCertificateTrustedForTimestampCalls.Add(certificateName); if (getCertificateTrustedForTimestampHandler != null) { return getCertificateTrustedForTimestampHandler.Invoke(certificateName); } if (wrapped != null) { - return wrapped.GetCertificateTrustedForTimestamp(certificateName); + return wrapped.GetCertificatesTrustedForTimestamp(certificateName); } return null; } - public override IX509Certificate GetCertificateTrustedForCA(String certificateName) { + public override ICollection GetCertificatesTrustedForCA(String certificateName) { getCertificateTrustedForCACalls.Add(certificateName); if (getCertificateTrustedForCAHandler != null) { return getCertificateTrustedForCAHandler.Invoke(certificateName); } if (wrapped != null) { - return wrapped.GetCertificateTrustedForCA(certificateName); + return wrapped.GetCertificatesTrustedForCA(certificateName); } return null; } - public override IX509Certificate GetKnownCertificate(String certificateName) { + public override ICollection GetKnownCertificates(String certificateName) { getKnownCertificateCalls.Add(certificateName); if (getKnownCertificateHandler != null) { return getKnownCertificateHandler.Invoke(certificateName); } if (wrapped != null) { - return wrapped.GetKnownCertificate(certificateName); + return wrapped.GetKnownCertificates(certificateName); } return null; } @@ -217,73 +217,73 @@ public override ICollection GetAllTrustedCertificates() { return null; } - public virtual iText.Signatures.Validation.V1.Mocks.MockTrustedCertificatesStore OnIsCertificateGenerallyTrustedDo + public virtual iText.Signatures.Validation.Mocks.MockTrustedCertificatesStore OnIsCertificateGenerallyTrustedDo (Func callBack) { isCertificateGenerallyTrustedHandler = callBack; return this; } - public virtual iText.Signatures.Validation.V1.Mocks.MockTrustedCertificatesStore OnIsCertificateTrustedForOcspDo + public virtual iText.Signatures.Validation.Mocks.MockTrustedCertificatesStore OnIsCertificateTrustedForOcspDo (Func callBack) { isCertificateTrustedForOcspHandler = callBack; return this; } - public virtual iText.Signatures.Validation.V1.Mocks.MockTrustedCertificatesStore OnIsCertificateTrustedForCrlDo + public virtual iText.Signatures.Validation.Mocks.MockTrustedCertificatesStore OnIsCertificateTrustedForCrlDo (Func callBack) { isCertificateTrustedForCrlHandler = callBack; return this; } - public virtual iText.Signatures.Validation.V1.Mocks.MockTrustedCertificatesStore OnIsCertificateTrustedForTimestampDo + public virtual iText.Signatures.Validation.Mocks.MockTrustedCertificatesStore OnIsCertificateTrustedForTimestampDo (Func callBack) { isCertificateTrustedForTimestampHandler = callBack; return this; } - public virtual iText.Signatures.Validation.V1.Mocks.MockTrustedCertificatesStore OnIsCertificateTrustedForCADo + public virtual iText.Signatures.Validation.Mocks.MockTrustedCertificatesStore OnIsCertificateTrustedForCADo (Func callBack) { isCertificateTrustedForCAHandler = callBack; return this; } - public virtual iText.Signatures.Validation.V1.Mocks.MockTrustedCertificatesStore OnGetGenerallyTrustedCertificateDo - (Func callBack) { + public virtual iText.Signatures.Validation.Mocks.MockTrustedCertificatesStore OnGetGenerallyTrustedCertificateDo + (Func> callBack) { getGenerallyTrustedCertificateHandler = callBack; return this; } - public virtual iText.Signatures.Validation.V1.Mocks.MockTrustedCertificatesStore OnGetCertificateTrustedForOcspDo - (Func callBack) { + public virtual iText.Signatures.Validation.Mocks.MockTrustedCertificatesStore OnGetCertificateTrustedForOcspDo + (Func> callBack) { getCertificateTrustedForOcspHandler = callBack; return this; } - public virtual iText.Signatures.Validation.V1.Mocks.MockTrustedCertificatesStore OnGetCertificateTrustedForCrlDo - (Func callBack) { + public virtual iText.Signatures.Validation.Mocks.MockTrustedCertificatesStore OnGetCertificateTrustedForCrlDo + (Func> callBack) { getCertificateTrustedForCrlHandler = callBack; return this; } - public virtual iText.Signatures.Validation.V1.Mocks.MockTrustedCertificatesStore OnGetCertificateTrustedForTimestampDo - (Func callBack) { + public virtual iText.Signatures.Validation.Mocks.MockTrustedCertificatesStore OnGetCertificateTrustedForTimestampDo + (Func> callBack) { getCertificateTrustedForTimestampHandler = callBack; return this; } - public virtual iText.Signatures.Validation.V1.Mocks.MockTrustedCertificatesStore OnGetCertificateTrustedForCADo - (Func callBack) { + public virtual iText.Signatures.Validation.Mocks.MockTrustedCertificatesStore OnGetCertificateTrustedForCADo + (Func> callBack) { getCertificateTrustedForCAHandler = callBack; return this; } - public virtual iText.Signatures.Validation.V1.Mocks.MockTrustedCertificatesStore OnGetKnownCertificateDo(Func - callBack) { + public virtual iText.Signatures.Validation.Mocks.MockTrustedCertificatesStore OnGetKnownCertificateDo(Func + > callBack) { getKnownCertificateHandler = callBack; return this; } - public virtual iText.Signatures.Validation.V1.Mocks.MockTrustedCertificatesStore OnGetAllTrustedCertificatesDo + public virtual iText.Signatures.Validation.Mocks.MockTrustedCertificatesStore OnGetAllTrustedCertificatesDo (Func> callBack) { getAllTrustedCertificatesHandler = callBack; return this; diff --git a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/report/ValidationReportTest.cs b/itext.tests/itext.sign.tests/itext/signatures/validation/report/ValidationReportTest.cs similarity index 99% rename from itext.tests/itext.sign.tests/itext/signatures/validation/v1/report/ValidationReportTest.cs rename to itext.tests/itext.sign.tests/itext/signatures/validation/report/ValidationReportTest.cs index edd75cfede..b9737a1832 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/report/ValidationReportTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/validation/report/ValidationReportTest.cs @@ -25,7 +25,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Signatures.Testutils; using iText.Test; -namespace iText.Signatures.Validation.V1.Report { +namespace iText.Signatures.Validation.Report { [NUnit.Framework.Category("BouncyCastleUnitTest")] public class ValidationReportTest : ExtendedITextTest { private static readonly String CERTS_SRC = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext diff --git a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/RevocationDataValidatorIntegrationTest.cs b/itext.tests/itext.sign.tests/itext/signatures/validation/v1/RevocationDataValidatorIntegrationTest.cs deleted file mode 100644 index 000810154c..0000000000 --- a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/RevocationDataValidatorIntegrationTest.cs +++ /dev/null @@ -1,111 +0,0 @@ -/* -This file is part of the iText (R) project. -Copyright (c) 1998-2024 Apryse Group NV -Authors: Apryse Software. - -This program is offered under a commercial and under the AGPL license. -For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. - -AGPL licensing: -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . -*/ -using System; -using iText.Bouncycastleconnector; -using iText.Commons.Bouncycastle; -using iText.Commons.Bouncycastle.Cert; -using iText.Commons.Bouncycastle.Crypto; -using iText.Commons.Utils; -using iText.Signatures; -using iText.Signatures.Testutils; -using iText.Signatures.Testutils.Builder; -using iText.Signatures.Testutils.Client; -using iText.Signatures.Validation.V1.Context; -using iText.Signatures.Validation.V1.Report; -using iText.Test; - -namespace iText.Signatures.Validation.V1 { - [NUnit.Framework.Category("BouncyCastleUnitTest")] - public class RevocationDataValidatorIntegrationTest : ExtendedITextTest { - private static readonly IBouncyCastleFactory FACTORY = BouncyCastleFactoryCreator.GetFactory(); - - private static readonly String SOURCE_FOLDER = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext - .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/v1/RevocationDataValidatorTest/"; - - private static readonly char[] PASSWORD = "testpassphrase".ToCharArray(); - - private static IX509Certificate caCert; - - private static IPrivateKey caPrivateKey; - - private static IX509Certificate checkCert; - - private static IX509Certificate responderCert; - - private static IPrivateKey ocspRespPrivateKey; - - private IssuingCertificateRetriever certificateRetriever; - - private SignatureValidationProperties parameters; - - private ValidatorChainBuilder validatorChainBuilder; - - private readonly ValidationContext baseContext = new ValidationContext(ValidatorContext.SIGNATURE_VALIDATOR - , CertificateSource.SIGNER_CERT, TimeBasedContext.PRESENT); - - [NUnit.Framework.OneTimeSetUp] - public static void Before() { - String rootCertFileName = SOURCE_FOLDER + "rootCert.pem"; - String checkCertFileName = SOURCE_FOLDER + "signCert.pem"; - String ocspResponderCertFileName = SOURCE_FOLDER + "ocspResponderCert.pem"; - caCert = (IX509Certificate)PemFileHelper.ReadFirstChain(rootCertFileName)[0]; - caPrivateKey = PemFileHelper.ReadFirstKey(rootCertFileName, PASSWORD); - checkCert = (IX509Certificate)PemFileHelper.ReadFirstChain(checkCertFileName)[0]; - responderCert = (IX509Certificate)PemFileHelper.ReadFirstChain(ocspResponderCertFileName)[0]; - ocspRespPrivateKey = PemFileHelper.ReadFirstKey(ocspResponderCertFileName, PASSWORD); - } - - [NUnit.Framework.SetUp] - public virtual void SetUp() { - certificateRetriever = new IssuingCertificateRetriever(); - parameters = new SignatureValidationProperties(); - validatorChainBuilder = new ValidatorChainBuilder().WithIssuingCertificateRetriever(certificateRetriever). - WithSignatureValidationProperties(parameters); - } - - [NUnit.Framework.Test] - public virtual void CrlWithOnlySomeReasonsTest() { - TestCrlBuilder builder1 = new TestCrlBuilder(caCert, caPrivateKey); - builder1.AddExtension(FACTORY.CreateExtensions().GetIssuingDistributionPoint(), true, FACTORY.CreateIssuingDistributionPoint - (null, false, false, FACTORY.CreateReasonFlags(CRLValidator.ALL_REASONS - 31), false, false)); - TestCrlBuilder builder2 = new TestCrlBuilder(caCert, caPrivateKey); - builder2.AddExtension(FACTORY.CreateExtensions().GetIssuingDistributionPoint(), true, FACTORY.CreateIssuingDistributionPoint - (null, false, false, FACTORY.CreateReasonFlags(31), false, false)); - TestCrlClient crlClient = new TestCrlClient().AddBuilderForCertIssuer(builder1).AddBuilderForCertIssuer(builder2 - ); - TestOcspResponseBuilder ocspBuilder = new TestOcspResponseBuilder(responderCert, ocspRespPrivateKey); - ocspBuilder.SetProducedAt(TimeTestUtil.TEST_DATE_TIME.AddDays(-100)); - certificateRetriever.SetTrustedCertificates(JavaCollectionsUtil.SingletonList(caCert)); - parameters.SetRevocationOnlineFetching(ValidatorContexts.All(), CertificateSources.All(), TimeBasedContexts - .All(), SignatureValidationProperties.OnlineFetching.NEVER_FETCH); - ValidationReport report = new ValidationReport(); - RevocationDataValidator validator = validatorChainBuilder.BuildRevocationDataValidator(); - validator.AddOcspClient(new TestOcspClient().AddBuilderForCertIssuer(caCert, ocspBuilder)).AddCrlClient(crlClient - ); - validator.Validate(report, baseContext, checkCert, TimeTestUtil.TEST_DATE_TIME); - AssertValidationReport.AssertThat(report, (a) => a.HasNumberOfFailures(0).HasLogItem((la) => la.WithCertificate - (checkCert).WithStatus(ReportItem.ReportItemStatus.INFO).WithMessage(CRLValidator.ONLY_SOME_REASONS_CHECKED - ))); - } - } -} diff --git a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/extensions/BasicConstraintsExtensionTest.cs b/itext.tests/itext.sign.tests/itext/signatures/validation/v1/extensions/BasicConstraintsExtensionTest.cs deleted file mode 100644 index d8c7f4a5f0..0000000000 --- a/itext.tests/itext.sign.tests/itext/signatures/validation/v1/extensions/BasicConstraintsExtensionTest.cs +++ /dev/null @@ -1,106 +0,0 @@ -/* -This file is part of the iText (R) project. -Copyright (c) 1998-2024 Apryse Group NV -Authors: Apryse Software. - -This program is offered under a commercial and under the AGPL license. -For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. - -AGPL licensing: -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . -*/ -using System; -using iText.Commons.Bouncycastle.Cert; -using iText.Signatures.Testutils; -using iText.Test; - -namespace iText.Signatures.Validation.V1.Extensions { - [NUnit.Framework.Category("BouncyCastleUnitTest")] - public class BasicConstraintsExtensionTest : ExtendedITextTest { - private static readonly String certsSrc = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext - .CurrentContext.TestDirectory) + "/resources/itext/signatures/validation/v1/extensions/BasicConstraintsExtensionTest/"; - - [NUnit.Framework.Test] - public virtual void BasicConstraintNotSetExpectedTest() { - String certName = certsSrc + "basicConstraintsNotSetCert.pem"; - IX509Certificate certificate = (IX509Certificate)PemFileHelper.ReadFirstChain(certName)[0]; - BasicConstraintsExtension extension = new BasicConstraintsExtension(-2); - NUnit.Framework.Assert.IsFalse(extension.ExistsInCertificate(certificate)); - } - - [NUnit.Framework.Test] - public virtual void BasicConstraintNotSetNotExpectedTest() { - String certName = certsSrc + "basicConstraintsNotSetCert.pem"; - IX509Certificate certificate = (IX509Certificate)PemFileHelper.ReadFirstChain(certName)[0]; - BasicConstraintsExtension extension = new BasicConstraintsExtension(10); - NUnit.Framework.Assert.IsFalse(extension.ExistsInCertificate(certificate)); - } - - [NUnit.Framework.Test] - public virtual void BasicConstraintMaxLengthExpectedTest() { - String certName = certsSrc + "basicConstraintsMaxCert.pem"; - IX509Certificate certificate = (IX509Certificate)PemFileHelper.ReadFirstChain(certName)[0]; - BasicConstraintsExtension extension = new BasicConstraintsExtension(true); - NUnit.Framework.Assert.IsTrue(extension.ExistsInCertificate(certificate)); - } - - [NUnit.Framework.Test] - public virtual void BasicConstraintMaxLengthNotExpectedTest() { - String certName = certsSrc + "basicConstraintsMaxCert.pem"; - IX509Certificate certificate = (IX509Certificate)PemFileHelper.ReadFirstChain(certName)[0]; - BasicConstraintsExtension extension = new BasicConstraintsExtension(false); - NUnit.Framework.Assert.IsFalse(extension.ExistsInCertificate(certificate)); - } - - [NUnit.Framework.Test] - public virtual void BasicConstraintLength10Test() { - String certName = certsSrc + "basicConstraints10Cert.pem"; - IX509Certificate certificate = (IX509Certificate)PemFileHelper.ReadFirstChain(certName)[0]; - BasicConstraintsExtension extension = new BasicConstraintsExtension(10); - NUnit.Framework.Assert.IsTrue(extension.ExistsInCertificate(certificate)); - } - - [NUnit.Framework.Test] - public virtual void BasicConstraintLength5ExpectedTest() { - String certName = certsSrc + "basicConstraints5Cert.pem"; - IX509Certificate certificate = (IX509Certificate)PemFileHelper.ReadFirstChain(certName)[0]; - BasicConstraintsExtension extension = new BasicConstraintsExtension(2); - NUnit.Framework.Assert.IsTrue(extension.ExistsInCertificate(certificate)); - } - - [NUnit.Framework.Test] - public virtual void BasicConstraintLength5NotExpectedTest() { - String certName = certsSrc + "basicConstraints5Cert.pem"; - IX509Certificate certificate = (IX509Certificate)PemFileHelper.ReadFirstChain(certName)[0]; - BasicConstraintsExtension extension = new BasicConstraintsExtension(10); - NUnit.Framework.Assert.IsFalse(extension.ExistsInCertificate(certificate)); - } - - [NUnit.Framework.Test] - public virtual void BasicConstraintFalseExpectedTest() { - String certName = certsSrc + "basicConstraintsFalseCert.pem"; - IX509Certificate certificate = (IX509Certificate)PemFileHelper.ReadFirstChain(certName)[0]; - BasicConstraintsExtension extension = new BasicConstraintsExtension(false); - NUnit.Framework.Assert.IsTrue(extension.ExistsInCertificate(certificate)); - } - - [NUnit.Framework.Test] - public virtual void BasicConstraintFalseNotExpectedTest() { - String certName = certsSrc + "basicConstraintsFalseCert.pem"; - IX509Certificate certificate = (IX509Certificate)PemFileHelper.ReadFirstChain(certName)[0]; - BasicConstraintsExtension extension = new BasicConstraintsExtension(10); - NUnit.Framework.Assert.IsFalse(extension.ExistsInCertificate(certificate)); - } - } -} diff --git a/itext.tests/itext.sign.tests/itext/signatures/verify/pdfinsecurity/IncrementalSavingAttackTest.cs b/itext.tests/itext.sign.tests/itext/signatures/verify/pdfinsecurity/IncrementalSavingAttackTest.cs index 5d158702e8..87c26a3581 100644 --- a/itext.tests/itext.sign.tests/itext/signatures/verify/pdfinsecurity/IncrementalSavingAttackTest.cs +++ b/itext.tests/itext.sign.tests/itext/signatures/verify/pdfinsecurity/IncrementalSavingAttackTest.cs @@ -39,7 +39,7 @@ public static void Before() { } [NUnit.Framework.Test] - [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)] + [LogMessage(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE)] public virtual void TestISA03() { String filePath = sourceFolder + "isa-3.pdf"; String signatureName = "Signature1"; diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/PKCS7ExternalSignatureContainerTest/cmp_testTroughPdfSignerWithTsaClient.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/PKCS7ExternalSignatureContainerTest/cmp_testTroughPdfSignerWithTsaClient.pdf index 6d9796e2e7..de5070aa7b 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/PKCS7ExternalSignatureContainerTest/cmp_testTroughPdfSignerWithTsaClient.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/PKCS7ExternalSignatureContainerTest/cmp_testTroughPdfSignerWithTsaClient.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/SignatureUtilTest/eolNotIncludedIntoByteRange1.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/SignatureUtilTest/eolNotIncludedIntoByteRange1.pdf new file mode 100644 index 0000000000..93b89a4fc1 Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/SignatureUtilTest/eolNotIncludedIntoByteRange1.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/SignatureUtilTest/eolNotIncludedIntoByteRange2.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/SignatureUtilTest/eolNotIncludedIntoByteRange2.pdf new file mode 100644 index 0000000000..fa22db2c24 Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/SignatureUtilTest/eolNotIncludedIntoByteRange2.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/SignatureUtilTest/eolNotIncludedIntoByteRange3.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/SignatureUtilTest/eolNotIncludedIntoByteRange3.pdf new file mode 100644 index 0000000000..3e2afa6cbe Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/SignatureUtilTest/eolNotIncludedIntoByteRange3.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/ReadSignedMacProtectedDocumentTest/cmp_updateSignedMacProtectedDocumentTest.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/ReadSignedMacProtectedDocumentTest/cmp_updateSignedMacProtectedDocumentTest.pdf new file mode 100644 index 0000000000..7df7decda8 Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/ReadSignedMacProtectedDocumentTest/cmp_updateSignedMacProtectedDocumentTest.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/ReadSignedMacProtectedDocumentTest/signedMacProtectedInvalidDoc.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/ReadSignedMacProtectedDocumentTest/signedMacProtectedInvalidDoc.pdf new file mode 100644 index 0000000000..9b46b247b0 Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/ReadSignedMacProtectedDocumentTest/signedMacProtectedInvalidDoc.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/ReadSignedMacProtectedDocumentTest/thirdPartyMacProtectedAndSignedDocument.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/ReadSignedMacProtectedDocumentTest/thirdPartyMacProtectedAndSignedDocument.pdf new file mode 100644 index 0000000000..e0b03c2b7b Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/ReadSignedMacProtectedDocumentTest/thirdPartyMacProtectedAndSignedDocument.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/certs/SHA256withRSA.cer b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/certs/SHA256withRSA.cer new file mode 100644 index 0000000000..fbaad2b382 Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/certs/SHA256withRSA.cer differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/certs/SHA256withRSA.key b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/certs/SHA256withRSA.key new file mode 100644 index 0000000000..d7e9b5e825 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/certs/SHA256withRSA.key @@ -0,0 +1,51 @@ +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQdOaEUfD0sZWtUR11 +xwgn0gICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEBaNXSfwUjF5SS7n +ce1JFoUEggTQ6eV+IsckiVP7I9VTldLkpP5OKB8brmw5t20fO11HyCnqkkhooR2b +t2fBj4fWv0IRUe266L+fVs7AOngjkWfezEvGR6nte4pNXEFrOwt/U8A6IYZXBdA5 +dvqs6VMPHbjQ8CufVLGvksuYFQVRcGy0rk1DH2Of44GU4X0GtROlFFJnkmfZhVPS +Hx2MXXGQ02Ko1i1eKoEGgvmSAsDcPijiX96DKlQZJ4YMtI/8rRsdvNJsJ2beyZDa +T3aJMmSSBF92mS2dtS21DwjzEu8utquguYA0KYzjZM9onOuBEEUifam8Fjnvlui6 +beQJya4zldoA6QZPSd2PUAP6l1U/d8UXqcisjzArDZDmRu58dPxn4rs0NgTOIO8h +fEUIvfS+wuknff1b/wdGnwXkXoeSrrjS9dhP9KVU1SJ/FWKc6BY+P+JmE5vLjAtn +AmbyZhXY0jX7ZHFh0z0y1y1fTIXL1aj4iB+cUwhJ1ZdlGkT5HdG4ts/oTGCnpB6O +F1GvGyhprmtjp/dspLH5ha0I+4aTn46yFpnBNyg8w9c2+xj8Jiqy9J/ppVtPdhxt +wrE1/ThUGIWUTsbGbLW87WIrZq6IlSGtztbxAMYxXoe4solYueE3pI3eYFzgnBcq +T6Byktr71gt9AGD/N/p+Kk5RM4JT8XpQjLjz9TlmsGpJzUoBGeG6KFLsqqLLSD+0 +c5lAGWsFhec3uCu4fCyBqxpQc0y5j2bgUiTRGYn1NOdyZg+ERO/aWGfkDOAtlL1i +B79NGIBxIXgt508g83UeaQC6KjuG/8hPY6UHmU5mlgRT9H5jvkSX3mEtl1Gdk2y0 +M5pZTTrhbG4p66GhBi8vM5tQfiBoLUKEM/kgiGXPC6Kob42nb3ufP0rmnKklcDGC ++898hW5ge+VNmOkHpVuV5ZD9aWUSVEU4+8QNZj8pcyL0GXFyEL/HxNxUESdz3k0S +bInuxO49mgGPjBqtx5ZvaxyWFnzOp6rmHZUHymejxxdnlnTnSnXKkJFjcm7n0sKO +575ofHtk0OdqIK6YiPgfeF6nZkIg3C0PbReZ05kTplrW182ZWuQQyJgv+RPzF4+9 +5rCe67nJhJrt7hXFRsUScHXNj+HF9Av8WR2RnHTRbpQBJszijM+Xgl+VeYcY5ckB +fk+AfcR9r0Jud4O9795OOWVxWqGVu/b1RGonfjMkGW+JdnZL0vkOYYcHt4iMZmzW +M0ZowZPGO5dFBV7/ZkVzb0fexw+f+E0lUBEK1cx0gxnzjmcGJO+C9if1uIEfwpon +3wBOTDsU7XKDx9v6ibcDMOXrZa+rcJWxgNkXt5nRpozZkddYctBkehGu+snV2g4n +SdOwr0eIVv/L+v4IywZmeWWEVnbSAvB0p7nB89bgLMr9tV0ly7MWxPH+gPnNJ1gE +7Mp3AgN5BxEmLfW3+ou3QLoqnOS2MCw/xcgLP0nJACSPI7/nWy95iKXKgkCkAgF9 +4Ztk7uBG4tiK14KcKq8ToCW2YNliT3g0CWjBLtVPUS6qboudMiuedxTxE8WEirpT +A77nfDNg4MVjl4kP9jhV0Phpn9rDMJ2jw0BqFc1Vou4aNDXYandAFJea44Wce9H+ +qAowcrfsWehD01HBQ2KwWVg3sLnwwBHw0nvbATS41hdxsP2OmCnxWkc= +-----END ENCRYPTED PRIVATE KEY----- +-----BEGIN CERTIFICATE----- +MIIDfzCCAmegAwIBAgIEUFic9zANBgkqhkiG9w0BAQsFADBvMQswCQYDVQQGEwJU +UzETMBEGA1UECBMKVGVzdCBTdGF0ZTESMBAGA1UEBxMJVGVzdCBUb3duMREwDwYD +VQQKEwhUZXN0IG9yZzEQMA4GA1UECxMHVGVzdCBPVTESMBAGA1UEAxMJVGVzdCBV +c2VyMCAXDTE0MDkyMjA5MTExMVoYDzIxMTQwODI5MDkxMTExWjBvMQswCQYDVQQG +EwJUUzETMBEGA1UECBMKVGVzdCBTdGF0ZTESMBAGA1UEBxMJVGVzdCBUb3duMREw +DwYDVQQKEwhUZXN0IG9yZzEQMA4GA1UECxMHVGVzdCBPVTESMBAGA1UEAxMJVGVz +dCBVc2VyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA+6g5sYzXiNOA +hR7C8wc8buxU/JgcbdHpHIR44iuXjpepBYAE7hRsWM7H4cuXrKiRxS9UMOadqkGF +Qqb5sG6lo2UUhcj4qlN6hKDc/+AMZMIW1mvQldiygCAkqgM8iso+kw56dpVuerG/ +k1nd8f+X9rjXN6/DIMznZcMy2d9ByIFuixFKElPvOWx9q9N4aiueOd5FM5eHxp+3 +F4uCTrpM5zkS7Rmf5GVtCofc8KgaTLLp4D0Ge5VUJm7yW8fuU3eIpin4ivjk+Gye +Q3t0BsrmNyQy3CmKGOBP/vX0+wEMvGN2xqNgAFP9dxA+AbJMiAfsmoWvxXaPktqC +DOspTCFqbwIDAQABoyEwHzAdBgNVHQ4EFgQUILviRCmSrhuLDmF0nus4pv2uu7gw +DQYJKoZIhvcNAQELBQADggEBAGnfGYL7nDm5taDPRxuGGMqUPwRnH2bXwef6S2Xb +/nIEFtNheVFQFtKNn5Ikq68DTFMP06yXLnI7F40+ZiQezRBB1EPPmDL2fYKc9fL1 +SHntu6HLgP/Y5nnCVegtL8l9745gQZnnXlMtkTs2HFwffznIHW/3STO0Bcj0+KMa +p8vebMjmvV7bZEGvrcrVXL55QPZXJwRuQMXJB3f5XhAEH1VqAhTW6DrvBUnuESwo +9fxxA5gmblt80SQYdKr2I08OTk0qmyF8zNuffTOiSS8/V6Cf7CntuPWjSuVf1EVP +MH6KkSjceLZ99Y7bvl7KKvQ4Kj5Bp27PwlRvtYbfCUmQEG8= +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/certs/signCertRsa01.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/certs/signCertRsa01.pem new file mode 100644 index 0000000000..5f2f1f25a8 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/certs/signCertRsa01.pem @@ -0,0 +1,76 @@ +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQgLsVp4wmljjCRgEy +kw2LWgICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEELyxbQ1T8vAMXX6t +md0GgdwEggTQXjePuN2mrJ4C7uFP/ErLys5cwO7QSOL5z7jUUep96YkZgMjau99o +6JolOHyJRzDbUNbTCfku8PqwDfdPrCPfMZ+e9UU/Y5uVZbEL+UtIkcH/uyFCd1k7 +AVOhAux7KZwgHlq66iUHqTQFd58Ly7KOoMKGZS07CtIxjYluFZZbx44EZrgqRwEa +ZAbIsdR2xZ092Who4CzkuF31m2TuyzfYir7kocJsdQU6k9OdptfJRda2UpZiUXW8 +GMg/qvF7RwkAbfu7gLkcmc5FETlY+E3P8tYDutN737wnd/VqO9Bd25umOAl3CHUA +5+YSXvWOSuAJjz7kEI2DEG/ov//oO0wohJPLKRF7jUI2WbIwCAypPZPvSS506ulO +ofuLTY0+Jii0ZO5SyC4Uu90lh8RISvi9RzRx2G4sN+gyeCBBg1R1f5IRNeBImpEw +aKqk4VrcUrLe623Z3el1Z8ErJBJ6G0ZV/EAFC7dmpTknrVOFzdO6sohtnHygm0Ce +h5QdqiWvb0QKHv3GZumdtCcdh8vPMRT1PEWVvfV/cyIOc5BH6sYNtxiohosl6DLz +I84vj3n8I+cFHrYIFCtghy9iZJ0GvvPxaiJCS5A+eDiOO3rhk3ZMkmTlVCpOBiY2 +QKdljhmRaN1Y6XfQ8SRNmr/qVfwFJ4JgYnk3VVHVvzt0EvEImNusOvTH2U4zMryP +FRhgGNIL0f5gflo2LxSPqsnqNfJLRHCmXkYeB4Pu8/xv6biFqtwC2UBaL7FCjIgY +NI+hi9Mt9fJpYqF4XGHcT2b6Aq7otgxX+5iiQg10bEjqI/gcZrFvBvmz/97OBe7X +BFa5F8nYeSxnr5XQiJ04oBVBjdvAFeS7ZZ4Quq2beEgcgCj7EU/OXLLHwBCCmD8s +8kgkhsv7+sPtNnC1YeoW6xHezt/FSDYxS1lPWsnr4AE4jpxOJgM8CNSDq0E52e83 +2uDNm3gIo133RRn9V8gNQzfIJv1BZFRUtOn9CRxrJBTptSxUJX1at+btTM7hlY2z +MwXM5i7ZGDVQOPSpKrlbmA8bHDRHeGryXz0HNWs5RWiTVSEhCuVTrrlQG4nmbhVm +b6xbd/DWs3NdEXwLLdg1W+fbeS2qIJtJqu0LU+PcGkhaVXeobc6MFGw06hDVtVg9 +Hm1/AZJ4OuD/+GyH9ku4Z9tPDh4NmXsVVV8CpzxRJ37gLrGPwbxXwW3v6B6NBRvz +W8KuWQjlNDxVcFb9Si7Mj81xX2k1818hwSm3iEQIwT0Q7BNUj3oJhTsNlB/Id79J +tl7AKam1ofDZVmU7gPcv0FPKxhEZIyjoqeAzLGuW1Hmp45HbJ94tL2uvbgPq2Mj7 +j4jllaPoN9J1QBVDHBqEzLZGeWKZYK2L9Sw4SdkZjLp96hxoQ7MYvTrsX4eSV0HH +xMLp5hhIiM8zGIsMYlwcfOSpQh/H1AnbiQIJ0/tzO6uBZ73fq59rTReRf+PtXqqT +5vg89nN6kNvJcrwNLyEhdC7uaqsoimTMi59BE36ZZcL0jHKMmPl9g/vbPj9CiRdu +B0+4lQD0hAqK6FVfl6ENpj4zLdU6/EER5L7v+Syv8d5AeFtdKrqxH3oCGPXmXCol +j2rALoIlZt0D+jjmcDo6C32qtu8w40zBD/+J8iZXVWC/U9cauP00N9E= +-----END ENCRYPTED PRIVATE KEY----- +-----BEGIN CERTIFICATE----- +MIID6TCCAtGgAwIBAgIEWOew7DANBgkqhkiG9w0BAQsFADBUMQswCQYDVQQGEwJC +WTEOMAwGA1UEBwwFTWluc2sxDjAMBgNVBAoMBWlUZXh0MQ0wCwYDVQQLDAR0ZXN0 +MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTE3MDQwNzE1MzM0MFoYDzIxMTcw +NDA3MTUzMzQwWjBZMQswCQYDVQQGEwJCWTEOMAwGA1UEBwwFTWluc2sxDjAMBgNV +BAoMBWlUZXh0MQ0wCwYDVQQLDAR0ZXN0MRswGQYDVQQDDBJpVGV4dFRlc3RSc2FD +ZXJ0MDEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCfr2PnZ6DjvrSY +g0cWtDR6drgvCowB5hQH7CHSAMTeVGZxUOBT1ylfxySioRU4ckq3uQu7jOe7Te6Y +xEenjFhTv8bT0/ZrL2w6OGBH4iUs3Kwx5jzbRHPuZt7+gCKLBXhRH6ytDnbTHNgT +4tjGXUmGa4sMbal1mXvKN/xaK+hGDskRW6cHZq7ZtdgfM8yBQWZzshAz7dQepmUH +ZYWxplTwJ8cuVLqjgXMXWfTatio6yYwf+5AkWszBcCA6oxm16wN2pLUeNx5aBLiF +Dhtj6qqHLwN/7tPb0ojqXRU3AfocC2y8a4WeVOOp2du0ja4E9P7IQNKiBBlOfNcF +D700qPFpAgMBAAGjgbswgbgwCQYDVR0TBAIwADB/BgNVHSMEeDB2gBRdKnF1rt3Y +vlm6ILFmkcl2NlNc7qFYpFYwVDELMAkGA1UEBhMCQlkxDjAMBgNVBAcMBU1pbnNr +MQ4wDAYDVQQKDAVpVGV4dDENMAsGA1UECwwEdGVzdDEWMBQGA1UEAwwNaVRleHRU +ZXN0Um9vdIIEWOeR1jAdBgNVHQ4EFgQUz41Jo8H/HAqxhMN/inuhKuLZU8gwCwYD +VR0PBAQDAgXgMA0GCSqGSIb3DQEBCwUAA4IBAQCT597xhkVzrYP7NudRgIZCDwT3 +TDnL+Xv8H4c9p+CdHJtFMoxAQlzcQi4uEIo5nfBKMEXK0d1OnO8zEBfK98EPahUI +++PDnNk82kh64CbZQ95Ms1Usq1XGd31bkXWWRM3LY2P7VG0nR+eLutVAClIcbTLN +yL9ZhiL33jCk1W5PeXJy13kL3XV/Awt8zb9fcinkuXkV5LoZHxh2Ob19R//5fGxH +hnUywReGptnIbEPiWGYyX1QCQeOqi3vmqZaGr+RZfF8+zqtSP5p4gFpryuTJxkcZ +UOeroaBv3sHCI9rtzcwZPYsW0BroFliEhNIDq5HxJgdwdu6uDOMMrC2QxB17 +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIID6jCCAtKgAwIBAgIEWOeR1jANBgkqhkiG9w0BAQsFADBUMQswCQYDVQQGEwJC +WTEOMAwGA1UEBwwFTWluc2sxDjAMBgNVBAoMBWlUZXh0MQ0wCwYDVQQLDAR0ZXN0 +MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTE3MDQwNzEzMjAwMVoYDzIxMTcw +NDA3MTMyMDAxWjBUMQswCQYDVQQGEwJCWTEOMAwGA1UEBwwFTWluc2sxDjAMBgNV +BAoMBWlUZXh0MQ0wCwYDVQQLDAR0ZXN0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290 +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz/fz7iq1wzhMMYcGfmMm +teCY/ZtdE26PB1OTTBuDSN86sVNmur5FV/mLPU9ZK2ofrs+wMrqn0agmFlRl4dTh +f5u5WSEQ/ARwXzYOn2uEkwR/0dwwZUL3VWhrPSD5SxX5MzFo8UXTNlXW2bClLC0F +QU2qLjIwwRFwwWDSQPR8r/Mv181RljVpEjPk6DfkDtHWWA4daGlQU0nXbuZszplv +iPafXmyKn+2w4G9Jw/8pHIK2VhWYstLI+bUZk662ZVldNvnpMyHn12FfB0Nbf/Z6 +V2WTGviEr8EEE2cA7I+H7ZGUDzug7umNCCJn3ilC6vAt9i9OLaZRDh6jPMOjMUiz +TwIDAQABo4HBMIG+MA8GA1UdEwEB/wQFMAMBAf8wfwYDVR0jBHgwdoAUXSpxda7d +2L5ZuiCxZpHJdjZTXO6hWKRWMFQxCzAJBgNVBAYTAkJZMQ4wDAYDVQQHDAVNaW5z +azEOMAwGA1UECgwFaVRleHQxDTALBgNVBAsMBHRlc3QxFjAUBgNVBAMMDWlUZXh0 +VGVzdFJvb3SCBFjnkdYwHQYDVR0OBBYEFF0qcXWu3di+WbogsWaRyXY2U1zuMAsG +A1UdDwQEAwIB9jANBgkqhkiG9w0BAQsFAAOCAQEAdhby6EaopoUF8j7oR44Mhe/N +3y9hzGb/zLmmgTavPd2plv6NlAPt9W+8rezKO6jQCsBRFw8JY+Lx6j3W0K6rWigB +pPGU/B/0bXLlOIv2a4uW8nBmq6jxAe5Xbtwm8HcKOOLMzxPIChHJIJy5NWw9ArD4 +Ul+FEt/VuEW1NfPZm1U5ixMOrBfn0C8pxIX4+VSHN9I8WoFjSfYX4Y3ldRLTeqxQ +rhZQlbhGNymp3Kcvtuq5At6vopskyB8Q1b7L4e+hRWK2prz/7p4Bdhu2TmkEfWZc +YKpgrkVFqa/Z1uZ0q4KVBOP3cyaQmqRXTV37SfpNyHAJdol5ueF68VVVNZFRXw== +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/certs/tsaCert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/certs/tsaCert.pem new file mode 100644 index 0000000000..173990cb2f --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/certs/tsaCert.pem @@ -0,0 +1,56 @@ +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQC6J4wXR/ZAEc5RnK +8VKKvAICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEAQIEEIH5lyIZUGdzvVqX +cvANBXUEggTQ4IqSPz58RZzYvimG3BoBJ9353e5H7UQlNi2OurPPLykLLHEY/gGd +c2n2hUZTXxPvmYXQkVoGhsUg59SQRjlhkeGyrrlkkjpmzYAjOMNF9YAwdoXVdA2H +lzOd4yYG+fUCfYma5pMXaqLBOUmB5l+nfBCvYM3hy6U5mnP2ZybR1GpYxkWJAGbG +b+0dz96EUjRPTuPhH8VBW1W0F0asBCTkEDOKAIfrxt6cD3kcnko1WK7wteU4Ln5c +wxnrtJTmSaFeHzSQXUTMfpwGe8ImMtUV0z/DS5x0pHmK/V+3MZN+RfdUXwF7LXwL +8J3CrGoIzGWzmHgGqRXuK9Z+Tdumm1MvRJnmBZp6CWM7j7f8iWKXzFJItDLLuaaJ +H4ZEUt5K7fb8JSPCiVovNmnnBaG7ua3n/5aGvym22TOBgelS0e+bee4YELGolU2g +yRNb24+casHZ/kyenHR4dyrxDTZHmPU9bPhzb05l3Vk+PiHJLxAqFtUiP4buSeoh +TPVYQXAE8EPInwyZxzYvWeSN1JSU3hdOpj+hVnZHoUxGYzZbatVzuJ+MQ3BW3z4g +PfoR3QfTjNNvB+zRp/rveBhbEf7tbvQrFSeQb0Dlta08+LDec6kKA10fzFMtlJcp +IrrH0Zafke95r1bNbqGZrMWSUdBKB2IS2PY/Q8ITGnB/RxIfE7odDVgFnrxrrhf8 +GRErkP1w9xz/+cBw6OeobGPK9ED/jAnOUpAXo22Jl/BsBt7SLTr4h+O3pV3ft79z +J9cOcWAHQy5BknIdahA88bMBnrA/NfHgWhKv1AaD4ICwydMWfxpqelzOiNF+LDq9 +D2fTR9SLiOkHpWgk7NJZAqkZRKrs1MHf9yuq0NDEIojqcQN+rK8O8DiT64XZuSqH +P84jatubXoXbulfRxC+6RkMpuJRjr/N9DNWNj6A61uquPLs9XgVlZNp4ND3tTDaa +tiM45qjxJWjcnI4zm4BtVYTrrU0z7kL2F/rBJEENCYAK5pWgAYA2t44on+k6sLYN +8Fp+J8t22H4v/ssfXUUk3oi7cP66chSNDyPNgWw1GnYqDVogI0bX6+Cx8t7/G9t7 +bWJZxhrgXC1yQeC4FrBfYE8j2m7qRMeINeU/jqdiwbCHlhoMmbMLDKFK9LW4A5mK +VMiLbF1zPnxY4ZxR5MxMJSnODf0RQWgsPX3Vno1pQfJ+1Jjy2m1gKUxqbIevux8Q +QMcRqrx5Mm1d0aztEoygShnkCjhf0yvkFZGyj1J0abgbstPaaOCR/BPMyyhh9znn +5FOViSg204d8j3oJdp/xuxJFJE8+vyB5baA0vudQIQ7+23tA9Fw3dE9Pszm4w8so +jhz1wv/8BoxLQ/4PZcKbQ+MSCzGnse6vlHaV3hXO1SEdN69LCIf65AYYvrdFmv48 +gU5bbYcJRYVdni3tZB7Lht1tmAjgZi+0dn6ApyLAeaaGiov1i622bhSe2REpUCRz +NbdSUl+3lAzNiLxPpR8cTscwf+ow4OEfChNAOzyaUvRdNTolcEhVwox0CUj0ELFE +XS9mK+XZEWJ+fiOGiKoUKDY2sdKRl4stucyah61RQUf/cPL4EmSFhB7i8lD6nyb5 +3cFrNW7nvH+Eu5QzywqGOxTqKJpWXfLTRmNgY+Y6UugnWIfKLcdNMy4= +-----END ENCRYPTED PRIVATE KEY----- +-----BEGIN CERTIFICATE----- +MIIEUjCCAzqgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwQDELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MSEwHwYDVQQDDBhpVGV4dFRlc3RUU0FJbnRlcm1lZGlh +dGUwIBcNMjAwMTAxMDAwMDAwWhgPMjQwMDAxMDEwMDAwMDBaMDgxCzAJBgNVBAYT +AkJFMQ4wDAYDVQQKDAVpVGV4dDEZMBcGA1UEAwwQaVRleHRUZXN0VFNBTGVhZjCC +ASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJ/HVl5COupS9fnTfblPgwSv +nsc7uqqqxKmQ4cqxhl2Xf9rOzFePOZVFlR+A7SW2Ax10x0in10WURwLErpZ47FGq +ytLdIfDIDUb4oBdx2BeToanRQHWEOOLZlb6Z9bEeWLVSWaDRNVSQm+xtBOKB6I6P +5ux7Q4X1115wwFGC0UYumTI5eIjMchWDI6rWcDdi5noA8/qEeQD4894yis5LEy2/ +s0M1OmBnilXxx8urQ0fYXiwf39Uh2yZsgu01urSmnOfVXS3d9+Y9jiJ4CB9w63sa +nbLv7NEB39wjJPrnlyG0bcdCn0mKamJSqdU4RG5nmB1BAH0Wn63IsWQJkjPGrssC +AwEAAaOCAVowggFWMB0GA1UdDgQWBBQVf4Hj+sEkGTEpxe8XFNtQFyGrJDAfBgNV +HSMEGDAWgBS2Vx2D2SIYPmYxGkT9a/4t6i0IaTAOBgNVHQ8BAf8EBAMCBeAwFgYD +VR0lAQH/BAwwCgYIKwYBBQUHAwgwgZ8GCCsGAQUFBwEBBIGSMIGPMD8GCCsGAQUF +BzABhjNodHRwOi8vdGVzdC5leGFtcGxlLmNvbS9leGFtcGxlLWNhL29jc3AvdHNh +LWNhLW9jc3AwTAYIKwYBBQUHMAKGQGh0dHA6Ly90ZXN0LmV4YW1wbGUuY29tL2V4 +YW1wbGUtY2EvY2VydHMvdHNhX2ludGVybWVkaWF0ZS9jYS5jcnQwSgYDVR0fBEMw +QTA/oD2gO4Y5aHR0cDovL3Rlc3QuZXhhbXBsZS5jb20vZXhhbXBsZS1jYS9jcmxz +L2NhLWNybC9sYXRlc3QuY3JsMA0GCSqGSIb3DQEBCwUAA4IBAQAPc81dvV0zZi9P +A4Tpr4nj28DAAPDkjBPiqmeP8FWomG3bF/pTi+vvpO79tR+sKh+38Pn6YwuGsK4d +UVyZ98gTQoTe/x2zviEer0+cdWNVgdTq1MTpiHQNTBN01kggjGdQzZXJNKg9L+Kb +Sw+t9QxzKjRFCUrr4txPxv4O6Yvc3cesM2Dxx0EPsgTqxIbSEliHtXU+K0WBXokw +mzCUXN+ry3iomQkqTIyohySA2dumbaxlxdcQ96pnU8swFwJ5jYEHITbepqDFq6NM +M8ewAFnrtnqqA6GU0thyZSUh4YXphBEkzAKhm2NIye2BXGirzB7DGfhev8kLD+6a +9qBtibHs +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacProtectedDocInAppendModeTest_signDetached.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacProtectedDocInAppendModeTest_signDetached.pdf new file mode 100644 index 0000000000..aa00ed849e Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacProtectedDocInAppendModeTest_signDetached.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacProtectedDocInAppendModeTest_signExternalContainerReal.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacProtectedDocInAppendModeTest_signExternalContainerReal.pdf new file mode 100644 index 0000000000..b3ac6a3dec Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacProtectedDocInAppendModeTest_signExternalContainerReal.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacProtectedDocInAppendModeTest_timestamping.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacProtectedDocInAppendModeTest_timestamping.pdf new file mode 100644 index 0000000000..4b22caf4ab Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacProtectedDocInAppendModeTest_timestamping.pdf differ diff --git a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/xobject/GetImageBytesTest/separationCSWithDeviceRgbAsAlternative.tif.png b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacProtectedDocTest_signDetached.pdf similarity index 50% rename from itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/xobject/GetImageBytesTest/separationCSWithDeviceRgbAsAlternative.tif.png rename to itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacProtectedDocTest_signDetached.pdf index 9fac666868..e4563ea8d0 100644 Binary files a/itext.tests/itext.kernel.tests/resources/itext/kernel/pdf/xobject/GetImageBytesTest/separationCSWithDeviceRgbAsAlternative.tif.png and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacProtectedDocTest_signDetached.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacProtectedDocTest_signExternalContainerReal.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacProtectedDocTest_signExternalContainerReal.pdf new file mode 100644 index 0000000000..63b2e42a1c Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacProtectedDocTest_signExternalContainerReal.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacProtectedDocTest_timestamping.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacProtectedDocTest_timestamping.pdf new file mode 100644 index 0000000000..fb6c479746 Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacProtectedDocTest_timestamping.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacProtectedDocWithSHA3_384Test_signDetached.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacProtectedDocWithSHA3_384Test_signDetached.pdf new file mode 100644 index 0000000000..f03b74c3e0 Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacProtectedDocWithSHA3_384Test_signDetached.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacProtectedDocWithSHA3_384Test_signExternalContainerReal.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacProtectedDocWithSHA3_384Test_signExternalContainerReal.pdf new file mode 100644 index 0000000000..d7270a7dd4 Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacProtectedDocWithSHA3_384Test_signExternalContainerReal.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacProtectedDocWithSHA3_384Test_timestamping.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacProtectedDocWithSHA3_384Test_timestamping.pdf new file mode 100644 index 0000000000..724f21d1ee Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacProtectedDocWithSHA3_384Test_timestamping.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacPublicEncryptionDocTest_signDetached.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacPublicEncryptionDocTest_signDetached.pdf new file mode 100644 index 0000000000..9a0546801d Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacPublicEncryptionDocTest_signDetached.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacPublicEncryptionDocTest_signExternalContainerReal.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacPublicEncryptionDocTest_signExternalContainerReal.pdf new file mode 100644 index 0000000000..7b140c8a5c Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacPublicEncryptionDocTest_signExternalContainerReal.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacPublicEncryptionDocTest_timestamping.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacPublicEncryptionDocTest_timestamping.pdf new file mode 100644 index 0000000000..90cb153ca2 Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signMacPublicEncryptionDocTest_timestamping.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDoc17Test_signDetached.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDoc17Test_signDetached.pdf new file mode 100644 index 0000000000..1435110eed Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDoc17Test_signDetached.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDoc17Test_signExternalContainerBlank.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDoc17Test_signExternalContainerBlank.pdf new file mode 100644 index 0000000000..79830a83ba Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDoc17Test_signExternalContainerBlank.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDoc17Test_signExternalContainerReal.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDoc17Test_signExternalContainerReal.pdf new file mode 100644 index 0000000000..6532a6e0a7 Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDoc17Test_signExternalContainerReal.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDoc17Test_timestamping.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDoc17Test_timestamping.pdf new file mode 100644 index 0000000000..914c0ef98e Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDoc17Test_timestamping.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDocInAppendModeTest_signDetached.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDocInAppendModeTest_signDetached.pdf new file mode 100644 index 0000000000..2b1bc1e5d2 Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDocInAppendModeTest_signDetached.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDocInAppendModeTest_signExternalContainerBlank.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDocInAppendModeTest_signExternalContainerBlank.pdf new file mode 100644 index 0000000000..abb3c4610d Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDocInAppendModeTest_signExternalContainerBlank.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDocInAppendModeTest_signExternalContainerReal.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDocInAppendModeTest_signExternalContainerReal.pdf new file mode 100644 index 0000000000..96d972f054 Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDocInAppendModeTest_signExternalContainerReal.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDocInAppendModeTest_timestamping.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDocInAppendModeTest_timestamping.pdf new file mode 100644 index 0000000000..490e40aa6a Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDocInAppendModeTest_timestamping.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDocTest_signDetached.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDocTest_signDetached.pdf new file mode 100644 index 0000000000..1ecb485b3d Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDocTest_signDetached.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDocTest_signExternalContainerReal.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDocTest_signExternalContainerReal.pdf new file mode 100644 index 0000000000..baafa3d807 Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDocTest_signExternalContainerReal.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDocTest_timestamping.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDocTest_timestamping.pdf new file mode 100644 index 0000000000..d206fd70ba Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/cmp_signNotMacProtectedDocTest_timestamping.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/macEncryptedDoc.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/macEncryptedDoc.pdf new file mode 100644 index 0000000000..f8bffedbdc Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/macEncryptedDoc.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/macEncryptedDocSHA3_384.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/macEncryptedDocSHA3_384.pdf new file mode 100644 index 0000000000..e4dfce5bbe Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/macEncryptedDocSHA3_384.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/macEncryptedWithPublicHandlerDoc.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/macEncryptedWithPublicHandlerDoc.pdf new file mode 100644 index 0000000000..e62dcb8d79 Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/macEncryptedWithPublicHandlerDoc.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/noMacProtectionDocument.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/noMacProtectionDocument.pdf new file mode 100644 index 0000000000..318f529543 Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/noMacProtectionDocument.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/noMacProtectionDocument_1_7.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/noMacProtectionDocument_1_7.pdf new file mode 100644 index 0000000000..db862c7069 Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/mac/SignedDocumentWithMacTest/noMacProtectionDocument_1_7.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/LtvSigTest/cmp_ltvEnabledSingleSignatureNoCrlDataTest.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/LtvSigTest/cmp_ltvEnabledSingleSignatureNoCrlDataTest.pdf index e2650fb2b0..dc95140722 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/LtvSigTest/cmp_ltvEnabledSingleSignatureNoCrlDataTest.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/LtvSigTest/cmp_ltvEnabledSingleSignatureNoCrlDataTest.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/LtvSigTest/cmp_ltvEnabledSingleSignatureNoOcspDataTest.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/LtvSigTest/cmp_ltvEnabledSingleSignatureNoOcspDataTest.pdf index 7836c124cd..14b4a18fd3 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/LtvSigTest/cmp_ltvEnabledSingleSignatureNoOcspDataTest.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/LtvSigTest/cmp_ltvEnabledSingleSignatureNoOcspDataTest.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/LtvSigTest/cmp_ltvEnabledTsTest01.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/LtvSigTest/cmp_ltvEnabledTsTest01.pdf index 17b5987106..6630ab9ca2 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/LtvSigTest/cmp_ltvEnabledTsTest01.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/LtvSigTest/cmp_ltvEnabledTsTest01.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/LtvSigTest/cmp_secondLtvOriginalHasNoVriTs01.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/LtvSigTest/cmp_secondLtvOriginalHasNoVriTs01.pdf index f50412d43e..28360ecdf1 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/LtvSigTest/cmp_secondLtvOriginalHasNoVriTs01.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/LtvSigTest/cmp_secondLtvOriginalHasNoVriTs01.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesSignatureLevelTest/cmp_padesSignatureLevelLTATest01.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesSignatureLevelTest/cmp_padesSignatureLevelLTATest01.pdf index 3f5a6ff34f..a6ea940f5c 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesSignatureLevelTest/cmp_padesSignatureLevelLTATest01.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesSignatureLevelTest/cmp_padesSignatureLevelLTATest01.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesSignatureLevelTest/cmp_padesSignatureLevelTTest01.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesSignatureLevelTest/cmp_padesSignatureLevelTTest01.pdf index 6e80b40664..0d78251689 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesSignatureLevelTest/cmp_padesSignatureLevelTTest01.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesSignatureLevelTest/cmp_padesSignatureLevelTTest01.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTATest1.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTATest1.pdf index 29ad2c6c86..a6be95ad51 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTATest1.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTATest1.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTATest2.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTATest2.pdf index 2209b43918..16f2783c73 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTATest2.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTATest2.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTATest3.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTATest3.pdf index 0ae6f10f9d..cee812a555 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTATest3.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTATest3.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTATest3_FIPS.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTATest3_FIPS.pdf new file mode 100644 index 0000000000..4232f9ec75 Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTATest3_FIPS.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTATest4.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTATest4.pdf index af616ece42..37cfc5a967 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTATest4.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTATest4.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTTest1.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTTest1.pdf index c818f5b0c4..78953a84ac 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTTest1.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTTest1.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTTest2.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTTest2.pdf index 601da3cd62..679ecc2d6a 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTTest2.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTTest2.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTTest3.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTTest3.pdf index a76a4f2218..e65747898b 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTTest3.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTTest3.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTTest3_FIPS.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTTest3_FIPS.pdf new file mode 100644 index 0000000000..3840acbadf Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTTest3_FIPS.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTTest4.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTTest4.pdf index 053f8cc08b..123c4b6954 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTTest4.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineLTTest4.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineTTest1.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineTTest1.pdf index fa1237c62d..dc762876e3 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineTTest1.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineTTest1.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineTTest2.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineTTest2.pdf index ebff5e665c..66bf74c45a 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineTTest2.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineTTest2.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineTTest3.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineTTest3.pdf index d3a36ccf58..36d546299c 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineTTest3.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineTTest3.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineTTest4.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineTTest4.pdf index e2798b8a79..f61d2f8b7e 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineTTest4.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PadesTwoPhaseSigningLevelsTest/cmp_twoStepSigningBaselineTTest4.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/Pdf20SigningTest/cmp_signPdf2CadesWithRipemd.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/Pdf20SigningTest/cmp_signPdf2CadesWithRipemd.pdf deleted file mode 100644 index 1f58edfa82..0000000000 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/Pdf20SigningTest/cmp_signPdf2CadesWithRipemd.pdf and /dev/null differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/Pdf20SigningTest/signPdf2CadesWithRipemd.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/Pdf20SigningTest/signPdf2CadesWithRipemd.pdf deleted file mode 100644 index 7b6d1701fb..0000000000 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/Pdf20SigningTest/signPdf2CadesWithRipemd.pdf and /dev/null differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelLTATest1.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelLTATest1.pdf index f9cd7d3820..d592f1feb0 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelLTATest1.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelLTATest1.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelLTATest2.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelLTATest2.pdf index 5666c4f044..ef482ecaad 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelLTATest2.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelLTATest2.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelLTATest3.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelLTATest3.pdf index 94bfab222e..c588ad9570 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelLTATest3.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelLTATest3.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelLTTest1.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelLTTest1.pdf index d16c5a4d8b..028004b72b 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelLTTest1.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelLTTest1.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelLTTest2.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelLTTest2.pdf index 3853a96412..1d7fc57037 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelLTTest2.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelLTTest2.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelLTTest3.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelLTTest3.pdf index 43b8f84047..39d0785c23 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelLTTest3.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelLTTest3.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelTTest1.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelTTest1.pdf index ac91394d28..cc5129dd24 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelTTest1.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelTTest1.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelTTest2.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelTTest2.pdf index b5754acf68..a71385963c 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelTTest2.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelTTest2.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelTTest3.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelTTest3.pdf index babc0976e9..db208ff194 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelTTest3.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_padesSignatureLevelTTest3.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_prolongDocumentSignaturesTest1.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_prolongDocumentSignaturesTest1.pdf index 9dfa8fe6de..0c6a8bfe90 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_prolongDocumentSignaturesTest1.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_prolongDocumentSignaturesTest1.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_prolongDocumentSignaturesTest2.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_prolongDocumentSignaturesTest2.pdf index 2ce18344be..72b71aa06d 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_prolongDocumentSignaturesTest2.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerLevelsTest/cmp_prolongDocumentSignaturesTest2.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerTest/cmp_defaultSignerPropertiesTest.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerTest/cmp_defaultSignerPropertiesTest.pdf index 190d46284d..0226439e8d 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerTest/cmp_defaultSignerPropertiesTest.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfPadesSignerTest/cmp_defaultSignerPropertiesTest.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/test.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/test.pem deleted file mode 100644 index a9307d180a..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/test.pem +++ /dev/null @@ -1,51 +0,0 @@ ------BEGIN ENCRYPTED PRIVATE KEY----- -MIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQYh8g3qiMhxsnV5xf -S4sK7AICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEMTVVdwTGHC+ynMw -BzHDt/kEggTQnubx8WeyfN5T2csCAqoBKCa0OkT3be7W9zJl3y3L7zZYKxxEG4L2 -vFCbGog85tvrwnziaqRYOmmYJbp86rTuY/M4+7gYKiMwibvrE6JIqE3YwBvFoH49 -q+MobF/QLIyKg5TiUrunqbmF/xZGOfCuSimnIGHFxpzDjAJAP/rhSfNYIqmKd7gW -6egJSsmgZ1LhTYhylKHlcDt52bS+tTmeuQpWslJ6hmojqnZToT8ihSEBgYJG3qis -06XnsZHt324vJRa2LCksm0mJD3rkpZlzfvveRr0MiU2U25KL8s1VQKfDoWWG3HGj -mNOUc0ggCQXsgVmfCsIq8QX46n/j/xHMs0gUu3NLfOlii8tt7BQKsmDtaufIo4+k -+Q42b/KPeAbMWOYJc6WozCwkaKjWCHi0GeiFfbnJLt2KMjMDw2qxArgXcjAvlyKk -1r8OD3je9/2NdknSVD5qv+WAhARJGk/aqx+TDMtMmr/5tevc/VzVuI8e5SeREI6m -H4yAd45EDw+OpPz9Tff1xPH5ZBnDAPYIodm4xXW42uIdPsmJbQYh1aX5ijLjmLSW -zjMqvN+ysDUMc0lBOn0HR8h8P+uObWigPk3J9n+7ABh4uAMEdjbXhSPbbjV2Gwri -irwJgGQt4F7a6vi8ypUf7leLLYn/Y0nFn438/eDjMmnj5nCZIlwM9f48NwTNRn5X -J7R+U98xsQHvu/23HLSVfXk5pRNi5++WEVDocb/vyEXmn7SdHAeL9QxzhxoM6xgs -5LGNyT5dsoxM7YoAUcRC7W4fDq4WFit3qxRTNXsqSVHOfZWZbkUuGSvBxQHFTL1Z -amItasoXZbOeA89LD2LXd9FrxXdDf702OOJonutl+OtszyNHHv/BXcktDEJmsVUz -qhmLrip6eB/boxSCJhWnMIcMb97/pkFex5YEMBxntx5mnO8ICD64vbIosYSHBdBv -9NQ8qczCqYJXVJD1AB/IhQDK+HC4EyMV9/h3dfzN2flZZHW64cHFG4YjFz2k00sF -mdGhbTXJAuC5vxRUWqf4/dlAc4uSmUeoxZqHfiiJ+hGXrbpLxx41/ZvBl6sgOHZ2 -Zb+yv/qZeu507eAQFNq+BYSu+B9shhxRB1VkMz9ZxdKiU1ywU0TFxPsxq62FtoF7 -REwVLUBUzQMS1t+gq+P9yGSSx8eZMvQgviTIX2iBWgVbgq4LKx5UgfVeFIxHqp6F -Ba1eYzEXSqGKZYWWtM4rjDhgOjZsM6wNQ8bsRSSkjYcg9JvIpZ13oT1HiCecohR4 -N2GNo5bLxDxTlfyZNTKr2SVPkARvmjBhxfVbnbNlRRmOe3uEh9PFDPl/mWa+Ql11 -YODqdYG4xVzYpqHpr1P49/Peib6Pr5LkHOp8R8tjD8L2ARFe9lZlS31c2Jqt0qgb -TC1IzV8DTxIxL1Lvpsklr+0sXkcwC/gYcWwkw/ADNik+pRSfSZ6T2AVAoS475erA -cIFYCD0uCrosMjaw1hL4TRwKh+8BVZi7CUFZPp0jvMyAN77aV+K2u8Nx1UcvZDzp -OTbudK1jnvbuMnYqCTPfGObbkbR6HoFN6OLdKa5QV3VAMuqOj/4n+3zUSfsI4WYX -Les4a5l7cbz5R68BD9XC03LJCFBK91yDKRFocrl5g6RzW9bfC7AzfCU= ------END ENCRYPTED PRIVATE KEY----- ------BEGIN CERTIFICATE----- -MIIDfzCCAmegAwIBAgIEUFic9zANBgkqhkiG9w0BAQsFADBvMQswCQYDVQQGEwJU -UzETMBEGA1UECBMKVGVzdCBTdGF0ZTESMBAGA1UEBxMJVGVzdCBUb3duMREwDwYD -VQQKEwhUZXN0IG9yZzEQMA4GA1UECxMHVGVzdCBPVTESMBAGA1UEAxMJVGVzdCBV -c2VyMCAXDTE0MDkyMjA5MTExMVoYDzIxMTQwODI5MDkxMTExWjBvMQswCQYDVQQG -EwJUUzETMBEGA1UECBMKVGVzdCBTdGF0ZTESMBAGA1UEBxMJVGVzdCBUb3duMREw -DwYDVQQKEwhUZXN0IG9yZzEQMA4GA1UECxMHVGVzdCBPVTESMBAGA1UEAxMJVGVz -dCBVc2VyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA+6g5sYzXiNOA -hR7C8wc8buxU/JgcbdHpHIR44iuXjpepBYAE7hRsWM7H4cuXrKiRxS9UMOadqkGF -Qqb5sG6lo2UUhcj4qlN6hKDc/+AMZMIW1mvQldiygCAkqgM8iso+kw56dpVuerG/ -k1nd8f+X9rjXN6/DIMznZcMy2d9ByIFuixFKElPvOWx9q9N4aiueOd5FM5eHxp+3 -F4uCTrpM5zkS7Rmf5GVtCofc8KgaTLLp4D0Ge5VUJm7yW8fuU3eIpin4ivjk+Gye -Q3t0BsrmNyQy3CmKGOBP/vX0+wEMvGN2xqNgAFP9dxA+AbJMiAfsmoWvxXaPktqC -DOspTCFqbwIDAQABoyEwHzAdBgNVHQ4EFgQUILviRCmSrhuLDmF0nus4pv2uu7gw -DQYJKoZIhvcNAQELBQADggEBAGnfGYL7nDm5taDPRxuGGMqUPwRnH2bXwef6S2Xb -/nIEFtNheVFQFtKNn5Ikq68DTFMP06yXLnI7F40+ZiQezRBB1EPPmDL2fYKc9fL1 -SHntu6HLgP/Y5nnCVegtL8l9745gQZnnXlMtkTs2HFwffznIHW/3STO0Bcj0+KMa -p8vebMjmvV7bZEGvrcrVXL55QPZXJwRuQMXJB3f5XhAEH1VqAhTW6DrvBUnuESwo -9fxxA5gmblt80SQYdKr2I08OTk0qmyF8zNuffTOiSS8/V6Cf7CntuPWjSuVf1EVP -MH6KkSjceLZ99Y7bvl7KKvQ4Kj5Bp27PwlRvtYbfCUmQEG8= ------END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/RSASSAPSSTest/ca.crt b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/RSASSAPSSTest/ca.crt deleted file mode 100644 index cd2f996d99..0000000000 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/RSASSAPSSTest/ca.crt and /dev/null differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/certs/ed448.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/RSASSAPSSTest/ca.pem similarity index 50% rename from itext.tests/itext.sign.tests/resources/itext/signatures/certs/ed448.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/RSASSAPSSTest/ca.pem index a353daabbd..a923e6ec69 100644 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/certs/ed448.pem +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/RSASSAPSSTest/ca.pem @@ -1,25 +1,3 @@ ------BEGIN ENCRYPTED PRIVATE KEY----- -MIGrMFcGCSqGSIb3DQEFDTBKMCkGCSqGSIb3DQEFDDAcBAjjXVpbVVssSQICCAAw -DAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEHeL6O3rZ8BWr8G5nXTj/S8EUIoH -PbIxONLZuCNhv/NGjAaE7Ma53fuOKjD/NpPfEa7pR81KMBwC8ykfRTpWfs0/aVY1 -5SYX6iMMDGHkWwDx+x2Gczk3/HO/QbVPtcFi9CKI ------END ENCRYPTED PRIVATE KEY----- ------BEGIN CERTIFICATE----- -MIICdDCCAVygAwIBAgICEAYwDQYJKoZIhvcNAQELBQAwPTEYMBYGA1UECgwPUERG -IEFzc29jaWF0aW9uMSEwHwYDVQQDDBhEaWdTaWcgRXh0ZW5zaW9uIERlbW8gQ0Ew -HhcNMjEwMTAxMDAwMDAwWhcNMzEwMTAxMDAwMDAwWjBKMRgwFgYDVQQKDA9QREYg -QXNzb2NpYXRpb24xGDAWBgNVBAwMD0RvY3VtZW50IFNpZ25lcjEUMBIGA1UEAwwL -QWxpY2UgTWNGb28wQzAFBgMrZXEDOgBQxzLqZ+9E8y/dHuCD8RPlqyq8dBRjxSiB -4RZl/TvsuALmIPsKOnoiB/gIa4+8IxiM1R08tcfomYCjUjBQMB0GA1UdDgQWBBSY -hRROaQ1ta3BSa8OPktt26bEy5TAfBgNVHSMEGDAWgBRGdbBGXT7btNdUkKKffG3L -TD1i0zAOBgNVHQ8BAf8EBAMCBsAwDQYJKoZIhvcNAQELBQADggEBANfIM6oT5Qe7 -/F9eb7plMUVy5JFQips8IDz5DmrrkYyJHYciFm2rccO7hKUMNsNSx6tyiMJwZS8D -RjjeDCwJjF+msgLGoMGu0Ql26ZWYtNaBfGmCsdUIJUIcrDPPvkOmdgmcsQjMyevj -/0mkXPTBu2gYss7Z/k9rO6us2ZkIU8ucRZ2M6jIF1cwq19oH6rnm5/iAnQKCm6Ye -ezXCFE5jgerKqyMBByOT/gBE8rR8KDdpFz+LED81DnNu4Yqf5b0bAy1MI9TfO9YR -gDW3G8bEPZVQ6UoJs1ZuIB//LDu+gcbHjnIpEXPO5ndaKzdtRpOeTIkhNuOb5HNV -d6uRcAfj1oc= ------END CERTIFICATE----- -----BEGIN CERTIFICATE----- MIIDWzCCAkOgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPTEYMBYGA1UECgwPUERG IEFzc29jaWF0aW9uMSEwHwYDVQQDDBhEaWdTaWcgRXh0ZW5zaW9uIERlbW8gQ0Ew diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/RSASSAPSSTest/rsa.crt b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/RSASSAPSSTest/rsa.crt deleted file mode 100644 index c6fa6b6714..0000000000 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/RSASSAPSSTest/rsa.crt and /dev/null differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/RSASSAPSSTest/rsa.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/RSASSAPSSTest/rsa.pem new file mode 100644 index 0000000000..7c0810c589 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/RSASSAPSSTest/rsa.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDVTCCAj2gAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwPTEYMBYGA1UECgwPUERG +IEFzc29jaWF0aW9uMSEwHwYDVQQDDBhEaWdTaWcgRXh0ZW5zaW9uIERlbW8gQ0Ew +HhcNMjEwMTAxMDAwMDAwWhcNMzEwMTAxMDAwMDAwWjBKMRgwFgYDVQQKDA9QREYg +QXNzb2NpYXRpb24xGDAWBgNVBAwMD0RvY3VtZW50IFNpZ25lcjEUMBIGA1UEAwwL +QWxpY2UgTWNGb28wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDGGDbm +XUfRFuAgvp+ODOOXC04rmsXpcruTUcNuz6XBNcqQfUm8Zdms1jG+PwzCuiYDArIt +GB7b00/ueZUMrqx23l6jXr3mL3B7644m61kfPRRDsApIdLnTULRCLp5waEQDDAWa +uYANAVqpl93A7x7SeF/SeEX0e7OXS5zT5NnZ0AydyExPbKMmsE5+P/Hrh1aBqTiG +hLPlxfYAHeLWD+2N/zIlNVLUdZV96pNKRS5WReY0Mu9PvBtvdWnZzVTlLJXDGjyY +A9drxM6/zy06bQWjImnES9V4mCwfNGYhhNOYgeO1f3G7u4MqQtlkjyJfdBNi4a6f +xU0ZfY5TumgQXZKXAgMBAAGjUjBQMB0GA1UdDgQWBBRadoeKDREfL2wDVEkhlhoD +x1NI6TAfBgNVHSMEGDAWgBRGdbBGXT7btNdUkKKffG3LTD1i0zAOBgNVHQ8BAf8E +BAMCBsAwDQYJKoZIhvcNAQELBQADggEBAGaefIP/MAj3OTQMoCHjgs6SykwWg2z1 +lWm+6OEvnG2dsHs2+mIlRU5n1HlEqaEJrCN9DknAl86T1qkZWqsVE0556/ctTdii +rUK3LhxwtnfMqkZxWyQIUMDbeAFhMqk4tjSGGLWlwjjXQbwmA4tdP1C8L2EoPXm8 ++jZ8JbUoDwE61JaTkTYsrtVpXu5ZOPBoPrgBQvyExj8H8ZRkeX0Kg22eosDqXQQ9 +IOm9ej8V0wfC6+IJded6ZurJVD4XDSyNZh9Bi3ro4tPz+kikwxVyCIBUa6NG+ndF +Hx3ZbkhZcx0Y1P+ypogf3M36QKy7BHfjw5/vbjV5YLou7VyYIM5a9/k= +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/1.png b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/1.png similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/1.png rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/1.png diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_createdAndSignedSignatureField.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_createdAndSignedSignatureField.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_createdAndSignedSignatureField.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_createdAndSignedSignatureField.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_deprecatedLayersTest.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_deprecatedLayersTest.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_deprecatedLayersTest.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_deprecatedLayersTest.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_emptySignatureAppearance.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_emptySignatureAppearance.pdf similarity index 71% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_emptySignatureAppearance.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_emptySignatureAppearance.pdf index e5a2cb45f3..34d21d1fd0 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_emptySignatureAppearance.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_emptySignatureAppearance.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_fieldLayersTest.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_fieldLayersTest.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_fieldLayersTest.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_fieldLayersTest.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_fontColorTest01.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_fontColorTest01.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_fontColorTest01.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_fontColorTest01.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_layer0Test.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_layer0Test.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_layer0Test.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_layer0Test.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_layer0WithImageAndNegativeImageScale.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_layer0WithImageAndNegativeImageScale.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_layer0WithImageAndNegativeImageScale.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_layer0WithImageAndNegativeImageScale.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_layer0WithImageAndPositiveImageScaleTest.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_layer0WithImageAndPositiveImageScaleTest.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_layer0WithImageAndPositiveImageScaleTest.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_layer0WithImageAndPositiveImageScaleTest.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_layer0WithImageTest.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_layer0WithImageTest.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_layer0WithImageTest.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_layer0WithImageTest.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_layer2Test.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_layer2Test.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_layer2Test.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_layer2Test.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_reuseAppearance.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_reuseAppearance.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_reuseAppearance.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_reuseAppearance.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_reuseAppearanceCompatibility.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_reuseAppearanceCompatibility.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_reuseAppearanceCompatibility.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_reuseAppearanceCompatibility.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_reuseAppearanceDeprecated.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_reuseAppearanceDeprecated.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_reuseAppearanceDeprecated.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_reuseAppearanceDeprecated.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signExistingNotMergedFieldNotReusedAP.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signExistingNotMergedFieldNotReusedAP.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signExistingNotMergedFieldNotReusedAP.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signExistingNotMergedFieldNotReusedAP.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signExistingNotMergedFieldReusedAP.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signExistingNotMergedFieldReusedAP.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signExistingNotMergedFieldReusedAP.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signExistingNotMergedFieldReusedAP.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signExistingNotMergedFieldReusedAPEntryNDic.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signExistingNotMergedFieldReusedAPEntryNDic.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signExistingNotMergedFieldReusedAPEntryNDic.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signExistingNotMergedFieldReusedAPEntryNDic.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signatureFieldAppearanceTest.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signatureFieldAppearanceTest.pdf similarity index 79% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signatureFieldAppearanceTest.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signatureFieldAppearanceTest.pdf index 3b4b50654a..0963394d15 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signatureFieldAppearanceTest.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signatureFieldAppearanceTest.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signatureFieldBackground.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signatureFieldBackground.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signatureFieldBackground.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signatureFieldBackground.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages1_mode_DESCRIPTION.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages1_mode_DESCRIPTION.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages1_mode_DESCRIPTION.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages1_mode_DESCRIPTION.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages1_mode_GRAPHIC.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages1_mode_GRAPHIC.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages1_mode_GRAPHIC.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages1_mode_GRAPHIC.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages1_mode_GRAPHIC_AND_DESCRIPTION.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages1_mode_GRAPHIC_AND_DESCRIPTION.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages1_mode_GRAPHIC_AND_DESCRIPTION.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages1_mode_GRAPHIC_AND_DESCRIPTION.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages1_mode_NAME_AND_DESCRIPTION.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages1_mode_NAME_AND_DESCRIPTION.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages1_mode_NAME_AND_DESCRIPTION.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages1_mode_NAME_AND_DESCRIPTION.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages2_mode_DESCRIPTION.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages2_mode_DESCRIPTION.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages2_mode_DESCRIPTION.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages2_mode_DESCRIPTION.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages2_mode_GRAPHIC.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages2_mode_GRAPHIC.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages2_mode_GRAPHIC.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages2_mode_GRAPHIC.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages2_mode_GRAPHIC_AND_DESCRIPTION.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages2_mode_GRAPHIC_AND_DESCRIPTION.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages2_mode_GRAPHIC_AND_DESCRIPTION.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages2_mode_GRAPHIC_AND_DESCRIPTION.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages2_mode_NAME_AND_DESCRIPTION.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages2_mode_NAME_AND_DESCRIPTION.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages2_mode_NAME_AND_DESCRIPTION.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages2_mode_NAME_AND_DESCRIPTION.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages3_mode_DESCRIPTION.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages3_mode_DESCRIPTION.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages3_mode_DESCRIPTION.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages3_mode_DESCRIPTION.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages3_mode_GRAPHIC.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages3_mode_GRAPHIC.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages3_mode_GRAPHIC.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages3_mode_GRAPHIC.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages3_mode_GRAPHIC_AND_DESCRIPTION.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages3_mode_GRAPHIC_AND_DESCRIPTION.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages3_mode_GRAPHIC_AND_DESCRIPTION.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages3_mode_GRAPHIC_AND_DESCRIPTION.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages3_mode_NAME_AND_DESCRIPTION.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages3_mode_NAME_AND_DESCRIPTION.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages3_mode_NAME_AND_DESCRIPTION.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages3_mode_NAME_AND_DESCRIPTION.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages4_mode_DESCRIPTION.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages4_mode_DESCRIPTION.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages4_mode_DESCRIPTION.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages4_mode_DESCRIPTION.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages4_mode_GRAPHIC.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages4_mode_GRAPHIC.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages4_mode_GRAPHIC.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages4_mode_GRAPHIC.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages4_mode_GRAPHIC_AND_DESCRIPTION.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages4_mode_GRAPHIC_AND_DESCRIPTION.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages4_mode_GRAPHIC_AND_DESCRIPTION.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages4_mode_GRAPHIC_AND_DESCRIPTION.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages4_mode_NAME_AND_DESCRIPTION.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages4_mode_NAME_AND_DESCRIPTION.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signaturesOnRotatedPages4_mode_NAME_AND_DESCRIPTION.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signaturesOnRotatedPages4_mode_NAME_AND_DESCRIPTION.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signedSignatureField.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signedSignatureField.pdf similarity index 76% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signedSignatureField.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signedSignatureField.pdf index 804629ccd2..da2ba9f986 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signedSignatureField.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signedSignatureField.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signed_hybrid.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signed_hybrid.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/cmp_signed_hybrid.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/cmp_signed_hybrid.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/documentWithRotatedPages.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/documentWithRotatedPages.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/documentWithRotatedPages.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/documentWithRotatedPages.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/emptyFieldNotMerged.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/emptyFieldNotMerged.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/emptyFieldNotMerged.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/emptyFieldNotMerged.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/emptyFieldNotMergedEntryNDict.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/emptyFieldNotMergedEntryNDict.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/emptyFieldNotMergedEntryNDict.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/emptyFieldNotMergedEntryNDict.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/hybrid.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/hybrid.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/hybrid.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/hybrid.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/itext.png b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/itext.png similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/itext.png rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/itext.png diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/noSignatureField.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/noSignatureField.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/noSignatureField.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/noSignatureField.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/signatureFieldNotMergedWithWidget.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/signatureFieldNotMergedWithWidget.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/signatureFieldNotMergedWithWidget.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/signatureFieldNotMergedWithWidget.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/simpleDocument.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/simpleDocument.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/simpleDocument.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/simpleDocument.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/test.cer b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/test.cer new file mode 100644 index 0000000000..fbaad2b382 Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/test.cer differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/test.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/test.pem new file mode 100644 index 0000000000..4cbee8fcbd --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/test.pem @@ -0,0 +1,74 @@ +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQrCI2KefPpkSRg93G +8wROsAICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEAQIEEERFvpTFKlKcFCBG +BvnLqGIEggTQjNcHtHwyEdouh5ct4ZXV3GZ0H8N6CZCi/tuiVn/BOWdgA7deGC6P ++7dg+1vcLj7VofkHM2//7wREw13GrYPfqULXWTxRJ978KM2mipcEEaaxCf7GWYoO +Y2gRcsc5Y/C4XS5Erpj+OMW/yXXiBmOGQRImC1hzc2Ggm3KoQuv5j7XDrMlfnMpm +QSURPxRoo1YwFgyHhL5gziCu7a9Vy+IygicrEUzlcJ2ooDKR/SiSBQXiVJbL7MmZ +bPmHhQ5TwD4mUcBgT+unkkTW67RsH1Le6ajCvjo1UBEdtmRAsygaoUpD3hBeon1F +gzrjBV3UgmvWcWDWJlBN8f5/3RZrINxHfl2aZoGpV+KyeniWaSRgpeuqFUkdvgVG +4y2rCaBse7NUMjVN5eq81tN5kClmvZFvdTZGlcYnUZ14b7ZVeGS0TC0yW/DloeNm +UdQ6qo2XZ/s/ZdL2erNKO2jvybIjEGihP3ttTPTLGgiCg62qa+8TSDxOc3Ue6g6s +OEwuI+ENTPs+kmWo814foXo/uEJ5E2NU7u38RFqnj6ksV9olAtin8NcN3Eh9OBBn +LA9bqh9A1NkGjN+A8Rlu25SxmSsxOIa8iR3L+h7lZRO5/72gu7SxnjJxbflS1ktF +gko7XIZOuN8psJ7lMAB+LGUZp2cK6oB9/naH/InoMVKU55f/Ln3YOc+cCpPlEzlz +oJsbkajNnfIESKEO+EnXOGNLhtsyq7fh3cjf7eGMN7FGdZVVIYfQG7ZrtLwDT5zc +9DMYZfdmUqGT20MtG04MpeQqqCBlSATjTz51wLcFFdctyGBBPRvbSWAO49M8PvKx +ASrtGrc/x/UjmgZc1Td6wW6lsp9GiAWbiSuqsHd9CSIeertpDXiow0zjfNMMBp8Z +4rfR2Kx5DkEJhTnoZiiNE8dYFPRGZoNqFzpEa5XNj9GLiFDyUM/TDnaW+GCsopn2 +FFH2TLqYS4GTp9yfiO9QZFVw9aXhzrvqC0mCirrxJjpa7on72nYvKUZXKFZjRJuk +0zIcYZq+7aFoNLuxyjnqCvvVCuR1aMbi1SQIFbk1ipfcT6DoDe3zoKkAmxs9d31f +8O+OYhGSev7WgXM4lLUf7aNmn56NrQ+gKJxx6fUsYK7/qcteqExpH2NDfCay55Nd +qa9WScL/uaTEM+YGosye5WbDJJ81aedsCPpAzYpOPNnpFYlMtIzyxVDqtjHNzKuq +ui2SbugZ1oAzWZHPttohdHvdrNgJydNg8d0LHuceqZbmvQOXhPLagPUgVQnMczyj +TJqX+Z1uCIlwpjM+kgQ7EL8LV/b8Tttdd294080q/j20yMUfj9ZVlyl0ZeqgaDXF +M204HVB/k3IqHjagR0Qnc45NglFVUOtitJ+TOlFTu/hQYCNG7UPSwW1kZfP1dNZf +MNrh/UmeQAlJoAxIjY2ndGMkDuHU+/3WuETkYtY019DMSHHqMB3lN7kKBcs1Ssdj +gvIypodexktcG2N8xMji1Su5Gp2HB14hGWtGCeA7rsCFft3SoLuwoYIoXQasqV9e +ETyH4UJ+eNtO1aSvG4dGZwq/uEKVQMBQkCMWi1G/moiEjDMSBauomnWWSnVf4qn2 +oPq3XcxDJFb9oCzxSZwjM5MFuVik07pRLZXgmY/tGYhTtB2HatSpscc= +-----END ENCRYPTED PRIVATE KEY----- +-----BEGIN CERTIFICATE----- +MIIDkTCCAnmgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwPzELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MSAwHgYDVQQDDBdpVGV4dFRlc3RBcHBlYXJhbmNlUm9v +dDAgFw0yMDAxMDEwMDAwMDBaGA8yNDAwMDEwMTAwMDAwMFowMDELMAkGA1UEBhMC +QkUxDjAMBgNVBAoMBWlUZXh0MREwDwYDVQQDDAhUZXN0VXNlcjCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBALcm1EvBk22gj9FrzoW6vJk9ixjDHS7SxrSn +nX7DUHvldq6ZRFqDSDZNlcd9HgoQ7/YGvXtquqYbqMVupk8uphtR7m2XRzLM9/YJ +h2Na1z7FrwsvJNtSYgLblzgFovcRhFE5ej2EKyjhh6BPIxBpYRAqy/kdPCRykNbU +XuIhvCG96+0RUqNoDZuAZx2Qhis6A9MkcuPXKH0Mh77qw/LJBM20ceNHxB4BOib3 +Vh6BUi5TrxSZCAW42X5qTZNlNNcgXI/aRMOaU9wJAbcsf9mbwN+V7Fz241DvrMX/ +H/ofpMS1g++xbXRQ7Ux7RwQnS5rBISsML0VlnXaj51aaKoeZsXkCAwEAAaOBozCB +oDAdBgNVHQ4EFgQUULQWZW++8B+zjGS2jnFK9twidOEwHwYDVR0jBBgwFoAU31+h +p8yurVuCSb47mYffu69v3cowDgYDVR0PAQH/BAQDAgXgME4GA1UdHwRHMEUwQ6BB +oD+GPWh0dHA6Ly90ZXN0LmV4YW1wbGUuY29tL2V4YW1wbGUtY2EvY3Jscy9sZWFm +LTEtY3JsL2xhdGVzdC5jcmwwDQYJKoZIhvcNAQELBQADggEBAD5EZH232RWoDPWp +TZzRdNRwKwXxVw/s148L+wyvzDretF6oIaV62KkwLndOsyGgMW+3cfgKbhjd36lW +3Hhk+VcWQBMW5/EctFvf9JMX2oDF8hKVcai0gaTIpVhpQKKk/jcBa7I0K2BD6Ply +xmRHManmXm8pFLDVoe6VSBr8uQGb951uvzhacy9nN+BdqZYBOLo1Qw5RgZpiaN9z +wjwMOTtgbfR9DmvAuurpBkK7zzYJ0u0uOilfX+DCaJz5wQweSxLDXFObJ8vkLFYY +I5GZRvJjZGVCUVIAM0p5iNlFnPMrOMVx3OVw5NDXkIdOynDBc3Q6TKhoxiCng6fs ++3D5f3w= +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDsjCCApqgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPzELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MSAwHgYDVQQDDBdpVGV4dFRlc3RBcHBlYXJhbmNlUm9v +dDAgFw0wMDAxMDEwMDAwMDBaGA8yNTAwMDEwMTAwMDAwMFowPzELMAkGA1UEBhMC +QkUxDjAMBgNVBAoMBWlUZXh0MSAwHgYDVQQDDBdpVGV4dFRlc3RBcHBlYXJhbmNl +Um9vdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJ6ftTqEedqlfU8C +BluXWlNf2P3bn1dgV2/W/vBFlPfuEa1Cx/CrhlpXWr+aHFeTr0Q0LYgInJaUFvb2 +p0VJy4q25D9t6zVuwrlJ9wo3CUKk9nC7FUykSBI9Rbwid8dpUznqjGeGoT7LIAt7 +qyfRGbdSuA3qeNJkHVW6wZ7wKCduyfqrD8eYV8DAZEpeK0UWqkfm8biaupsu8znI +hdXW1pueDMA3Maotjm2PybvQNxwMLEaQ7MqiPje1p1pk4hvY1g+LD75n1p/9nyPe +l7eCMiAO2fcG15M/nI/riloQp7oeGPxkY562M9JpZvy5EgoUm9w39ZWUAbvFWPl1 +pqkQgwsCAwEAAaOBtTCBsjAdBgNVHQ4EFgQU31+hp8yurVuCSb47mYffu69v3cow +HwYDVR0jBBgwFoAU31+hp8yurVuCSb47mYffu69v3cowDwYDVR0TAQH/BAUwAwEB +/zAOBgNVHQ8BAf8EBAMCAeYwTwYDVR0fBEgwRjBEoEKgQIY+aHR0cDovL3Rlc3Qu +ZXhhbXBsZS5jb20vZXhhbXBsZS1jYS9jcmxzL3Jvb3QtY2EtY3JsL2xhdGVzdC5j +cmwwDQYJKoZIhvcNAQELBQADggEBAADuDp8U0cVqTZLSPMZnCQK/0VjosgG+Mnrj +9MpOp/S8Htf+zvpDoyJkOVITNPX0rtzkqr2BF8JskEN65LyWiIlLGre7uojn07pf +dlNk44RHM/Jc692avM+3QHulgF92rtvF8Zw9kfi+MeT+/FDspKzEEcrEUUaA2Hll +7A4j7pInPG9VPZRAbu1kgDBzor/t23oreEIsnbpdM1iSbDTpIoz3oAD9ZlYPk9fk +3jrFpLIo9Hwn0iHxB0c/lB2M9kRRQhywhWnTEnhS2Eb6RYZwIvcCFTiv+OP0KCAO ++OhlFwKkLEGGR7Qn0X5JA0CVJ45vC/+u/XU1asYTR2J4zWQHvfs= +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/unsignedSignatureField.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/unsignedSignatureField.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/sign/PdfSignatureAppearanceTest/unsignedSignatureField.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignatureAppearanceTest/unsignedSignatureField.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignedAppearanceTextTest/cmp_noReasonLocationSignDateInAppearanceText.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignedAppearanceTextTest/cmp_noReasonLocationSignDateInAppearanceText.pdf new file mode 100644 index 0000000000..724bfc6182 Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/SignedAppearanceTextTest/cmp_noReasonLocationSignDateInAppearanceText.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/TimestampSigTest/cmp_timestampTest01.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/TimestampSigTest/cmp_timestampTest01.pdf index 3d0cefe2fc..d7c3b1963c 100644 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/sign/TimestampSigTest/cmp_timestampTest01.pdf and b/itext.tests/itext.sign.tests/resources/itext/signatures/sign/TimestampSigTest/cmp_timestampTest01.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/README.md b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/README.md similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/README.md rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/README.md diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/createTestData.cmd b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/createTestData.cmd similarity index 53% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/createTestData.cmd rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/createTestData.cmd index 0675533643..ba87e44b37 100644 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/createTestData.cmd +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/createTestData.cmd @@ -1,15 +1,18 @@ REM create the test keys IF [%1] == [] goto continue md keys -openssl genrsa -out keys/root_key.pem -passout pass:testpassphrase 2048 -openssl genrsa -out keys/im_key.pem -passout pass:testpassphrase 2048 -openssl genrsa -out keys/sign-key.pem -passout pass:testpassphrase 2048 -openssl genrsa -out keys/crl-key.pem -passout pass:testpassphrase 2048 +openssl genrsa -out keys/root_key.pem -aes256 -passout pass:testpassphrase 2048 +openssl genrsa -out keys/im_key.pem -aes256 -passout pass:testpassphrase 2048 +openssl genrsa -out keys/im2_key.pem -aes256 -passout pass:testpassphrase 2048 +openssl genrsa -out keys/sign-key.pem -aes256 -passout pass:testpassphrase 2048 +openssl genrsa -out keys/crl-key.pem -aes256 -passout pass:testpassphrase 2048 :continue call :runTestCase happyPath call :runTestCase crlIssuerRevokedBeforeSigningDate call :runTestCase crlIssuerAndSignCertHaveNoSharedRoot +call :runTestCase crlSignerInValidatedChain +call :runTestCase multipleCrlIssuerCandidates EXIT :runTestCase diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot.yml b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot.yml similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot.yml rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot.yml diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/ca.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/ca.cert.pem new file mode 100644 index 0000000000..efb7717302 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/ca.cert.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDSzCCAjOgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI1MDAwMTAxMDAwMDAwWjA1MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxFjAUBgNVBAMMDWlUZXh0VGVzdFJvb3QwggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQDYxUs+SgZkRkOhOfddCnPeuE1QP2kAm6gAsg4qjNzr +rZpZvwziyWaz6bXXq8fATjXEAdypAiWL/BDZscdCM/M11jds9mMv7dMvCtLns6Oe +4GbChYxxloN2rVxElFPK2siKBaEeWyItr2Ms0P+hSR5uHjFt+krzl2zv828fyEnH +fPvln42SAcuCKsLmfjtutus5jFKBFF8oiqDFlI2eXYggKV7JELttgPLobv2ZyFa5 +nXo/xbtzlPb8AvV3/mxpX4prFhBXupJXuCwmqmzVRqGbwKSz/Bewb/4aJGSpg32x +yIWeXTld58f+Jntfes8xHwK0aJB/Tm2WrH+RWoV+TN/pAgMBAAGjYzBhMB0GA1Ud +DgQWBBR0MlTFwFzoq8mPVusDjIEnL5avqzAfBgNVHSMEGDAWgBR0MlTFwFzoq8mP +VusDjIEnL5avqzAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIC5DANBgkq +hkiG9w0BAQsFAAOCAQEAK2dbxbQ7jEdtqvnMpKOZsB55PDO5OZ2hPYilT5ZVZNt1 +jdE94HdCBHED3upmOeBH+XtsK/MLk+eYICM5SZwWVCBY0aQQR0URyTsX4SA/12A5 +VhrnP6bqy4b+3mO3J9s0go59cZOtSkxQ7191teEQMsDeh8GxXGLW/7Tf4x6v7U34 +B7UghMhUD2bHJ7U8MOqto9fVar/9S93tc9vRtYOXZbfRwjFKOYD4IFm7cH3VnrX7 +od3KUEKGKhQ2ZaqrtnW19xNTbdRcMT3+8QSai9DLV0kGGSSY09AHDO3WvxkAs9ZI +cIsMM/n+mLK0Km9fh5uE3k6NmiN3GV+QMyjbmFnVNg== +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/chain.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/chain.pem new file mode 100644 index 0000000000..c1951e4162 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/chain.pem @@ -0,0 +1,101 @@ +-----BEGIN CERTIFICATE----- +MIIDSzCCAjOgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI1MDAwMTAxMDAwMDAwWjA1MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxFjAUBgNVBAMMDWlUZXh0VGVzdFJvb3QwggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQDYxUs+SgZkRkOhOfddCnPeuE1QP2kAm6gAsg4qjNzr +rZpZvwziyWaz6bXXq8fATjXEAdypAiWL/BDZscdCM/M11jds9mMv7dMvCtLns6Oe +4GbChYxxloN2rVxElFPK2siKBaEeWyItr2Ms0P+hSR5uHjFt+krzl2zv828fyEnH +fPvln42SAcuCKsLmfjtutus5jFKBFF8oiqDFlI2eXYggKV7JELttgPLobv2ZyFa5 +nXo/xbtzlPb8AvV3/mxpX4prFhBXupJXuCwmqmzVRqGbwKSz/Bewb/4aJGSpg32x +yIWeXTld58f+Jntfes8xHwK0aJB/Tm2WrH+RWoV+TN/pAgMBAAGjYzBhMB0GA1Ud +DgQWBBR0MlTFwFzoq8mPVusDjIEnL5avqzAfBgNVHSMEGDAWgBR0MlTFwFzoq8mP +VusDjIEnL5avqzAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIC5DANBgkq +hkiG9w0BAQsFAAOCAQEAK2dbxbQ7jEdtqvnMpKOZsB55PDO5OZ2hPYilT5ZVZNt1 +jdE94HdCBHED3upmOeBH+XtsK/MLk+eYICM5SZwWVCBY0aQQR0URyTsX4SA/12A5 +VhrnP6bqy4b+3mO3J9s0go59cZOtSkxQ7191teEQMsDeh8GxXGLW/7Tf4x6v7U34 +B7UghMhUD2bHJ7U8MOqto9fVar/9S93tc9vRtYOXZbfRwjFKOYD4IFm7cH3VnrX7 +od3KUEKGKhQ2ZaqrtnW19xNTbdRcMT3+8QSai9DLV0kGGSSY09AHDO3WvxkAs9ZI +cIsMM/n+mLK0Km9fh5uE3k6NmiN3GV+QMyjbmFnVNg== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDijCCAnKgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwOjELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRswGQYDVQQDDBJpVGV4dE90aGVyVGVzdFJvb3QwIBcN +MDAwMTAxMDAwMDAwWhgPMjQ1MDAxMDEwMDAwMDBaMDoxCzAJBgNVBAYTAkJFMQ4w +DAYDVQQKDAVpVGV4dDEbMBkGA1UEAwwSaVRleHRUZXN0Q3JsSXNzdWVyMIIBIjAN +BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwnsONfztmnDdLJKbWd8sE/2txomx +72HBnrBM3G2bLpGfcvAFm9n/F0WLf1dPDYY94JAFKsBGG0Enh4eBJ753ZHgug/qw +DIiF5DnRH57e2EtoJWwXjeSm5KLIsaWcUsUGHJDfS8SfWDqOIDCp+qm2mv1M98po +KsIo4lRHyM4XDL5ERGUAYklA0h5noHP1V1JnCQ0/4Z+j4dX0tfTnsxp4wA+Cu8Am +sfL+UP3LTu7Soo3rbHMtn8yf12j7eohMRTX71eRf1fR1Nes0wA72RPe6RHpd1kiX +yW8P/Y+BNNpqujnW/R6LcjsVlc2iSPK4XonwBExXGp44yVVQjEt4G/uPrQIDAQAB +o4GXMIGUMB0GA1UdDgQWBBQSbqEw8HXXDUnva1e6YGF7DBbGdTAfBgNVHSMEGDAW +gBSJQJIqlFRpEC9NMuebZTa38Lxk1TAOBgNVHQ8BAf8EBAMCAcIwQgYDVR0fBDsw +OTA3oDWgM4YxaHR0cDovL2xvY2FsaG9zdC50ZXN0L2RlZmF1bHQvY3Jscy9jcmwv +bGF0ZXN0LmNybDANBgkqhkiG9w0BAQsFAAOCAQEAY6Ql0oP20FsZrtKyLVFYJSkL +c3R4mTRHJ5JbrgtPSLkLDxN3QGssgwmhZUyf8TvaCYVBomedFvOVd3xizmQPcAkD +yDeX7XTvkrg9aSaGyjtKcOduk8eVHyPvAnFZ4eJ7m0vYJThLeVlupRYKnMcVR9AA +HMxKk+YTTaTr6o2zWE63vbzkdAvJTYuVzfDw2Qo+6IeAGL3jD9ipa6+krN/h6z8k +EPun+ndDEijo9TcPv+pPT+DHcXiWcLCQFi7611h4ErvFtUJoDl3xoTMsgqMKRzJJ +46HaLTKqkLikI/s4bKZ23brDHUYzpFCHs5WkQpRfdq6jHek9lBHNRK+tp66s6w== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDQjCCAiqgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA9MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxHjAcBgNVBAMMFWlUZXh0VGVzdEludGVybWVkaWF0ZTCCASIwDQYJ +KoZIhvcNAQEBBQADggEPADCCAQoCggEBAJ6M9OSQgx20Fw14rYFeM6HQuQxBD276 +e6kXMpmdsbbkvExq5mrAWPvFGYHCmRAtH7pGm1pL91Zlgh1CbUPzwSa/Lfp9FeAX +83G7OJn0sY3kJRthtj5B0dGinXSIFCIb6gx9ICzoVpY9Ljvl4tyBr0dkGmED3MBx +SFltOMPplDhYwFekL7woNXMFIAxMnDWuS7dZ7xEpLAwNfH9D92I4lzSrQ9TrxwDP +dW2gWGvi2eu77W4YqFQgydgbKmFHAzDUTA01LNmKZkASBcLUoiLnLBMmVYgDMH4f +o4oj+2/J/OZNuGv5DK9dRCryAhnY3f8/9b8JzoPeRCmgRO9IU7ObZ/0CAwEAAaNS +MFAwHQYDVR0OBBYEFIlAkiqUVGkQL00y55tlNrfwvGTVMB8GA1UdIwQYMBaAFHQy +VMXAXOiryY9W6wOMgScvlq+rMA4GA1UdDwEB/wQEAwIB5jANBgkqhkiG9w0BAQsF +AAOCAQEAMoIJ86nzczzR41l5EFHlxGvUEQY/w7BJ42LICN3F12WPmJ+A3i/GAJSQ +14W+Jy8CXEhEFZF3R45vuOAGhOkF7igtbXeeVXunM3rmi8XIlpGjqbBZxC5w1Fd8 +IPOTArrzcF8agwthRzKOEpFSklmpUDT4MYZkdzR7TVM6TkdL+ModYFrhf9/+OFGb +qHzKUPVv+dvNaKn6JvKfQ311MKG3fLU7vyKEUNoolAnLMy3VETsnhMTk6Wa5rfzJ +eq2sdBiLxgwC3xhYk33Cla0X3hsr++Yqb8BX1ztKaRxu0PSi+KKJ9kvXAxRkFlwh +Xa7iIRXelUhftWRF/4VgDsDhWx+eDQ== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDVTCCAj2gAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwOjELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRswGQYDVQQDDBJpVGV4dE90aGVyVGVzdFJvb3QwIBcN +MDAwMTAxMDAwMDAwWhgPMjUwMDAxMDEwMDAwMDBaMDoxCzAJBgNVBAYTAkJFMQ4w +DAYDVQQKDAVpVGV4dDEbMBkGA1UEAwwSaVRleHRPdGhlclRlc3RSb290MIIBIjAN +BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnoz05JCDHbQXDXitgV4zodC5DEEP +bvp7qRcymZ2xtuS8TGrmasBY+8UZgcKZEC0fukabWkv3VmWCHUJtQ/PBJr8t+n0V +4Bfzcbs4mfSxjeQlG2G2PkHR0aKddIgUIhvqDH0gLOhWlj0uO+Xi3IGvR2QaYQPc +wHFIWW04w+mUOFjAV6QvvCg1cwUgDEycNa5Lt1nvESksDA18f0P3YjiXNKtD1OvH +AM91baBYa+LZ67vtbhioVCDJ2BsqYUcDMNRMDTUs2YpmQBIFwtSiIucsEyZViAMw +fh+jiiP7b8n85k24a/kMr11EKvICGdjd/z/1vwnOg95EKaBE70hTs5tn/QIDAQAB +o2MwYTAdBgNVHQ4EFgQUiUCSKpRUaRAvTTLnm2U2t/C8ZNUwHwYDVR0jBBgwFoAU +iUCSKpRUaRAvTTLnm2U2t/C8ZNUwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8E +BAMCAuQwDQYJKoZIhvcNAQELBQADggEBAFYU69yV334eE2i93VyIs/sXpvuX7ZGd +EXn3SwQ+hlo4Bm2Diabs6Z/4AC0CKyA8vzTJ7Hp7qb77/cjlno25/uR76vUJQEp2 +LSWWeN80Mzzn3tOLjVd5wew5tcGZ97j/4aaDWSg/6geRfo4SuMHkahFe3V8JzE1O +vtpIvkb7q+K6B0GR/IIr4bub6dAKsVQVIQozUmmRsQU7lmQXurdkq9u1XLZKLF6J +A2j1ORzFpCMFfvXW3yACTUbmGKvdTWoEnhSaU45hJ9KA9+SYS3xR/CGgjHRSvJRV +O2D83nPDnIk8dN5PW0NWpyQvmotsjv89kBrSanL8yMoD8FnClJnMSSQ= +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDQjCCAiqgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MR4wHAYDVQQDDBVpVGV4dFRlc3RJbnRlcm1lZGlhdGUw +IBcNMDAwMTAxMDAwMDAwWhgPMjQwMDAxMDEwMDAwMDBaMDUxCzAJBgNVBAYTAkJF +MQ4wDAYDVQQKDAVpVGV4dDEWMBQGA1UEAwwNaVRleHRUZXN0U2lnbjCCASIwDQYJ +KoZIhvcNAQEBBQADggEPADCCAQoCggEBALMHHzTZo1BOQkZzEZl2Q3leNfBH20Yf +O4R0l0ZBWbnpg/099ON4I8ItO0f24Wq0gs//+1adlJqeUMeUVxQ0fpu0cHQOc9h7 +CWJLnPAJjEvItZ5WXW4l8/ppo1bo4WLB1hToF42NfHgh7Laoj2gqVLWXS6Ngd8ch +VxITaxfKA9PG56dje+PlJnTNi+ayudB/O57dhoaAu+sbxBhog/7zRAV87OsH9zxc +Nuw+3ZzHhss5Lpn6F+/WDcHPyXsT7QkX6rvbRvxUOpcysXtCH3v5+ZRKyUqRPlI6 +3/hyMMZBDqYtFDHiawk587hbMp2swHF6z56d10Za22Vq9lxiX4MdftsCAwEAAaNS +MFAwHQYDVR0OBBYEFFVqj/1gRbt6YJdo1/zMvcyOmY1cMB8GA1UdIwQYMBaAFIlA +kiqUVGkQL00y55tlNrfwvGTVMA4GA1UdDwEB/wQEAwIGwDANBgkqhkiG9w0BAQsF +AAOCAQEAMsIeJp6AHJwChOEddcGu5dD/Q4R6l7dMIe3Q8g8vDVz94572jmvHIOa5 +Q/xJALRFn5rG1oC06q6Gy4ffbUm5S1dNBXdmwyfNzAa5yAwXraIWkXLPM5zFUueB +qu2ekfPhHq0NjCqhVCCYkhngaf+mqeuw8usML6mMf8o0aC6TlQu7GXm/6Z4SSKmY +wDyM4iSVR3fZHb3R/VBP7+GNKsamapZPThdxueWnm6o2vsMKSfgGHRV/41BrUqb7 +t5SXDihXCImTpUr89EL7kix42Q/BFQ60hO3LYsKn4w8gjUQffQdlB2zR6cQJx2eK +9jrkP1+J6xcuWHHrn2l9YXw6rI7r0g== +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/crl-issuer.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/crl-issuer.cert.pem new file mode 100644 index 0000000000..956cf849d3 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/crl-issuer.cert.pem @@ -0,0 +1,21 @@ +-----BEGIN CERTIFICATE----- +MIIDijCCAnKgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwOjELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRswGQYDVQQDDBJpVGV4dE90aGVyVGVzdFJvb3QwIBcN +MDAwMTAxMDAwMDAwWhgPMjQ1MDAxMDEwMDAwMDBaMDoxCzAJBgNVBAYTAkJFMQ4w +DAYDVQQKDAVpVGV4dDEbMBkGA1UEAwwSaVRleHRUZXN0Q3JsSXNzdWVyMIIBIjAN +BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwnsONfztmnDdLJKbWd8sE/2txomx +72HBnrBM3G2bLpGfcvAFm9n/F0WLf1dPDYY94JAFKsBGG0Enh4eBJ753ZHgug/qw +DIiF5DnRH57e2EtoJWwXjeSm5KLIsaWcUsUGHJDfS8SfWDqOIDCp+qm2mv1M98po +KsIo4lRHyM4XDL5ERGUAYklA0h5noHP1V1JnCQ0/4Z+j4dX0tfTnsxp4wA+Cu8Am +sfL+UP3LTu7Soo3rbHMtn8yf12j7eohMRTX71eRf1fR1Nes0wA72RPe6RHpd1kiX +yW8P/Y+BNNpqujnW/R6LcjsVlc2iSPK4XonwBExXGp44yVVQjEt4G/uPrQIDAQAB +o4GXMIGUMB0GA1UdDgQWBBQSbqEw8HXXDUnva1e6YGF7DBbGdTAfBgNVHSMEGDAW +gBSJQJIqlFRpEC9NMuebZTa38Lxk1TAOBgNVHQ8BAf8EBAMCAcIwQgYDVR0fBDsw +OTA3oDWgM4YxaHR0cDovL2xvY2FsaG9zdC50ZXN0L2RlZmF1bHQvY3Jscy9jcmwv +bGF0ZXN0LmNybDANBgkqhkiG9w0BAQsFAAOCAQEAY6Ql0oP20FsZrtKyLVFYJSkL +c3R4mTRHJ5JbrgtPSLkLDxN3QGssgwmhZUyf8TvaCYVBomedFvOVd3xizmQPcAkD +yDeX7XTvkrg9aSaGyjtKcOduk8eVHyPvAnFZ4eJ7m0vYJThLeVlupRYKnMcVR9AA +HMxKk+YTTaTr6o2zWE63vbzkdAvJTYuVzfDw2Qo+6IeAGL3jD9ipa6+krN/h6z8k +EPun+ndDEijo9TcPv+pPT+DHcXiWcLCQFi7611h4ErvFtUJoDl3xoTMsgqMKRzJJ +46HaLTKqkLikI/s4bKZ23brDHUYzpFCHs5WkQpRfdq6jHek9lBHNRK+tp66s6w== +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/intermediate.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/intermediate.cert.pem new file mode 100644 index 0000000000..ca4cf7ba9c --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/intermediate.cert.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDQjCCAiqgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA9MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxHjAcBgNVBAMMFWlUZXh0VGVzdEludGVybWVkaWF0ZTCCASIwDQYJ +KoZIhvcNAQEBBQADggEPADCCAQoCggEBAJ6M9OSQgx20Fw14rYFeM6HQuQxBD276 +e6kXMpmdsbbkvExq5mrAWPvFGYHCmRAtH7pGm1pL91Zlgh1CbUPzwSa/Lfp9FeAX +83G7OJn0sY3kJRthtj5B0dGinXSIFCIb6gx9ICzoVpY9Ljvl4tyBr0dkGmED3MBx +SFltOMPplDhYwFekL7woNXMFIAxMnDWuS7dZ7xEpLAwNfH9D92I4lzSrQ9TrxwDP +dW2gWGvi2eu77W4YqFQgydgbKmFHAzDUTA01LNmKZkASBcLUoiLnLBMmVYgDMH4f +o4oj+2/J/OZNuGv5DK9dRCryAhnY3f8/9b8JzoPeRCmgRO9IU7ObZ/0CAwEAAaNS +MFAwHQYDVR0OBBYEFIlAkiqUVGkQL00y55tlNrfwvGTVMB8GA1UdIwQYMBaAFHQy +VMXAXOiryY9W6wOMgScvlq+rMA4GA1UdDwEB/wQEAwIB5jANBgkqhkiG9w0BAQsF +AAOCAQEAMoIJ86nzczzR41l5EFHlxGvUEQY/w7BJ42LICN3F12WPmJ+A3i/GAJSQ +14W+Jy8CXEhEFZF3R45vuOAGhOkF7igtbXeeVXunM3rmi8XIlpGjqbBZxC5w1Fd8 +IPOTArrzcF8agwthRzKOEpFSklmpUDT4MYZkdzR7TVM6TkdL+ModYFrhf9/+OFGb +qHzKUPVv+dvNaKn6JvKfQ311MKG3fLU7vyKEUNoolAnLMy3VETsnhMTk6Wa5rfzJ +eq2sdBiLxgwC3xhYk33Cla0X3hsr++Yqb8BX1ztKaRxu0PSi+KKJ9kvXAxRkFlwh +Xa7iIRXelUhftWRF/4VgDsDhWx+eDQ== +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/otherca.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/otherca.cert.pem new file mode 100644 index 0000000000..046922df36 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/otherca.cert.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDVTCCAj2gAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwOjELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRswGQYDVQQDDBJpVGV4dE90aGVyVGVzdFJvb3QwIBcN +MDAwMTAxMDAwMDAwWhgPMjUwMDAxMDEwMDAwMDBaMDoxCzAJBgNVBAYTAkJFMQ4w +DAYDVQQKDAVpVGV4dDEbMBkGA1UEAwwSaVRleHRPdGhlclRlc3RSb290MIIBIjAN +BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnoz05JCDHbQXDXitgV4zodC5DEEP +bvp7qRcymZ2xtuS8TGrmasBY+8UZgcKZEC0fukabWkv3VmWCHUJtQ/PBJr8t+n0V +4Bfzcbs4mfSxjeQlG2G2PkHR0aKddIgUIhvqDH0gLOhWlj0uO+Xi3IGvR2QaYQPc +wHFIWW04w+mUOFjAV6QvvCg1cwUgDEycNa5Lt1nvESksDA18f0P3YjiXNKtD1OvH +AM91baBYa+LZ67vtbhioVCDJ2BsqYUcDMNRMDTUs2YpmQBIFwtSiIucsEyZViAMw +fh+jiiP7b8n85k24a/kMr11EKvICGdjd/z/1vwnOg95EKaBE70hTs5tn/QIDAQAB +o2MwYTAdBgNVHQ4EFgQUiUCSKpRUaRAvTTLnm2U2t/C8ZNUwHwYDVR0jBBgwFoAU +iUCSKpRUaRAvTTLnm2U2t/C8ZNUwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8E +BAMCAuQwDQYJKoZIhvcNAQELBQADggEBAFYU69yV334eE2i93VyIs/sXpvuX7ZGd +EXn3SwQ+hlo4Bm2Diabs6Z/4AC0CKyA8vzTJ7Hp7qb77/cjlno25/uR76vUJQEp2 +LSWWeN80Mzzn3tOLjVd5wew5tcGZ97j/4aaDWSg/6geRfo4SuMHkahFe3V8JzE1O +vtpIvkb7q+K6B0GR/IIr4bub6dAKsVQVIQozUmmRsQU7lmQXurdkq9u1XLZKLF6J +A2j1ORzFpCMFfvXW3yACTUbmGKvdTWoEnhSaU45hJ9KA9+SYS3xR/CGgjHRSvJRV +O2D83nPDnIk8dN5PW0NWpyQvmotsjv89kBrSanL8yMoD8FnClJnMSSQ= +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/sign.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/sign.cert.pem new file mode 100644 index 0000000000..bfcfbf0242 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/sign.cert.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDQjCCAiqgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MR4wHAYDVQQDDBVpVGV4dFRlc3RJbnRlcm1lZGlhdGUw +IBcNMDAwMTAxMDAwMDAwWhgPMjQwMDAxMDEwMDAwMDBaMDUxCzAJBgNVBAYTAkJF +MQ4wDAYDVQQKDAVpVGV4dDEWMBQGA1UEAwwNaVRleHRUZXN0U2lnbjCCASIwDQYJ +KoZIhvcNAQEBBQADggEPADCCAQoCggEBALMHHzTZo1BOQkZzEZl2Q3leNfBH20Yf +O4R0l0ZBWbnpg/099ON4I8ItO0f24Wq0gs//+1adlJqeUMeUVxQ0fpu0cHQOc9h7 +CWJLnPAJjEvItZ5WXW4l8/ppo1bo4WLB1hToF42NfHgh7Laoj2gqVLWXS6Ngd8ch +VxITaxfKA9PG56dje+PlJnTNi+ayudB/O57dhoaAu+sbxBhog/7zRAV87OsH9zxc +Nuw+3ZzHhss5Lpn6F+/WDcHPyXsT7QkX6rvbRvxUOpcysXtCH3v5+ZRKyUqRPlI6 +3/hyMMZBDqYtFDHiawk587hbMp2swHF6z56d10Za22Vq9lxiX4MdftsCAwEAAaNS +MFAwHQYDVR0OBBYEFFVqj/1gRbt6YJdo1/zMvcyOmY1cMB8GA1UdIwQYMBaAFIlA +kiqUVGkQL00y55tlNrfwvGTVMA4GA1UdDwEB/wQEAwIGwDANBgkqhkiG9w0BAQsF +AAOCAQEAMsIeJp6AHJwChOEddcGu5dD/Q4R6l7dMIe3Q8g8vDVz94572jmvHIOa5 +Q/xJALRFn5rG1oC06q6Gy4ffbUm5S1dNBXdmwyfNzAa5yAwXraIWkXLPM5zFUueB +qu2ekfPhHq0NjCqhVCCYkhngaf+mqeuw8usML6mMf8o0aC6TlQu7GXm/6Z4SSKmY +wDyM4iSVR3fZHb3R/VBP7+GNKsamapZPThdxueWnm6o2vsMKSfgGHRV/41BrUqb7 +t5SXDihXCImTpUr89EL7kix42Q/BFQ60hO3LYsKn4w8gjUQffQdlB2zR6cQJx2eK +9jrkP1+J6xcuWHHrn2l9YXw6rI7r0g== +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate.yml b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate.yml similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate.yml rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate.yml diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/ca.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/ca.cert.pem new file mode 100644 index 0000000000..efb7717302 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/ca.cert.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDSzCCAjOgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI1MDAwMTAxMDAwMDAwWjA1MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxFjAUBgNVBAMMDWlUZXh0VGVzdFJvb3QwggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQDYxUs+SgZkRkOhOfddCnPeuE1QP2kAm6gAsg4qjNzr +rZpZvwziyWaz6bXXq8fATjXEAdypAiWL/BDZscdCM/M11jds9mMv7dMvCtLns6Oe +4GbChYxxloN2rVxElFPK2siKBaEeWyItr2Ms0P+hSR5uHjFt+krzl2zv828fyEnH +fPvln42SAcuCKsLmfjtutus5jFKBFF8oiqDFlI2eXYggKV7JELttgPLobv2ZyFa5 +nXo/xbtzlPb8AvV3/mxpX4prFhBXupJXuCwmqmzVRqGbwKSz/Bewb/4aJGSpg32x +yIWeXTld58f+Jntfes8xHwK0aJB/Tm2WrH+RWoV+TN/pAgMBAAGjYzBhMB0GA1Ud +DgQWBBR0MlTFwFzoq8mPVusDjIEnL5avqzAfBgNVHSMEGDAWgBR0MlTFwFzoq8mP +VusDjIEnL5avqzAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIC5DANBgkq +hkiG9w0BAQsFAAOCAQEAK2dbxbQ7jEdtqvnMpKOZsB55PDO5OZ2hPYilT5ZVZNt1 +jdE94HdCBHED3upmOeBH+XtsK/MLk+eYICM5SZwWVCBY0aQQR0URyTsX4SA/12A5 +VhrnP6bqy4b+3mO3J9s0go59cZOtSkxQ7191teEQMsDeh8GxXGLW/7Tf4x6v7U34 +B7UghMhUD2bHJ7U8MOqto9fVar/9S93tc9vRtYOXZbfRwjFKOYD4IFm7cH3VnrX7 +od3KUEKGKhQ2ZaqrtnW19xNTbdRcMT3+8QSai9DLV0kGGSSY09AHDO3WvxkAs9ZI +cIsMM/n+mLK0Km9fh5uE3k6NmiN3GV+QMyjbmFnVNg== +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/chain.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/chain.pem new file mode 100644 index 0000000000..2965925da3 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/chain.pem @@ -0,0 +1,81 @@ +-----BEGIN CERTIFICATE----- +MIIDSzCCAjOgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI1MDAwMTAxMDAwMDAwWjA1MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxFjAUBgNVBAMMDWlUZXh0VGVzdFJvb3QwggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQDYxUs+SgZkRkOhOfddCnPeuE1QP2kAm6gAsg4qjNzr +rZpZvwziyWaz6bXXq8fATjXEAdypAiWL/BDZscdCM/M11jds9mMv7dMvCtLns6Oe +4GbChYxxloN2rVxElFPK2siKBaEeWyItr2Ms0P+hSR5uHjFt+krzl2zv828fyEnH +fPvln42SAcuCKsLmfjtutus5jFKBFF8oiqDFlI2eXYggKV7JELttgPLobv2ZyFa5 +nXo/xbtzlPb8AvV3/mxpX4prFhBXupJXuCwmqmzVRqGbwKSz/Bewb/4aJGSpg32x +yIWeXTld58f+Jntfes8xHwK0aJB/Tm2WrH+RWoV+TN/pAgMBAAGjYzBhMB0GA1Ud +DgQWBBR0MlTFwFzoq8mPVusDjIEnL5avqzAfBgNVHSMEGDAWgBR0MlTFwFzoq8mP +VusDjIEnL5avqzAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIC5DANBgkq +hkiG9w0BAQsFAAOCAQEAK2dbxbQ7jEdtqvnMpKOZsB55PDO5OZ2hPYilT5ZVZNt1 +jdE94HdCBHED3upmOeBH+XtsK/MLk+eYICM5SZwWVCBY0aQQR0URyTsX4SA/12A5 +VhrnP6bqy4b+3mO3J9s0go59cZOtSkxQ7191teEQMsDeh8GxXGLW/7Tf4x6v7U34 +B7UghMhUD2bHJ7U8MOqto9fVar/9S93tc9vRtYOXZbfRwjFKOYD4IFm7cH3VnrX7 +od3KUEKGKhQ2ZaqrtnW19xNTbdRcMT3+8QSai9DLV0kGGSSY09AHDO3WvxkAs9ZI +cIsMM/n+mLK0Km9fh5uE3k6NmiN3GV+QMyjbmFnVNg== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDiTCCAnGgAwIBAgICEAIwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA6MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxGzAZBgNVBAMMEmlUZXh0VGVzdENybElzc3VlcjCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBAMJ7DjX87Zpw3SySm1nfLBP9rcaJse9hwZ6w +TNxtmy6Rn3LwBZvZ/xdFi39XTw2GPeCQBSrARhtBJ4eHgSe+d2R4LoP6sAyIheQ5 +0R+e3thLaCVsF43kpuSiyLGlnFLFBhyQ30vEn1g6jiAwqfqptpr9TPfKaCrCKOJU +R8jOFwy+RERlAGJJQNIeZ6Bz9VdSZwkNP+Gfo+HV9LX057MaeMAPgrvAJrHy/lD9 +y07u0qKN62xzLZ/Mn9do+3qITEU1+9XkX9X0dTXrNMAO9kT3ukR6XdZIl8lvD/2P +gTTaaro51v0ei3I7FZXNokjyuF6J8ARMVxqeOMlVUIxLeBv7j60CAwEAAaOBmzCB +mDAdBgNVHQ4EFgQUEm6hMPB11w1J72tXumBhewwWxnUwHwYDVR0jBBgwFoAUdDJU +xcBc6KvJj1brA4yBJy+Wr6swDgYDVR0PAQH/BAQDAgHCMEYGA1UdHwQ/MD0wO6A5 +oDeGNWh0dHA6Ly9sb2NhbGhvc3QudGVzdC9kZWZhdWx0L2NybHMvZGVmYXVsdC9s +YXRlc3QuY3JsMA0GCSqGSIb3DQEBCwUAA4IBAQCmoFeEZPbeDx/k45qhsk34MGkV +2mDEhE29G9qzy1FSUfQFJO0LI5nWNUyjLiYKox53MZ5+ltL8Oe5wB0r2EnepOK+U +VHNrqOL9f/weszwH5uyZLyu5+NhzZm08U9t6hxebwF6TajP8eob5PZ1dRZSSShQF +SU5mSlgBbaZGiXdvUnQhoowtmYOGnbUYrYavrQIAuTZ0A3nL0UaVlFljgecOYR2M +ovxHTO08DkrFyD22tkbGZOpLXP+B3BwhUwlhJPIl84/BzdYZCav/llrMr1CztzgW +Ox29pB8ayAXDbY7Uen9wD9fUdIXmOiDkUHsEBk46Utd8Ril628Ev4I2lhPpd +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDQjCCAiqgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA9MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxHjAcBgNVBAMMFWlUZXh0VGVzdEludGVybWVkaWF0ZTCCASIwDQYJ +KoZIhvcNAQEBBQADggEPADCCAQoCggEBAJ6M9OSQgx20Fw14rYFeM6HQuQxBD276 +e6kXMpmdsbbkvExq5mrAWPvFGYHCmRAtH7pGm1pL91Zlgh1CbUPzwSa/Lfp9FeAX +83G7OJn0sY3kJRthtj5B0dGinXSIFCIb6gx9ICzoVpY9Ljvl4tyBr0dkGmED3MBx +SFltOMPplDhYwFekL7woNXMFIAxMnDWuS7dZ7xEpLAwNfH9D92I4lzSrQ9TrxwDP +dW2gWGvi2eu77W4YqFQgydgbKmFHAzDUTA01LNmKZkASBcLUoiLnLBMmVYgDMH4f +o4oj+2/J/OZNuGv5DK9dRCryAhnY3f8/9b8JzoPeRCmgRO9IU7ObZ/0CAwEAAaNS +MFAwHQYDVR0OBBYEFIlAkiqUVGkQL00y55tlNrfwvGTVMB8GA1UdIwQYMBaAFHQy +VMXAXOiryY9W6wOMgScvlq+rMA4GA1UdDwEB/wQEAwIB5jANBgkqhkiG9w0BAQsF +AAOCAQEAMoIJ86nzczzR41l5EFHlxGvUEQY/w7BJ42LICN3F12WPmJ+A3i/GAJSQ +14W+Jy8CXEhEFZF3R45vuOAGhOkF7igtbXeeVXunM3rmi8XIlpGjqbBZxC5w1Fd8 +IPOTArrzcF8agwthRzKOEpFSklmpUDT4MYZkdzR7TVM6TkdL+ModYFrhf9/+OFGb +qHzKUPVv+dvNaKn6JvKfQ311MKG3fLU7vyKEUNoolAnLMy3VETsnhMTk6Wa5rfzJ +eq2sdBiLxgwC3xhYk33Cla0X3hsr++Yqb8BX1ztKaRxu0PSi+KKJ9kvXAxRkFlwh +Xa7iIRXelUhftWRF/4VgDsDhWx+eDQ== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDQjCCAiqgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MR4wHAYDVQQDDBVpVGV4dFRlc3RJbnRlcm1lZGlhdGUw +IBcNMDAwMTAxMDAwMDAwWhgPMjQwMDAxMDEwMDAwMDBaMDUxCzAJBgNVBAYTAkJF +MQ4wDAYDVQQKDAVpVGV4dDEWMBQGA1UEAwwNaVRleHRUZXN0U2lnbjCCASIwDQYJ +KoZIhvcNAQEBBQADggEPADCCAQoCggEBALMHHzTZo1BOQkZzEZl2Q3leNfBH20Yf +O4R0l0ZBWbnpg/099ON4I8ItO0f24Wq0gs//+1adlJqeUMeUVxQ0fpu0cHQOc9h7 +CWJLnPAJjEvItZ5WXW4l8/ppo1bo4WLB1hToF42NfHgh7Laoj2gqVLWXS6Ngd8ch +VxITaxfKA9PG56dje+PlJnTNi+ayudB/O57dhoaAu+sbxBhog/7zRAV87OsH9zxc +Nuw+3ZzHhss5Lpn6F+/WDcHPyXsT7QkX6rvbRvxUOpcysXtCH3v5+ZRKyUqRPlI6 +3/hyMMZBDqYtFDHiawk587hbMp2swHF6z56d10Za22Vq9lxiX4MdftsCAwEAAaNS +MFAwHQYDVR0OBBYEFFVqj/1gRbt6YJdo1/zMvcyOmY1cMB8GA1UdIwQYMBaAFIlA +kiqUVGkQL00y55tlNrfwvGTVMA4GA1UdDwEB/wQEAwIGwDANBgkqhkiG9w0BAQsF +AAOCAQEAMsIeJp6AHJwChOEddcGu5dD/Q4R6l7dMIe3Q8g8vDVz94572jmvHIOa5 +Q/xJALRFn5rG1oC06q6Gy4ffbUm5S1dNBXdmwyfNzAa5yAwXraIWkXLPM5zFUueB +qu2ekfPhHq0NjCqhVCCYkhngaf+mqeuw8usML6mMf8o0aC6TlQu7GXm/6Z4SSKmY +wDyM4iSVR3fZHb3R/VBP7+GNKsamapZPThdxueWnm6o2vsMKSfgGHRV/41BrUqb7 +t5SXDihXCImTpUr89EL7kix42Q/BFQ60hO3LYsKn4w8gjUQffQdlB2zR6cQJx2eK +9jrkP1+J6xcuWHHrn2l9YXw6rI7r0g== +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/crl-issuer.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/crl-issuer.cert.pem new file mode 100644 index 0000000000..f29734904d --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/crl-issuer.cert.pem @@ -0,0 +1,21 @@ +-----BEGIN CERTIFICATE----- +MIIDiTCCAnGgAwIBAgICEAIwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA6MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxGzAZBgNVBAMMEmlUZXh0VGVzdENybElzc3VlcjCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBAMJ7DjX87Zpw3SySm1nfLBP9rcaJse9hwZ6w +TNxtmy6Rn3LwBZvZ/xdFi39XTw2GPeCQBSrARhtBJ4eHgSe+d2R4LoP6sAyIheQ5 +0R+e3thLaCVsF43kpuSiyLGlnFLFBhyQ30vEn1g6jiAwqfqptpr9TPfKaCrCKOJU +R8jOFwy+RERlAGJJQNIeZ6Bz9VdSZwkNP+Gfo+HV9LX057MaeMAPgrvAJrHy/lD9 +y07u0qKN62xzLZ/Mn9do+3qITEU1+9XkX9X0dTXrNMAO9kT3ukR6XdZIl8lvD/2P +gTTaaro51v0ei3I7FZXNokjyuF6J8ARMVxqeOMlVUIxLeBv7j60CAwEAAaOBmzCB +mDAdBgNVHQ4EFgQUEm6hMPB11w1J72tXumBhewwWxnUwHwYDVR0jBBgwFoAUdDJU +xcBc6KvJj1brA4yBJy+Wr6swDgYDVR0PAQH/BAQDAgHCMEYGA1UdHwQ/MD0wO6A5 +oDeGNWh0dHA6Ly9sb2NhbGhvc3QudGVzdC9kZWZhdWx0L2NybHMvZGVmYXVsdC9s +YXRlc3QuY3JsMA0GCSqGSIb3DQEBCwUAA4IBAQCmoFeEZPbeDx/k45qhsk34MGkV +2mDEhE29G9qzy1FSUfQFJO0LI5nWNUyjLiYKox53MZ5+ltL8Oe5wB0r2EnepOK+U +VHNrqOL9f/weszwH5uyZLyu5+NhzZm08U9t6hxebwF6TajP8eob5PZ1dRZSSShQF +SU5mSlgBbaZGiXdvUnQhoowtmYOGnbUYrYavrQIAuTZ0A3nL0UaVlFljgecOYR2M +ovxHTO08DkrFyD22tkbGZOpLXP+B3BwhUwlhJPIl84/BzdYZCav/llrMr1CztzgW +Ox29pB8ayAXDbY7Uen9wD9fUdIXmOiDkUHsEBk46Utd8Ril628Ev4I2lhPpd +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/intermediate.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/intermediate.cert.pem new file mode 100644 index 0000000000..ca4cf7ba9c --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/intermediate.cert.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDQjCCAiqgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA9MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxHjAcBgNVBAMMFWlUZXh0VGVzdEludGVybWVkaWF0ZTCCASIwDQYJ +KoZIhvcNAQEBBQADggEPADCCAQoCggEBAJ6M9OSQgx20Fw14rYFeM6HQuQxBD276 +e6kXMpmdsbbkvExq5mrAWPvFGYHCmRAtH7pGm1pL91Zlgh1CbUPzwSa/Lfp9FeAX +83G7OJn0sY3kJRthtj5B0dGinXSIFCIb6gx9ICzoVpY9Ljvl4tyBr0dkGmED3MBx +SFltOMPplDhYwFekL7woNXMFIAxMnDWuS7dZ7xEpLAwNfH9D92I4lzSrQ9TrxwDP +dW2gWGvi2eu77W4YqFQgydgbKmFHAzDUTA01LNmKZkASBcLUoiLnLBMmVYgDMH4f +o4oj+2/J/OZNuGv5DK9dRCryAhnY3f8/9b8JzoPeRCmgRO9IU7ObZ/0CAwEAAaNS +MFAwHQYDVR0OBBYEFIlAkiqUVGkQL00y55tlNrfwvGTVMB8GA1UdIwQYMBaAFHQy +VMXAXOiryY9W6wOMgScvlq+rMA4GA1UdDwEB/wQEAwIB5jANBgkqhkiG9w0BAQsF +AAOCAQEAMoIJ86nzczzR41l5EFHlxGvUEQY/w7BJ42LICN3F12WPmJ+A3i/GAJSQ +14W+Jy8CXEhEFZF3R45vuOAGhOkF7igtbXeeVXunM3rmi8XIlpGjqbBZxC5w1Fd8 +IPOTArrzcF8agwthRzKOEpFSklmpUDT4MYZkdzR7TVM6TkdL+ModYFrhf9/+OFGb +qHzKUPVv+dvNaKn6JvKfQ311MKG3fLU7vyKEUNoolAnLMy3VETsnhMTk6Wa5rfzJ +eq2sdBiLxgwC3xhYk33Cla0X3hsr++Yqb8BX1ztKaRxu0PSi+KKJ9kvXAxRkFlwh +Xa7iIRXelUhftWRF/4VgDsDhWx+eDQ== +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/sign.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/sign.cert.pem new file mode 100644 index 0000000000..bfcfbf0242 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/sign.cert.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDQjCCAiqgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MR4wHAYDVQQDDBVpVGV4dFRlc3RJbnRlcm1lZGlhdGUw +IBcNMDAwMTAxMDAwMDAwWhgPMjQwMDAxMDEwMDAwMDBaMDUxCzAJBgNVBAYTAkJF +MQ4wDAYDVQQKDAVpVGV4dDEWMBQGA1UEAwwNaVRleHRUZXN0U2lnbjCCASIwDQYJ +KoZIhvcNAQEBBQADggEPADCCAQoCggEBALMHHzTZo1BOQkZzEZl2Q3leNfBH20Yf +O4R0l0ZBWbnpg/099ON4I8ItO0f24Wq0gs//+1adlJqeUMeUVxQ0fpu0cHQOc9h7 +CWJLnPAJjEvItZ5WXW4l8/ppo1bo4WLB1hToF42NfHgh7Laoj2gqVLWXS6Ngd8ch +VxITaxfKA9PG56dje+PlJnTNi+ayudB/O57dhoaAu+sbxBhog/7zRAV87OsH9zxc +Nuw+3ZzHhss5Lpn6F+/WDcHPyXsT7QkX6rvbRvxUOpcysXtCH3v5+ZRKyUqRPlI6 +3/hyMMZBDqYtFDHiawk587hbMp2swHF6z56d10Za22Vq9lxiX4MdftsCAwEAAaNS +MFAwHQYDVR0OBBYEFFVqj/1gRbt6YJdo1/zMvcyOmY1cMB8GA1UdIwQYMBaAFIlA +kiqUVGkQL00y55tlNrfwvGTVMA4GA1UdDwEB/wQEAwIGwDANBgkqhkiG9w0BAQsF +AAOCAQEAMsIeJp6AHJwChOEddcGu5dD/Q4R6l7dMIe3Q8g8vDVz94572jmvHIOa5 +Q/xJALRFn5rG1oC06q6Gy4ffbUm5S1dNBXdmwyfNzAa5yAwXraIWkXLPM5zFUueB +qu2ekfPhHq0NjCqhVCCYkhngaf+mqeuw8usML6mMf8o0aC6TlQu7GXm/6Z4SSKmY +wDyM4iSVR3fZHb3R/VBP7+GNKsamapZPThdxueWnm6o2vsMKSfgGHRV/41BrUqb7 +t5SXDihXCImTpUr89EL7kix42Q/BFQ60hO3LYsKn4w8gjUQffQdlB2zR6cQJx2eK +9jrkP1+J6xcuWHHrn2l9YXw6rI7r0g== +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlSignerInValidatedChain.yml b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlSignerInValidatedChain.yml new file mode 100644 index 0000000000..141ebe7616 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlSignerInValidatedChain.yml @@ -0,0 +1,109 @@ +external-url-prefix: "http://localhost.test" +keysets: + testkeys: + keys: + ca: + path: keys/root_key.pem + password: testpassphrase + intermediate: + path: keys/im_key.pem + password: testpassphrase + intermediate2: + path: keys/im2_key.pem + password: testpassphrase + sign: + path: keys/sign-key.pem + password: testpassphrase + crl-issuer: + path: keys/crl-key.pem + password: testpassphrase + +pki-architectures: + default: + keyset: testkeys + entity-defaults: + country-name: BE + organization-name: iText + entities: + ca: + common-name: iTextTestRoot + intermediate: + common-name: iTextTestIntermediate + intermediate2: + common-name: iTextTestIntermediate2 + sign: + common-name: iTextTestSign + crl-issuer: + common-name: iTextTestCrlIssuer + certs: + ca: + subject: ca + issuer: ca + validity: + valid-from: "2000-01-01T00:00:00+0000" + valid-to: "2500-01-01T00:00:00+0000" + extensions: + - id: basic_constraints + critical: true + value: + ca: true + - id: key_usage + critical: true + smart-value: + schema: key-usage + params: [digital_signature, non_repudiation, key_encipherment, key_cert_sign] + intermediate: + issuer: ca + validity: + valid-from: "2000-01-01T00:00:00+0000" + valid-to: "2450-01-01T00:00:00+0000" + extensions: + - id: key_usage + critical: true + smart-value: + schema: key-usage + params: [digital_signature, non_repudiation, key_encipherment, key_cert_sign, crl_sign] + intermediate2: + issuer: intermediate + validity: + valid-from: "2000-01-01T00:00:00+0000" + valid-to: "2450-01-01T00:00:00+0000" + extensions: + - id: key_usage + critical: true + smart-value: + schema: key-usage + params: [ digital_signature, non_repudiation, key_encipherment, key_cert_sign, crl_sign ] + sign: + issuer: intermediate2 + validity: + valid-from: "2000-01-01T00:00:00+0000" + valid-to: "2400-01-01T00:00:00+0000" + extensions: + - id: key_usage + critical: true + smart-value: + schema: key-usage + params: [digital_signature, non_repudiation] + crl-issuer: + issuer: intermediate + validity: + valid-from: "2000-01-01T00:00:00+0000" + valid-to: "2450-01-01T00:00:00+0000" + extensions: + - id: key_usage + critical: true + smart-value: + schema: key-usage + params: [ digital_signature, non_repudiation, crl_sign] + - id: crl_distribution_points + smart-value: + schema: crl-dist-url + params: + crl-repo-names: [crl] + services: + crl-repo: + crl: + for-issuer: crl-issuer + signing-key: crl-issuer + simulated-update-schedule: "P90D" \ No newline at end of file diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlSignerInValidatedChain/ca.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlSignerInValidatedChain/ca.cert.pem new file mode 100644 index 0000000000..efb7717302 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlSignerInValidatedChain/ca.cert.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDSzCCAjOgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI1MDAwMTAxMDAwMDAwWjA1MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxFjAUBgNVBAMMDWlUZXh0VGVzdFJvb3QwggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQDYxUs+SgZkRkOhOfddCnPeuE1QP2kAm6gAsg4qjNzr +rZpZvwziyWaz6bXXq8fATjXEAdypAiWL/BDZscdCM/M11jds9mMv7dMvCtLns6Oe +4GbChYxxloN2rVxElFPK2siKBaEeWyItr2Ms0P+hSR5uHjFt+krzl2zv828fyEnH +fPvln42SAcuCKsLmfjtutus5jFKBFF8oiqDFlI2eXYggKV7JELttgPLobv2ZyFa5 +nXo/xbtzlPb8AvV3/mxpX4prFhBXupJXuCwmqmzVRqGbwKSz/Bewb/4aJGSpg32x +yIWeXTld58f+Jntfes8xHwK0aJB/Tm2WrH+RWoV+TN/pAgMBAAGjYzBhMB0GA1Ud +DgQWBBR0MlTFwFzoq8mPVusDjIEnL5avqzAfBgNVHSMEGDAWgBR0MlTFwFzoq8mP +VusDjIEnL5avqzAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIC5DANBgkq +hkiG9w0BAQsFAAOCAQEAK2dbxbQ7jEdtqvnMpKOZsB55PDO5OZ2hPYilT5ZVZNt1 +jdE94HdCBHED3upmOeBH+XtsK/MLk+eYICM5SZwWVCBY0aQQR0URyTsX4SA/12A5 +VhrnP6bqy4b+3mO3J9s0go59cZOtSkxQ7191teEQMsDeh8GxXGLW/7Tf4x6v7U34 +B7UghMhUD2bHJ7U8MOqto9fVar/9S93tc9vRtYOXZbfRwjFKOYD4IFm7cH3VnrX7 +od3KUEKGKhQ2ZaqrtnW19xNTbdRcMT3+8QSai9DLV0kGGSSY09AHDO3WvxkAs9ZI +cIsMM/n+mLK0Km9fh5uE3k6NmiN3GV+QMyjbmFnVNg== +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlSignerInValidatedChain/chain.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlSignerInValidatedChain/chain.pem new file mode 100644 index 0000000000..eb0c61e73a --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlSignerInValidatedChain/chain.pem @@ -0,0 +1,102 @@ +-----BEGIN CERTIFICATE----- +MIIDSzCCAjOgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI1MDAwMTAxMDAwMDAwWjA1MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxFjAUBgNVBAMMDWlUZXh0VGVzdFJvb3QwggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQDYxUs+SgZkRkOhOfddCnPeuE1QP2kAm6gAsg4qjNzr +rZpZvwziyWaz6bXXq8fATjXEAdypAiWL/BDZscdCM/M11jds9mMv7dMvCtLns6Oe +4GbChYxxloN2rVxElFPK2siKBaEeWyItr2Ms0P+hSR5uHjFt+krzl2zv828fyEnH +fPvln42SAcuCKsLmfjtutus5jFKBFF8oiqDFlI2eXYggKV7JELttgPLobv2ZyFa5 +nXo/xbtzlPb8AvV3/mxpX4prFhBXupJXuCwmqmzVRqGbwKSz/Bewb/4aJGSpg32x +yIWeXTld58f+Jntfes8xHwK0aJB/Tm2WrH+RWoV+TN/pAgMBAAGjYzBhMB0GA1Ud +DgQWBBR0MlTFwFzoq8mPVusDjIEnL5avqzAfBgNVHSMEGDAWgBR0MlTFwFzoq8mP +VusDjIEnL5avqzAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIC5DANBgkq +hkiG9w0BAQsFAAOCAQEAK2dbxbQ7jEdtqvnMpKOZsB55PDO5OZ2hPYilT5ZVZNt1 +jdE94HdCBHED3upmOeBH+XtsK/MLk+eYICM5SZwWVCBY0aQQR0URyTsX4SA/12A5 +VhrnP6bqy4b+3mO3J9s0go59cZOtSkxQ7191teEQMsDeh8GxXGLW/7Tf4x6v7U34 +B7UghMhUD2bHJ7U8MOqto9fVar/9S93tc9vRtYOXZbfRwjFKOYD4IFm7cH3VnrX7 +od3KUEKGKhQ2ZaqrtnW19xNTbdRcMT3+8QSai9DLV0kGGSSY09AHDO3WvxkAs9ZI +cIsMM/n+mLK0Km9fh5uE3k6NmiN3GV+QMyjbmFnVNg== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDjTCCAnWgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwPTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MR4wHAYDVQQDDBVpVGV4dFRlc3RJbnRlcm1lZGlhdGUw +IBcNMDAwMTAxMDAwMDAwWhgPMjQ1MDAxMDEwMDAwMDBaMDoxCzAJBgNVBAYTAkJF +MQ4wDAYDVQQKDAVpVGV4dDEbMBkGA1UEAwwSaVRleHRUZXN0Q3JsSXNzdWVyMIIB +IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwnsONfztmnDdLJKbWd8sE/2t +xomx72HBnrBM3G2bLpGfcvAFm9n/F0WLf1dPDYY94JAFKsBGG0Enh4eBJ753ZHgu +g/qwDIiF5DnRH57e2EtoJWwXjeSm5KLIsaWcUsUGHJDfS8SfWDqOIDCp+qm2mv1M +98poKsIo4lRHyM4XDL5ERGUAYklA0h5noHP1V1JnCQ0/4Z+j4dX0tfTnsxp4wA+C +u8AmsfL+UP3LTu7Soo3rbHMtn8yf12j7eohMRTX71eRf1fR1Nes0wA72RPe6RHpd +1kiXyW8P/Y+BNNpqujnW/R6LcjsVlc2iSPK4XonwBExXGp44yVVQjEt4G/uPrQID +AQABo4GXMIGUMB0GA1UdDgQWBBQSbqEw8HXXDUnva1e6YGF7DBbGdTAfBgNVHSME +GDAWgBSJQJIqlFRpEC9NMuebZTa38Lxk1TAOBgNVHQ8BAf8EBAMCAcIwQgYDVR0f +BDswOTA3oDWgM4YxaHR0cDovL2xvY2FsaG9zdC50ZXN0L2RlZmF1bHQvY3Jscy9j +cmwvbGF0ZXN0LmNybDANBgkqhkiG9w0BAQsFAAOCAQEAIei53b7VB3ZL8Axad3Jt +MjjzTp4+rGrh4RneoCEMUd04CjjcNToF3uCadAaBpi6j+eYEq/FTdebVrsdwGUvT +W+GqzYlesyv9BcbIGpla2ajw8SGBxpOOUPlZdHLkFlu9X86LXf/4acRglj02HDSf +kmvz3xmKwMLmctS6PpYVYfWUFdiBBHTnPTVm4dHQCHUiwyaSxLiShO9LaFtzQSZ4 +hfH4RD112fIFtW0srEwTCZtrQkttkTdBYJPg6SorGjBDsQqK9bkACYfyBOt+9hQY +Kcb1WRX3VfnBT+l7Nwzf7X37onRrm08gUefoHHAB1lUEN63tbGYnWy0az+0UYMMn +Fw== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDQjCCAiqgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA9MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxHjAcBgNVBAMMFWlUZXh0VGVzdEludGVybWVkaWF0ZTCCASIwDQYJ +KoZIhvcNAQEBBQADggEPADCCAQoCggEBAJ6M9OSQgx20Fw14rYFeM6HQuQxBD276 +e6kXMpmdsbbkvExq5mrAWPvFGYHCmRAtH7pGm1pL91Zlgh1CbUPzwSa/Lfp9FeAX +83G7OJn0sY3kJRthtj5B0dGinXSIFCIb6gx9ICzoVpY9Ljvl4tyBr0dkGmED3MBx +SFltOMPplDhYwFekL7woNXMFIAxMnDWuS7dZ7xEpLAwNfH9D92I4lzSrQ9TrxwDP +dW2gWGvi2eu77W4YqFQgydgbKmFHAzDUTA01LNmKZkASBcLUoiLnLBMmVYgDMH4f +o4oj+2/J/OZNuGv5DK9dRCryAhnY3f8/9b8JzoPeRCmgRO9IU7ObZ/0CAwEAAaNS +MFAwHQYDVR0OBBYEFIlAkiqUVGkQL00y55tlNrfwvGTVMB8GA1UdIwQYMBaAFHQy +VMXAXOiryY9W6wOMgScvlq+rMA4GA1UdDwEB/wQEAwIB5jANBgkqhkiG9w0BAQsF +AAOCAQEAMoIJ86nzczzR41l5EFHlxGvUEQY/w7BJ42LICN3F12WPmJ+A3i/GAJSQ +14W+Jy8CXEhEFZF3R45vuOAGhOkF7igtbXeeVXunM3rmi8XIlpGjqbBZxC5w1Fd8 +IPOTArrzcF8agwthRzKOEpFSklmpUDT4MYZkdzR7TVM6TkdL+ModYFrhf9/+OFGb +qHzKUPVv+dvNaKn6JvKfQ311MKG3fLU7vyKEUNoolAnLMy3VETsnhMTk6Wa5rfzJ +eq2sdBiLxgwC3xhYk33Cla0X3hsr++Yqb8BX1ztKaRxu0PSi+KKJ9kvXAxRkFlwh +Xa7iIRXelUhftWRF/4VgDsDhWx+eDQ== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDSzCCAjOgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MR4wHAYDVQQDDBVpVGV4dFRlc3RJbnRlcm1lZGlhdGUw +IBcNMDAwMTAxMDAwMDAwWhgPMjQ1MDAxMDEwMDAwMDBaMD4xCzAJBgNVBAYTAkJF +MQ4wDAYDVQQKDAVpVGV4dDEfMB0GA1UEAwwWaVRleHRUZXN0SW50ZXJtZWRpYXRl +MjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKN7p56CI+QpTP773pE1 +MjK9gKerROMznvSyRhyrXit89y9XbQXE4vyy136Wp3hJrNvb5oEg4np+knpRplQ/ +Z3Pypn4VsQSfN/VZHn7OsS9DUNAXpf48W8hph2/eLx8S3vs35bPdcF2PZGiy1L82 +GrEJS68lZ0iQw6KKxeGA87k1qL67uzRZq1MHHg4LSdMi5ffouGBv5oWyGQuD6AXs +aS70kKD8+Hj2Yg1lg0dM9tMGdzJ+ija4qASFo36/WouS4pcXwZUNB6kGWJJAdDbo +KzzWyaG0ygl3HtvBvrQjlERjq4PXIkDtCvA1gp0WFxNyIC/brUuaktK2V0I5uvzW +eS8CAwEAAaNSMFAwHQYDVR0OBBYEFGAHlG/vhI4aheowsOg1wfgcIpb5MB8GA1Ud +IwQYMBaAFIlAkiqUVGkQL00y55tlNrfwvGTVMA4GA1UdDwEB/wQEAwIB5jANBgkq +hkiG9w0BAQsFAAOCAQEAIiyAUyICl5tGxOkVpbdIvm7TYRGgivoUcLONpke4ypo6 +Yeh+2KmPAhIM6npUpuGIBMSsXfBVwQkWGUDHi3BMTbzO9Q5ivFx5GK68RYQryPkI +A4chJNnoxtbLJogsLpl3DxBmZc83z8RoHKbqyxOcR1NhQQXqcXz9ZxvAwfW8v6tJ +tD5IS55zBvcROB4AdH2+dVtjlHgBGniQheZ/JHI/74iXQCyiynEh3Bc54iH9qDUj +oQGY/cjDJJS6Xwqts1SCoLkpQTHO/GrAIRZwpIvTDeAVS0F16c5h+oAr4vV3iVEL +B/dPAG3gZDWO8zeOS4BF+yRYzt28zooQFNOUMUi4XQ== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDQzCCAiugAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPjELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MR8wHQYDVQQDDBZpVGV4dFRlc3RJbnRlcm1lZGlhdGUy +MCAXDTAwMDEwMTAwMDAwMFoYDzI0MDAwMTAxMDAwMDAwWjA1MQswCQYDVQQGEwJC +RTEOMAwGA1UECgwFaVRleHQxFjAUBgNVBAMMDWlUZXh0VGVzdFNpZ24wggEiMA0G +CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCzBx802aNQTkJGcxGZdkN5XjXwR9tG +HzuEdJdGQVm56YP9PfTjeCPCLTtH9uFqtILP//tWnZSanlDHlFcUNH6btHB0DnPY +ewliS5zwCYxLyLWeVl1uJfP6aaNW6OFiwdYU6BeNjXx4Iey2qI9oKlS1l0ujYHfH +IVcSE2sXygPTxuenY3vj5SZ0zYvmsrnQfzue3YaGgLvrG8QYaIP+80QFfOzrB/c8 +XDbsPt2cx4bLOS6Z+hfv1g3Bz8l7E+0JF+q720b8VDqXMrF7Qh97+fmUSslKkT5S +Ot/4cjDGQQ6mLRQx4msJOfO4WzKdrMBxes+enddGWttlavZcYl+DHX7bAgMBAAGj +UjBQMB0GA1UdDgQWBBRVao/9YEW7emCXaNf8zL3MjpmNXDAfBgNVHSMEGDAWgBRg +B5Rv74SOGoXqMLDoNcH4HCKW+TAOBgNVHQ8BAf8EBAMCBsAwDQYJKoZIhvcNAQEL +BQADggEBABuMF3tRpfmvjt96ZH0Bb8NWjB/WXUu6Pfv8lcO1PgDYsm0XLiVnN1Bl +4hhOJVL9Ceus1YB2uOqr8ukNYLuBidGtgaV3gxrT9CkqlnZHsRppNbUiKHER9hS8 +xAgja27YOM/qeyzzp6HZUfiFNsfz/oAddoDUWVPdQx1+EpQ0mlY9nAqHlFXhhoyU +H3RVA8N/DJiFHGhn/JAzUHFDorrxDHXWDOqCIZtVGOtTvNZ4KHeD9vKKtMNBlAfE +SpCPPml1gl1w70ou+GsMHaqioXfNgd6+H+y6xa+vBmjzmYenrUSA1IstNq3aHBVU ++ncyOb8+CbSUmWuYUu7HTpNWGBaGRxg= +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlSignerInValidatedChain/crl-issuer.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlSignerInValidatedChain/crl-issuer.cert.pem new file mode 100644 index 0000000000..d5d2bebf26 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlSignerInValidatedChain/crl-issuer.cert.pem @@ -0,0 +1,22 @@ +-----BEGIN CERTIFICATE----- +MIIDjTCCAnWgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwPTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MR4wHAYDVQQDDBVpVGV4dFRlc3RJbnRlcm1lZGlhdGUw +IBcNMDAwMTAxMDAwMDAwWhgPMjQ1MDAxMDEwMDAwMDBaMDoxCzAJBgNVBAYTAkJF +MQ4wDAYDVQQKDAVpVGV4dDEbMBkGA1UEAwwSaVRleHRUZXN0Q3JsSXNzdWVyMIIB +IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwnsONfztmnDdLJKbWd8sE/2t +xomx72HBnrBM3G2bLpGfcvAFm9n/F0WLf1dPDYY94JAFKsBGG0Enh4eBJ753ZHgu +g/qwDIiF5DnRH57e2EtoJWwXjeSm5KLIsaWcUsUGHJDfS8SfWDqOIDCp+qm2mv1M +98poKsIo4lRHyM4XDL5ERGUAYklA0h5noHP1V1JnCQ0/4Z+j4dX0tfTnsxp4wA+C +u8AmsfL+UP3LTu7Soo3rbHMtn8yf12j7eohMRTX71eRf1fR1Nes0wA72RPe6RHpd +1kiXyW8P/Y+BNNpqujnW/R6LcjsVlc2iSPK4XonwBExXGp44yVVQjEt4G/uPrQID +AQABo4GXMIGUMB0GA1UdDgQWBBQSbqEw8HXXDUnva1e6YGF7DBbGdTAfBgNVHSME +GDAWgBSJQJIqlFRpEC9NMuebZTa38Lxk1TAOBgNVHQ8BAf8EBAMCAcIwQgYDVR0f +BDswOTA3oDWgM4YxaHR0cDovL2xvY2FsaG9zdC50ZXN0L2RlZmF1bHQvY3Jscy9j +cmwvbGF0ZXN0LmNybDANBgkqhkiG9w0BAQsFAAOCAQEAIei53b7VB3ZL8Axad3Jt +MjjzTp4+rGrh4RneoCEMUd04CjjcNToF3uCadAaBpi6j+eYEq/FTdebVrsdwGUvT +W+GqzYlesyv9BcbIGpla2ajw8SGBxpOOUPlZdHLkFlu9X86LXf/4acRglj02HDSf +kmvz3xmKwMLmctS6PpYVYfWUFdiBBHTnPTVm4dHQCHUiwyaSxLiShO9LaFtzQSZ4 +hfH4RD112fIFtW0srEwTCZtrQkttkTdBYJPg6SorGjBDsQqK9bkACYfyBOt+9hQY +Kcb1WRX3VfnBT+l7Nwzf7X37onRrm08gUefoHHAB1lUEN63tbGYnWy0az+0UYMMn +Fw== +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlSignerInValidatedChain/intermediate.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlSignerInValidatedChain/intermediate.cert.pem new file mode 100644 index 0000000000..ca4cf7ba9c --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlSignerInValidatedChain/intermediate.cert.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDQjCCAiqgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA9MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxHjAcBgNVBAMMFWlUZXh0VGVzdEludGVybWVkaWF0ZTCCASIwDQYJ +KoZIhvcNAQEBBQADggEPADCCAQoCggEBAJ6M9OSQgx20Fw14rYFeM6HQuQxBD276 +e6kXMpmdsbbkvExq5mrAWPvFGYHCmRAtH7pGm1pL91Zlgh1CbUPzwSa/Lfp9FeAX +83G7OJn0sY3kJRthtj5B0dGinXSIFCIb6gx9ICzoVpY9Ljvl4tyBr0dkGmED3MBx +SFltOMPplDhYwFekL7woNXMFIAxMnDWuS7dZ7xEpLAwNfH9D92I4lzSrQ9TrxwDP +dW2gWGvi2eu77W4YqFQgydgbKmFHAzDUTA01LNmKZkASBcLUoiLnLBMmVYgDMH4f +o4oj+2/J/OZNuGv5DK9dRCryAhnY3f8/9b8JzoPeRCmgRO9IU7ObZ/0CAwEAAaNS +MFAwHQYDVR0OBBYEFIlAkiqUVGkQL00y55tlNrfwvGTVMB8GA1UdIwQYMBaAFHQy +VMXAXOiryY9W6wOMgScvlq+rMA4GA1UdDwEB/wQEAwIB5jANBgkqhkiG9w0BAQsF +AAOCAQEAMoIJ86nzczzR41l5EFHlxGvUEQY/w7BJ42LICN3F12WPmJ+A3i/GAJSQ +14W+Jy8CXEhEFZF3R45vuOAGhOkF7igtbXeeVXunM3rmi8XIlpGjqbBZxC5w1Fd8 +IPOTArrzcF8agwthRzKOEpFSklmpUDT4MYZkdzR7TVM6TkdL+ModYFrhf9/+OFGb +qHzKUPVv+dvNaKn6JvKfQ311MKG3fLU7vyKEUNoolAnLMy3VETsnhMTk6Wa5rfzJ +eq2sdBiLxgwC3xhYk33Cla0X3hsr++Yqb8BX1ztKaRxu0PSi+KKJ9kvXAxRkFlwh +Xa7iIRXelUhftWRF/4VgDsDhWx+eDQ== +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlSignerInValidatedChain/intermediate2.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlSignerInValidatedChain/intermediate2.cert.pem new file mode 100644 index 0000000000..713d7be544 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlSignerInValidatedChain/intermediate2.cert.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDSzCCAjOgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MR4wHAYDVQQDDBVpVGV4dFRlc3RJbnRlcm1lZGlhdGUw +IBcNMDAwMTAxMDAwMDAwWhgPMjQ1MDAxMDEwMDAwMDBaMD4xCzAJBgNVBAYTAkJF +MQ4wDAYDVQQKDAVpVGV4dDEfMB0GA1UEAwwWaVRleHRUZXN0SW50ZXJtZWRpYXRl +MjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKN7p56CI+QpTP773pE1 +MjK9gKerROMznvSyRhyrXit89y9XbQXE4vyy136Wp3hJrNvb5oEg4np+knpRplQ/ +Z3Pypn4VsQSfN/VZHn7OsS9DUNAXpf48W8hph2/eLx8S3vs35bPdcF2PZGiy1L82 +GrEJS68lZ0iQw6KKxeGA87k1qL67uzRZq1MHHg4LSdMi5ffouGBv5oWyGQuD6AXs +aS70kKD8+Hj2Yg1lg0dM9tMGdzJ+ija4qASFo36/WouS4pcXwZUNB6kGWJJAdDbo +KzzWyaG0ygl3HtvBvrQjlERjq4PXIkDtCvA1gp0WFxNyIC/brUuaktK2V0I5uvzW +eS8CAwEAAaNSMFAwHQYDVR0OBBYEFGAHlG/vhI4aheowsOg1wfgcIpb5MB8GA1Ud +IwQYMBaAFIlAkiqUVGkQL00y55tlNrfwvGTVMA4GA1UdDwEB/wQEAwIB5jANBgkq +hkiG9w0BAQsFAAOCAQEAIiyAUyICl5tGxOkVpbdIvm7TYRGgivoUcLONpke4ypo6 +Yeh+2KmPAhIM6npUpuGIBMSsXfBVwQkWGUDHi3BMTbzO9Q5ivFx5GK68RYQryPkI +A4chJNnoxtbLJogsLpl3DxBmZc83z8RoHKbqyxOcR1NhQQXqcXz9ZxvAwfW8v6tJ +tD5IS55zBvcROB4AdH2+dVtjlHgBGniQheZ/JHI/74iXQCyiynEh3Bc54iH9qDUj +oQGY/cjDJJS6Xwqts1SCoLkpQTHO/GrAIRZwpIvTDeAVS0F16c5h+oAr4vV3iVEL +B/dPAG3gZDWO8zeOS4BF+yRYzt28zooQFNOUMUi4XQ== +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlSignerInValidatedChain/sign.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlSignerInValidatedChain/sign.cert.pem new file mode 100644 index 0000000000..a6aaacc0ff --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/crlSignerInValidatedChain/sign.cert.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDQzCCAiugAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPjELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MR8wHQYDVQQDDBZpVGV4dFRlc3RJbnRlcm1lZGlhdGUy +MCAXDTAwMDEwMTAwMDAwMFoYDzI0MDAwMTAxMDAwMDAwWjA1MQswCQYDVQQGEwJC +RTEOMAwGA1UECgwFaVRleHQxFjAUBgNVBAMMDWlUZXh0VGVzdFNpZ24wggEiMA0G +CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCzBx802aNQTkJGcxGZdkN5XjXwR9tG +HzuEdJdGQVm56YP9PfTjeCPCLTtH9uFqtILP//tWnZSanlDHlFcUNH6btHB0DnPY +ewliS5zwCYxLyLWeVl1uJfP6aaNW6OFiwdYU6BeNjXx4Iey2qI9oKlS1l0ujYHfH +IVcSE2sXygPTxuenY3vj5SZ0zYvmsrnQfzue3YaGgLvrG8QYaIP+80QFfOzrB/c8 +XDbsPt2cx4bLOS6Z+hfv1g3Bz8l7E+0JF+q720b8VDqXMrF7Qh97+fmUSslKkT5S +Ot/4cjDGQQ6mLRQx4msJOfO4WzKdrMBxes+enddGWttlavZcYl+DHX7bAgMBAAGj +UjBQMB0GA1UdDgQWBBRVao/9YEW7emCXaNf8zL3MjpmNXDAfBgNVHSMEGDAWgBRg +B5Rv74SOGoXqMLDoNcH4HCKW+TAOBgNVHQ8BAf8EBAMCBsAwDQYJKoZIhvcNAQEL +BQADggEBABuMF3tRpfmvjt96ZH0Bb8NWjB/WXUu6Pfv8lcO1PgDYsm0XLiVnN1Bl +4hhOJVL9Ceus1YB2uOqr8ukNYLuBidGtgaV3gxrT9CkqlnZHsRppNbUiKHER9hS8 +xAgja27YOM/qeyzzp6HZUfiFNsfz/oAddoDUWVPdQx1+EpQ0mlY9nAqHlFXhhoyU +H3RVA8N/DJiFHGhn/JAzUHFDorrxDHXWDOqCIZtVGOtTvNZ4KHeD9vKKtMNBlAfE +SpCPPml1gl1w70ou+GsMHaqioXfNgd6+H+y6xa+vBmjzmYenrUSA1IstNq3aHBVU ++ncyOb8+CbSUmWuYUu7HTpNWGBaGRxg= +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/happyPath.yml b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/happyPath.yml similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/happyPath.yml rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/happyPath.yml diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/happyPath/ca.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/happyPath/ca.cert.pem new file mode 100644 index 0000000000..efb7717302 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/happyPath/ca.cert.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDSzCCAjOgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI1MDAwMTAxMDAwMDAwWjA1MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxFjAUBgNVBAMMDWlUZXh0VGVzdFJvb3QwggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQDYxUs+SgZkRkOhOfddCnPeuE1QP2kAm6gAsg4qjNzr +rZpZvwziyWaz6bXXq8fATjXEAdypAiWL/BDZscdCM/M11jds9mMv7dMvCtLns6Oe +4GbChYxxloN2rVxElFPK2siKBaEeWyItr2Ms0P+hSR5uHjFt+krzl2zv828fyEnH +fPvln42SAcuCKsLmfjtutus5jFKBFF8oiqDFlI2eXYggKV7JELttgPLobv2ZyFa5 +nXo/xbtzlPb8AvV3/mxpX4prFhBXupJXuCwmqmzVRqGbwKSz/Bewb/4aJGSpg32x +yIWeXTld58f+Jntfes8xHwK0aJB/Tm2WrH+RWoV+TN/pAgMBAAGjYzBhMB0GA1Ud +DgQWBBR0MlTFwFzoq8mPVusDjIEnL5avqzAfBgNVHSMEGDAWgBR0MlTFwFzoq8mP +VusDjIEnL5avqzAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIC5DANBgkq +hkiG9w0BAQsFAAOCAQEAK2dbxbQ7jEdtqvnMpKOZsB55PDO5OZ2hPYilT5ZVZNt1 +jdE94HdCBHED3upmOeBH+XtsK/MLk+eYICM5SZwWVCBY0aQQR0URyTsX4SA/12A5 +VhrnP6bqy4b+3mO3J9s0go59cZOtSkxQ7191teEQMsDeh8GxXGLW/7Tf4x6v7U34 +B7UghMhUD2bHJ7U8MOqto9fVar/9S93tc9vRtYOXZbfRwjFKOYD4IFm7cH3VnrX7 +od3KUEKGKhQ2ZaqrtnW19xNTbdRcMT3+8QSai9DLV0kGGSSY09AHDO3WvxkAs9ZI +cIsMM/n+mLK0Km9fh5uE3k6NmiN3GV+QMyjbmFnVNg== +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/happyPath/chain.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/happyPath/chain.pem new file mode 100644 index 0000000000..f444b02a80 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/happyPath/chain.pem @@ -0,0 +1,81 @@ +-----BEGIN CERTIFICATE----- +MIIDSzCCAjOgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI1MDAwMTAxMDAwMDAwWjA1MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxFjAUBgNVBAMMDWlUZXh0VGVzdFJvb3QwggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQDYxUs+SgZkRkOhOfddCnPeuE1QP2kAm6gAsg4qjNzr +rZpZvwziyWaz6bXXq8fATjXEAdypAiWL/BDZscdCM/M11jds9mMv7dMvCtLns6Oe +4GbChYxxloN2rVxElFPK2siKBaEeWyItr2Ms0P+hSR5uHjFt+krzl2zv828fyEnH +fPvln42SAcuCKsLmfjtutus5jFKBFF8oiqDFlI2eXYggKV7JELttgPLobv2ZyFa5 +nXo/xbtzlPb8AvV3/mxpX4prFhBXupJXuCwmqmzVRqGbwKSz/Bewb/4aJGSpg32x +yIWeXTld58f+Jntfes8xHwK0aJB/Tm2WrH+RWoV+TN/pAgMBAAGjYzBhMB0GA1Ud +DgQWBBR0MlTFwFzoq8mPVusDjIEnL5avqzAfBgNVHSMEGDAWgBR0MlTFwFzoq8mP +VusDjIEnL5avqzAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIC5DANBgkq +hkiG9w0BAQsFAAOCAQEAK2dbxbQ7jEdtqvnMpKOZsB55PDO5OZ2hPYilT5ZVZNt1 +jdE94HdCBHED3upmOeBH+XtsK/MLk+eYICM5SZwWVCBY0aQQR0URyTsX4SA/12A5 +VhrnP6bqy4b+3mO3J9s0go59cZOtSkxQ7191teEQMsDeh8GxXGLW/7Tf4x6v7U34 +B7UghMhUD2bHJ7U8MOqto9fVar/9S93tc9vRtYOXZbfRwjFKOYD4IFm7cH3VnrX7 +od3KUEKGKhQ2ZaqrtnW19xNTbdRcMT3+8QSai9DLV0kGGSSY09AHDO3WvxkAs9ZI +cIsMM/n+mLK0Km9fh5uE3k6NmiN3GV+QMyjbmFnVNg== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDhTCCAm2gAwIBAgICEAIwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA6MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxGzAZBgNVBAMMEmlUZXh0VGVzdENybElzc3VlcjCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBAMJ7DjX87Zpw3SySm1nfLBP9rcaJse9hwZ6w +TNxtmy6Rn3LwBZvZ/xdFi39XTw2GPeCQBSrARhtBJ4eHgSe+d2R4LoP6sAyIheQ5 +0R+e3thLaCVsF43kpuSiyLGlnFLFBhyQ30vEn1g6jiAwqfqptpr9TPfKaCrCKOJU +R8jOFwy+RERlAGJJQNIeZ6Bz9VdSZwkNP+Gfo+HV9LX057MaeMAPgrvAJrHy/lD9 +y07u0qKN62xzLZ/Mn9do+3qITEU1+9XkX9X0dTXrNMAO9kT3ukR6XdZIl8lvD/2P +gTTaaro51v0ei3I7FZXNokjyuF6J8ARMVxqeOMlVUIxLeBv7j60CAwEAAaOBlzCB +lDAdBgNVHQ4EFgQUEm6hMPB11w1J72tXumBhewwWxnUwHwYDVR0jBBgwFoAUdDJU +xcBc6KvJj1brA4yBJy+Wr6swDgYDVR0PAQH/BAQDAgHCMEIGA1UdHwQ7MDkwN6A1 +oDOGMWh0dHA6Ly9sb2NhbGhvc3QudGVzdC9kZWZhdWx0L2NybHMvY3JsL2xhdGVz +dC5jcmwwDQYJKoZIhvcNAQELBQADggEBAEg69NBvQJkOO25o1UxRoJqKb7PdwF5K +xiidxXjJQTZHVR56rWoMfg/31eDwBdc6bmSAELd2wPSs3Ov3HJJP4f31+plXB3Qb +B5pQUEc5i4IZiE0jz7Be4GLqSVNaLh9ay4o8PnpvcIZiKNukJzPhGsOzW8xrTF7R +Cc6VSjmLHG2UnEt2CBbkaWnVXV8ibENSawv4Ar2AKpcU9LLoT1F92zx/7YpUQLr1 +k/RwWxkKByV5ko001DuwiWf/BjZ67pu5WTgdHQP9KaNMahnSqrjERCTLWVipdvJ2 +o3bHCe9I0OQMVlMeesKMWPRqLiAMpz7f7q09AXlqjvZT9+FPSi6nsss= +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDQjCCAiqgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA9MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxHjAcBgNVBAMMFWlUZXh0VGVzdEludGVybWVkaWF0ZTCCASIwDQYJ +KoZIhvcNAQEBBQADggEPADCCAQoCggEBAJ6M9OSQgx20Fw14rYFeM6HQuQxBD276 +e6kXMpmdsbbkvExq5mrAWPvFGYHCmRAtH7pGm1pL91Zlgh1CbUPzwSa/Lfp9FeAX +83G7OJn0sY3kJRthtj5B0dGinXSIFCIb6gx9ICzoVpY9Ljvl4tyBr0dkGmED3MBx +SFltOMPplDhYwFekL7woNXMFIAxMnDWuS7dZ7xEpLAwNfH9D92I4lzSrQ9TrxwDP +dW2gWGvi2eu77W4YqFQgydgbKmFHAzDUTA01LNmKZkASBcLUoiLnLBMmVYgDMH4f +o4oj+2/J/OZNuGv5DK9dRCryAhnY3f8/9b8JzoPeRCmgRO9IU7ObZ/0CAwEAAaNS +MFAwHQYDVR0OBBYEFIlAkiqUVGkQL00y55tlNrfwvGTVMB8GA1UdIwQYMBaAFHQy +VMXAXOiryY9W6wOMgScvlq+rMA4GA1UdDwEB/wQEAwIB5jANBgkqhkiG9w0BAQsF +AAOCAQEAMoIJ86nzczzR41l5EFHlxGvUEQY/w7BJ42LICN3F12WPmJ+A3i/GAJSQ +14W+Jy8CXEhEFZF3R45vuOAGhOkF7igtbXeeVXunM3rmi8XIlpGjqbBZxC5w1Fd8 +IPOTArrzcF8agwthRzKOEpFSklmpUDT4MYZkdzR7TVM6TkdL+ModYFrhf9/+OFGb +qHzKUPVv+dvNaKn6JvKfQ311MKG3fLU7vyKEUNoolAnLMy3VETsnhMTk6Wa5rfzJ +eq2sdBiLxgwC3xhYk33Cla0X3hsr++Yqb8BX1ztKaRxu0PSi+KKJ9kvXAxRkFlwh +Xa7iIRXelUhftWRF/4VgDsDhWx+eDQ== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDQjCCAiqgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MR4wHAYDVQQDDBVpVGV4dFRlc3RJbnRlcm1lZGlhdGUw +IBcNMDAwMTAxMDAwMDAwWhgPMjQwMDAxMDEwMDAwMDBaMDUxCzAJBgNVBAYTAkJF +MQ4wDAYDVQQKDAVpVGV4dDEWMBQGA1UEAwwNaVRleHRUZXN0U2lnbjCCASIwDQYJ +KoZIhvcNAQEBBQADggEPADCCAQoCggEBALMHHzTZo1BOQkZzEZl2Q3leNfBH20Yf +O4R0l0ZBWbnpg/099ON4I8ItO0f24Wq0gs//+1adlJqeUMeUVxQ0fpu0cHQOc9h7 +CWJLnPAJjEvItZ5WXW4l8/ppo1bo4WLB1hToF42NfHgh7Laoj2gqVLWXS6Ngd8ch +VxITaxfKA9PG56dje+PlJnTNi+ayudB/O57dhoaAu+sbxBhog/7zRAV87OsH9zxc +Nuw+3ZzHhss5Lpn6F+/WDcHPyXsT7QkX6rvbRvxUOpcysXtCH3v5+ZRKyUqRPlI6 +3/hyMMZBDqYtFDHiawk587hbMp2swHF6z56d10Za22Vq9lxiX4MdftsCAwEAAaNS +MFAwHQYDVR0OBBYEFFVqj/1gRbt6YJdo1/zMvcyOmY1cMB8GA1UdIwQYMBaAFIlA +kiqUVGkQL00y55tlNrfwvGTVMA4GA1UdDwEB/wQEAwIGwDANBgkqhkiG9w0BAQsF +AAOCAQEAMsIeJp6AHJwChOEddcGu5dD/Q4R6l7dMIe3Q8g8vDVz94572jmvHIOa5 +Q/xJALRFn5rG1oC06q6Gy4ffbUm5S1dNBXdmwyfNzAa5yAwXraIWkXLPM5zFUueB +qu2ekfPhHq0NjCqhVCCYkhngaf+mqeuw8usML6mMf8o0aC6TlQu7GXm/6Z4SSKmY +wDyM4iSVR3fZHb3R/VBP7+GNKsamapZPThdxueWnm6o2vsMKSfgGHRV/41BrUqb7 +t5SXDihXCImTpUr89EL7kix42Q/BFQ60hO3LYsKn4w8gjUQffQdlB2zR6cQJx2eK +9jrkP1+J6xcuWHHrn2l9YXw6rI7r0g== +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/happyPath/crl-issuer.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/happyPath/crl-issuer.cert.pem new file mode 100644 index 0000000000..3656f9e733 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/happyPath/crl-issuer.cert.pem @@ -0,0 +1,21 @@ +-----BEGIN CERTIFICATE----- +MIIDhTCCAm2gAwIBAgICEAIwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA6MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxGzAZBgNVBAMMEmlUZXh0VGVzdENybElzc3VlcjCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBAMJ7DjX87Zpw3SySm1nfLBP9rcaJse9hwZ6w +TNxtmy6Rn3LwBZvZ/xdFi39XTw2GPeCQBSrARhtBJ4eHgSe+d2R4LoP6sAyIheQ5 +0R+e3thLaCVsF43kpuSiyLGlnFLFBhyQ30vEn1g6jiAwqfqptpr9TPfKaCrCKOJU +R8jOFwy+RERlAGJJQNIeZ6Bz9VdSZwkNP+Gfo+HV9LX057MaeMAPgrvAJrHy/lD9 +y07u0qKN62xzLZ/Mn9do+3qITEU1+9XkX9X0dTXrNMAO9kT3ukR6XdZIl8lvD/2P +gTTaaro51v0ei3I7FZXNokjyuF6J8ARMVxqeOMlVUIxLeBv7j60CAwEAAaOBlzCB +lDAdBgNVHQ4EFgQUEm6hMPB11w1J72tXumBhewwWxnUwHwYDVR0jBBgwFoAUdDJU +xcBc6KvJj1brA4yBJy+Wr6swDgYDVR0PAQH/BAQDAgHCMEIGA1UdHwQ7MDkwN6A1 +oDOGMWh0dHA6Ly9sb2NhbGhvc3QudGVzdC9kZWZhdWx0L2NybHMvY3JsL2xhdGVz +dC5jcmwwDQYJKoZIhvcNAQELBQADggEBAEg69NBvQJkOO25o1UxRoJqKb7PdwF5K +xiidxXjJQTZHVR56rWoMfg/31eDwBdc6bmSAELd2wPSs3Ov3HJJP4f31+plXB3Qb +B5pQUEc5i4IZiE0jz7Be4GLqSVNaLh9ay4o8PnpvcIZiKNukJzPhGsOzW8xrTF7R +Cc6VSjmLHG2UnEt2CBbkaWnVXV8ibENSawv4Ar2AKpcU9LLoT1F92zx/7YpUQLr1 +k/RwWxkKByV5ko001DuwiWf/BjZ67pu5WTgdHQP9KaNMahnSqrjERCTLWVipdvJ2 +o3bHCe9I0OQMVlMeesKMWPRqLiAMpz7f7q09AXlqjvZT9+FPSi6nsss= +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/happyPath/intermediate.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/happyPath/intermediate.cert.pem new file mode 100644 index 0000000000..ca4cf7ba9c --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/happyPath/intermediate.cert.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDQjCCAiqgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA9MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxHjAcBgNVBAMMFWlUZXh0VGVzdEludGVybWVkaWF0ZTCCASIwDQYJ +KoZIhvcNAQEBBQADggEPADCCAQoCggEBAJ6M9OSQgx20Fw14rYFeM6HQuQxBD276 +e6kXMpmdsbbkvExq5mrAWPvFGYHCmRAtH7pGm1pL91Zlgh1CbUPzwSa/Lfp9FeAX +83G7OJn0sY3kJRthtj5B0dGinXSIFCIb6gx9ICzoVpY9Ljvl4tyBr0dkGmED3MBx +SFltOMPplDhYwFekL7woNXMFIAxMnDWuS7dZ7xEpLAwNfH9D92I4lzSrQ9TrxwDP +dW2gWGvi2eu77W4YqFQgydgbKmFHAzDUTA01LNmKZkASBcLUoiLnLBMmVYgDMH4f +o4oj+2/J/OZNuGv5DK9dRCryAhnY3f8/9b8JzoPeRCmgRO9IU7ObZ/0CAwEAAaNS +MFAwHQYDVR0OBBYEFIlAkiqUVGkQL00y55tlNrfwvGTVMB8GA1UdIwQYMBaAFHQy +VMXAXOiryY9W6wOMgScvlq+rMA4GA1UdDwEB/wQEAwIB5jANBgkqhkiG9w0BAQsF +AAOCAQEAMoIJ86nzczzR41l5EFHlxGvUEQY/w7BJ42LICN3F12WPmJ+A3i/GAJSQ +14W+Jy8CXEhEFZF3R45vuOAGhOkF7igtbXeeVXunM3rmi8XIlpGjqbBZxC5w1Fd8 +IPOTArrzcF8agwthRzKOEpFSklmpUDT4MYZkdzR7TVM6TkdL+ModYFrhf9/+OFGb +qHzKUPVv+dvNaKn6JvKfQ311MKG3fLU7vyKEUNoolAnLMy3VETsnhMTk6Wa5rfzJ +eq2sdBiLxgwC3xhYk33Cla0X3hsr++Yqb8BX1ztKaRxu0PSi+KKJ9kvXAxRkFlwh +Xa7iIRXelUhftWRF/4VgDsDhWx+eDQ== +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/happyPath/sign.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/happyPath/sign.cert.pem new file mode 100644 index 0000000000..bfcfbf0242 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/happyPath/sign.cert.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDQjCCAiqgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MR4wHAYDVQQDDBVpVGV4dFRlc3RJbnRlcm1lZGlhdGUw +IBcNMDAwMTAxMDAwMDAwWhgPMjQwMDAxMDEwMDAwMDBaMDUxCzAJBgNVBAYTAkJF +MQ4wDAYDVQQKDAVpVGV4dDEWMBQGA1UEAwwNaVRleHRUZXN0U2lnbjCCASIwDQYJ +KoZIhvcNAQEBBQADggEPADCCAQoCggEBALMHHzTZo1BOQkZzEZl2Q3leNfBH20Yf +O4R0l0ZBWbnpg/099ON4I8ItO0f24Wq0gs//+1adlJqeUMeUVxQ0fpu0cHQOc9h7 +CWJLnPAJjEvItZ5WXW4l8/ppo1bo4WLB1hToF42NfHgh7Laoj2gqVLWXS6Ngd8ch +VxITaxfKA9PG56dje+PlJnTNi+ayudB/O57dhoaAu+sbxBhog/7zRAV87OsH9zxc +Nuw+3ZzHhss5Lpn6F+/WDcHPyXsT7QkX6rvbRvxUOpcysXtCH3v5+ZRKyUqRPlI6 +3/hyMMZBDqYtFDHiawk587hbMp2swHF6z56d10Za22Vq9lxiX4MdftsCAwEAAaNS +MFAwHQYDVR0OBBYEFFVqj/1gRbt6YJdo1/zMvcyOmY1cMB8GA1UdIwQYMBaAFIlA +kiqUVGkQL00y55tlNrfwvGTVMA4GA1UdDwEB/wQEAwIGwDANBgkqhkiG9w0BAQsF +AAOCAQEAMsIeJp6AHJwChOEddcGu5dD/Q4R6l7dMIe3Q8g8vDVz94572jmvHIOa5 +Q/xJALRFn5rG1oC06q6Gy4ffbUm5S1dNBXdmwyfNzAa5yAwXraIWkXLPM5zFUueB +qu2ekfPhHq0NjCqhVCCYkhngaf+mqeuw8usML6mMf8o0aC6TlQu7GXm/6Z4SSKmY +wDyM4iSVR3fZHb3R/VBP7+GNKsamapZPThdxueWnm6o2vsMKSfgGHRV/41BrUqb7 +t5SXDihXCImTpUr89EL7kix42Q/BFQ60hO3LYsKn4w8gjUQffQdlB2zR6cQJx2eK +9jrkP1+J6xcuWHHrn2l9YXw6rI7r0g== +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/issuingDistributionPointTest/certWithDPReasons.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/issuingDistributionPointTest/certWithDPReasons.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/issuingDistributionPointTest/certWithDPReasons.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/issuingDistributionPointTest/certWithDPReasons.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/issuingDistributionPointTest/onlyAttr.crl b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/issuingDistributionPointTest/onlyAttr.crl similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/issuingDistributionPointTest/onlyAttr.crl rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/issuingDistributionPointTest/onlyAttr.crl diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/issuingDistributionPointTest/onlyCA.crl b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/issuingDistributionPointTest/onlyCA.crl similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/issuingDistributionPointTest/onlyCA.crl rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/issuingDistributionPointTest/onlyCA.crl diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/issuingDistributionPointTest/onlyUser.crl b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/issuingDistributionPointTest/onlyUser.crl similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/issuingDistributionPointTest/onlyUser.crl rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/issuingDistributionPointTest/onlyUser.crl diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/issuingDistributionPointTest/root.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/issuingDistributionPointTest/root.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/issuingDistributionPointTest/root.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/issuingDistributionPointTest/root.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/issuingDistributionPointTest/rootCert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/issuingDistributionPointTest/rootCert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/issuingDistributionPointTest/rootCert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/issuingDistributionPointTest/rootCert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/issuingDistributionPointTest/sign.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/issuingDistributionPointTest/sign.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/issuingDistributionPointTest/sign.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/issuingDistributionPointTest/sign.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/keys/crl-key.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/keys/crl-key.pem new file mode 100644 index 0000000000..2d3cc82ac3 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/keys/crl-key.pem @@ -0,0 +1,30 @@ +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQ+urJds/EcAU2OgmN +7A3GxgICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEELjgW4C64QNqkHi/ +9UbE+ksEggTQdbe6Y1LtVHoDERy5p7sy0FEy1k7Co5xmUKPUOLhrFhEPBXs3Lawl +su/CemkwRXt2sdlOUl01wXkDazZEZIkGevGZ6v8COag8CUcMs/woh+dEFRYfSmj9 +fxfFLNCvtR726GLuUboztWmhbsS6jMbAOM2soQoVQwxK5C3P0xQQ2KwL4avK/nYp +OZibBvepGR7cFnkqCCw5Mk/wMe0uTiPqhHf27t7qcXrEXIh/vhT6R0RUDC3wZWRX +gRd+oQbCQ44yeisboPEMC1xs/qAHPd+tfQBX/z6uNeHcwoabwF3fOHxjJmB70ydz +R3vS86uSeOe9/xa0Fz4Vl5nelYek6p+MzhMhmom7OwyNHRlUQfRsemgy6RqXgVbe +hR91V1oH+lkv4cFeV3tBREOWWXbwvU1LUTW2gk2NskLYNZ8SLcURXo1+7M3jZ5EK +X4kTsgcWVJJ/DXVEDsKRQv5OWGZW7IYJkrhUEKAn1OOodlY5irNa7fR6Aj1qc86+ +D7zTF7Mr5VHHqjY0o/nQ145s8KGdx46gPQLvZGw1ipZfXh7ZSv/kRmdYfs6SEZRd +IMF2VOcsgw/SnGfHz3i0YH7SX+G1/lH3YKRr9j+4ZFdIim6qd68l0UlnoheTEKIq +4/5f8dYxmBgeEg2OR0oWvjtX55sXNOSRpoboM1AZlVHBRvXEKZuTXLaj8GjCP6Fy +ww58rug0ZakvcIcoGmZBw0QjS4n3FzoHmIU2U6pJAcYu92yYjhtgCy/BOhmOE/1e +wiLr8r9Jg4gRhGq8it1voNebK0PkpngVKW20gfIlrilww2q6zXlsEm2NBxa9yaif +FGolpBvxjCsPCPTC1/wjj659PCCnflnWu+YMJ7a8VPAeFlKW+D5DV5PXzmJTiIPM +H0BiwNj1wzJBtsqiFRdLlJHO1ys7kqEWVsh4rWJ7aqiq1Nfok2aM/z6TlcBQwtcs +qKmkD+eLKTXhyYByc1oGcV+sc5taAp2ktiMknFGen/jd4DThTxXg+F0E6Jrr0EJb +kKkVPfayQvVczDEoJpwluRuOFyjUWwUybkBvvhu845gi7CEei8T9NoZI+8waCMWq +tQKqIy6HqW4VqFDOmKaS1D0vXaWB64majlvUCRMzGW/XtTZYDnKIqWEcztCjlDNa +tOUUAHFu7NcRwOi9h9Y8tVCL19U2RRDOW4ZpLwcPCPYb1z9WAvLfW9QEhJLu10id +2R5WeCmrTglZpeTgSUsbjmMfyVPROK5Mfp4poNzWvnuyoj0wUk+y9PmExatCqZ+r +yBPJGhC5mYPGun3LaBDAE0vrW8Op3GdSBtdPpV70yZa2t4YqIrgrCSSylmXQSd/K +6fRAsLS/T0stsQ+t9v7nR08EWtEeKYz2DYP94GT21B+1Vi80UR/Rw3z0Wd1FyGMw +Rtp2eIotHGevA9spef1fG8ckjvVfZPow7TAsZsHBhnDZvSu8DByK/1hji1l++QSe +w4z+PwjQnTf1mK0j7R+NKrWOdI0lHKA+T9LfuC5W6T0jAqZxnMefGitOe//fPdKf +MzJd2XZYTCNTUYCZArCxQZwID6kE0dOnomv9f1NB3SrKnkRw3IDMtUsvDanuWHJo +XNEodRiuhObecRmNp7Zl0cX6WQTVyYoMUys/Kei7NVehkVsHmJ7xFd8= +-----END ENCRYPTED PRIVATE KEY----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/keys/im2_key.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/keys/im2_key.pem new file mode 100644 index 0000000000..3bc1ae1572 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/keys/im2_key.pem @@ -0,0 +1,30 @@ +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQ20H7VWfD+2t4fdMK +eME51AICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEDieWNlVjwWqZxb0 +ZX/Z8pkEggTQXND6t2DXbjSWT/dtPiAsb0c6DuwFH4CsHglZvGHJIyT8KEuX6Cjc +AAxaZACpA1/3/Wh3S62UTkK1jbaRApZFZMYP8mkgOkw1cHVDGv3wIb1dzVz1Ql1h +4wrotPAw+obZDFWYG7zS5C8qazlVoH56CxLafKNi/CWjgLcg9lDgkrnBZvLpjHF7 +py9V9BPUOD31TEGY5ZdtJTbYucp5QCBer+MLXoqsF2eI4iMWs0BlGpF46cL01zN6 +W0l+uOznu3d/h81iFYfWAENSpRi+lapzMqbD/cJlQBc/S1U8LEthRKa2p7Yt6NAf +1pRR/NuucXc/GnYrkCC55RK7Y4kuusSO2SU8B66MXbUory9J+pBCizuqqScf+qdh +52Y+tEgrthyQkZP3gw145u6MFYA6ZGcyNma7BWcNDmwQ9ImLBMDSmRVdHqSLujXx +rI3ASvUJtoCq9yOCPrhgha9j6fg/MnYYZL6hmS0osx+AeeCZ/VCOqq5/ctmcoAPX +fmXivH9NrQs7Hv/rMibbRbZumBD3/ueymbnUf17Lf0PGlLe5oMpJUTn6AaTPLqTa +HRQkDDBMsSrRErekAMyYgfQVNRSSmmHxPkoe1woQdVYtkBYcYY0b/B4rI1JW2qV6 +0khSRwPbUlX01z7R3Gwhx/Z18DIGcCHQXM/CHCXVFB56N92TRSpCulJ2fec0sJr7 +nZP4QGXnjmjKwjqITsBwqzgrNhM+yN6IzaLPH/Lu5/fq6yIM58wE3nsM61Zfixig +rBXSyj5fKUQ0sahHEbtFEhxFIiRwflrdCCBI/SXWG2U1lwuhRKRybsMoWB6+9KmZ +tdZUZlw0BUBT+yFTn4Ov8OwMCFhRg9nn/DTqUyju0vLSUitc15or309cgDE2YtHB +UT+GOqVtLcPcTjuBUWgrUIxDT9qUNa7az26tIDr7MNk0iQ4NPJ0COoe2W5sUDMJl +Nwz1k2xRjLsr20+75qm81zhi+1TZptMMTuMwx3NEZPkz2mYx7DL3oLk/7CMFYlZG +lbTr6Xl9deL+ExXMGQfGmCLG9X6lYL+666GI+ADPDw4wsKre6hWgu7BBkFxCyUSB +NxhM1ekh+wY5zwFVEMVCST97AopBWwu2frfa3WnHycQk/jwINSroqgTEmp/DjK1R +H2rye/OXCtSnv1CWxTHCjmIxxXNh5dXZ/M1It9F/+u7sYWlvwxs0Y4FIkBAwp+PY +J5iTLG5Rcuac483k0+kSJw+W2IEcrfLxr0dvTQkP/mUkx6OmHT8f3+2uMjXeVRD6 +tnYVPACAa8toA75DW9lvQeQllGTIStrD3LgQqEDlAEH+D3b0eGFSSX5E/7OnLeKS +SZBikPUHVJSKBXH/HsxzLWRwop640adE7rKTTcHbI9VAZ2H+mozyPibZGzRE43bw +Z8CV3XiCmlM4uxmi9QKGhedjP3Ak14ns/MYiyoK0Z22mNHWgD3DpQB3k2nd67eZw +oX2ddqwcQfjIjhwRcbnsMBHGeCtIS8u3r6trE0DA9dGCScMxVcfkel+y5rtZU3+u +sxdWlFS7bzV4/5PldL/3F2tvn8vYrFzUkmOy43gV6tSnL9ht4znWQLI/nXUcCdOW +eFXWZTwzlZfs4SmII3hfsJFrskP80PC6AjcsfIbBxWphTiL7B2aN2D4= +-----END ENCRYPTED PRIVATE KEY----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/keys/im_key.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/keys/im_key.pem new file mode 100644 index 0000000000..3ba75b5380 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/keys/im_key.pem @@ -0,0 +1,30 @@ +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQ3MrI44qDJ1HV28m3 +64fDSAICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEJMmQPDYjRL7Xj3a +kdVCihUEggTQPUogB6yfRJrKa7T1GngdDkcLrbTo5IPb30bKoEuCLvvq72+rRSH/ +PgKAMWJRvvEtVj7c/EPeRxryo+m92ljFF4A36xAedBBQKcQGwF0a/Jp7uNsofOrr +ZWa013g3SBYCh75s0+7sW9CJ/TeAb4TwVeWXsQZMzAtYcG7QPXYSd4CDTuVYBhh0 +zfGn6DNggfvNwxPIq1MHyY1wGyfkSp/ILRBR4XQ4hF/BdWV190ol7ewtae2GuREk +gDp0XReYvKXKa5k0J3tdIUwCsGxtnmD9tWeBQpPFNahtcx0Ga7RBxnQyJVsY4naf +20RzT8l0bfCv62nHyLU1afMivT1A9uZAngvZXz2eW2vYsCsFxAOoc/6BcCa5ivV8 +X4iFWa9kQPk1nbslaExK/ZsYKsdkpwX8/g+8iVdHGO/D64C0ohiXdSf5XBe/2EJ4 +bFAUR+Ku6+EhUK4ceysq9hSC4eqCyN2e8FR4YHu48jrwiyPyI9oqGuvNic0aPyyW +gUYfpgI2PP/Q6bO9YwM+2wfpQXcfpQy8i+JOlbd6m8YGafYj3rXGvwHEHOUmhdg6 +5jkA92lNrrYR6gvA+QZnYn2AcM+aToi1mx3eJ1sEzXn0UgQJUcCPDFJeGhhhpK+e +j17vltRo9W61qr1ttQ+y9UQGmNCkLUO20NW/0EFLoFrFzB8qhIX/CjA1mPIllaiG +R8Xf/Q1Mdhe/ZbQ/ufc4VuM3p7pf3udYyGAGY+/TadIECXd6ZEllzCOXQfoO0T5o +Sb6rvW2G1LulZ797EAAdLpPjinIHv/snEhLBSyYZUN+XTIpTdG+zxFE/wCyG4ML3 +1GHNmd/OfngRpkqb9rB1K2xCBvnZaJK9t1G799EGLF/EIK9Tc24O3bTcFoA2wKPh +NVmHEHXad2iZuQO8gQvQCezgwHKyk4Z4B5Klmd1uG0nMB6c1q5VpW3x3cgQs72uz +/X/vbdrPitP5fZNb3DrpoIOGFd8HeyMUryoebHducCj6W19xkaHATbyLdnd3Dl1i +fzLPzPnfDv9XyPjizZjyg3MCM9TaJ8YY+zry0x4VwadYM3XZfPGCLUxlEFlM0I9T +N+52ahoWh1U/6E6lr/mQcpKa+BJ/caU5L1X3j1cVU3KKtjz9FJVida/lbZgJS7tJ +aWEFCjq95ihfireDuoOfLDIiKfFU0yQd5q45dEgyuoWsHC1qt4iM+zwS+1fUmrQV +m49S3fm8nsaPrSc2bVp/F8KKi0eeAhfzXICtwVcTTHAoVz3XREbWQ0BpLZxWIkvk +DRK2BCa1HLbtOwwZ/tmgcmOgVdwvdXAUnlXN2ZA0KwfKDY3v0pvwzEnatSU7DH+T +K28EqBDnPY4mrelYaGT3qRZo7R4itH2fvC7M/hwzaX8mR0lyMkJADzOleWHC288W +Ku2uV4LGo0gtenICTdogcUctK8AgUAz4qF8oa8Xij0ZaB2ncYL837ZCOYiguHFQs +LrbsO6zB3wyi00PcozmjNUjgsni51ku9ftLpneR5t6d3dF6jkZlggXRRiGmbVNpb +OHkLyGEt4kryQGzw8Y+uf11Zoffzr0UjzTnTKpPHniqjUSb5YCKEG2erwb+HN0D/ +27AXRMlMACYOwoX7krgGcGrYeJJa3h9Y442TNMtMMpd3yJKOMr8OEaw= +-----END ENCRYPTED PRIVATE KEY----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/keys/root_key.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/keys/root_key.pem new file mode 100644 index 0000000000..3c8d16b9c4 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/keys/root_key.pem @@ -0,0 +1,30 @@ +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQCCEV6O6sip4xlX6V +9cfMcAICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEGMdp4t7kRReyjMr +R/DJhnwEggTQCtpkMGabpm+2IipjEdhnw+rXUkNSNFqg7nN5A+zXE9W3V/mPFJdu +/AVCkagFCUM7z5Wx4k4GIfwX0q/S1TDorcDisg9sgGWO5TYwqHCJRffOcFkf9GoJ +TSUABpYyctbpC6gbUhOAG9xCeWkYwhQ5RdIKd4I7xuPFmJm/aYclCNpFx2ymydIc +0lC+OmfrosIMlhCpX7WMB/zwubMUD7NDtxOqzvoE2HOKljfOWGWgbW6I4BGKiU7z +vZV4nJXOpcthK/qqTZbuxZDwzY3ZHYgPh9bUTTRg53jSPi6wQT+DFOjYa+HXco62 +Zsyr8ER9vdnX+GNZCRyY7AYpJZv8aIk5hh7c88/kQSluWiz6twDlSG211eMV6tOW +6N1QyscQoyay8+Ug3XxMpd3KA+rVNNBvmixj8hk6L9Aek3jGbMM+X7EcgZ66z3Q0 +kXuweb4cynaBVpryAQLT0zbUj3J5xdnJmE7+4/8PE4qKw3aZOKfL2+WlrejiUfP9 +lXa6GYhlPL435RdFw/Kv6huJ6vAL1az07G7GysImvkcLWxs4EhsSjxNB6ecGjhG0 +eAqXtMDK7yFweALT2RJSNhlKXiEyvs9Nm+kGDyBrCAqk7GTpp1fXLtKr4Nf9dTKO +6TyqjadT0hJLUVnoTxX+L8peYm2JVSeS/oCi0Im9bq1zW6MXQ74mDeSdLXWfXJjA +J9dA+CojSH9i07E/yalQxtA4nED74XmOSNK8Y8NSuZpdrZMvRmpOoWkZzMA46HQL +za0QtVNaMiHfiFV3a7ktbDCNFmAZyXz+L+4qB4V19k8Y13RgMbhDYYkwp5z1Z+Md +875DYb5QTxGDQfuYrCyDMR5TGezJ7QAvBRtN6ytxHJttqCP6pBSOOcyIsJxg5FnV +mjfGf/C7V9pkXne83IG+S9pF7IncTGRmql9QEfd7PMThuUoY16E9HN0ynCYO/x+Z +5quPMukfwh9d2fSNtpFptyXrcHGLOrvh2l4Hxypx6g+WG49q1cyUKoOldloY1o6Z +W2+LoFj1o+lJUoIAADrSTsRUEBazSygz3LevHWA+3nh1ljDfTd3eV02+CNB7xdHe +kpt8WU7yrA2a/MOgsfcUvZOaBwgDqf0mzGuPmZITjTXJzTrWoMlJKaMpw+1lPSnS +7k1RRs6KGso1E7S1JIgHeo0DZgP95+IoFL5APGwBZHX3w4LHtciR0spIVQ0lI9Um +WtDYHugnfR+j4GRmpnC9WUCBv+kRgsZxBzcPd53NfIVWu/1Vk0GH6qcCNngGwlLn +SJZncwG5bZj5IH82dNzZrtnahxLJ4n72aU3SFevxu/9KokB39doJYQU9Ifud2YwM +kYWIhDBtukpE4FWdcO7dt4Xwh9ThFttTG4VAkLNYFHOg2OINW2WmoPInD/HnYkik +qTRF1q4ItJHY9I8Tj0wTKvtqCoO1HjhVgkWdk7+BgEOII19V7OSFOeTvG+6hmCSj +WBSA+bth2RlsjCgxLx8YshbctBFhBJ/Vqm08InjRTCYmqFJm7WdUtssfZWCog63f +3TJBwwq8TPQIle8gTAsuPPjqnm+7mjzLVe6a3MY36rNB55zsxbkc9BysDKRMLDOh +0EXYDWgavFGlaycsK5HohOovpwtR9YFJ/QWHGONb3ABF48yQHq3IogE= +-----END ENCRYPTED PRIVATE KEY----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/keys/sign-key.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/keys/sign-key.pem new file mode 100644 index 0000000000..ca58df688f --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/keys/sign-key.pem @@ -0,0 +1,30 @@ +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQ19Lc6P09f69/8SfZ +XiijZgICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEFDB/s9gDONS6aOH +lX2oEnEEggTQDm6xQuhgWpBClEy0wjynzXFvQvEL+IQxBauz81wr0wQvlHiDgBS/ +BDtojvYNXbaNtpt8c5vV41twVtBu0JUCfL17EMpOUq0XAYQhEWul+DcMGXy+g9A9 +WMaXBUTz96KLUk1n9B0mwZvcttNA5mq0bxRL/wc3lPSKOMDVrxUruu7et1dzC8jU +y/K5W7clmivxwLUiRrkMYVWlesDQSa+TqpdcA/K0vJXfMF6jY5ssNRhcs2EWzQwo +27U5EVTaTV3c32y+UgYAaOnmy7vlw0rhc8AR5vbUHCSKa4UTRLzlJbk47tYW/rKM +YvjeV+GZqaInkQkCoF81GoR3UF/4QQVkT0rYQEUtvSsz24MYU+irT0KBdvkxj7ah +gYSFcDXlPGBuHot8+ZwB7ofARai/O41vLnqMsLogKK9KiuIxvwJlSE1yGtZMmd/w +oJ+qpH0dY+gUCN+Cwcd9z7vyRwPfmh8e22aO97UKoA3X+wtFYt7jUycZHFe85FLW +e8N1/Ly5P2E5aSdku6x07ye596RYEi8kw+KrAL1NCSOfiejaKxpzcHaO7C6C5SGq +dTDVpi4moH5GOG2ksqlL928EwmLklMoFMgMs0CnBcKVAHOdUleIA87blVTFh8U3r +8CSStkohnhPHPgptwoXppl4wbACiZ257jDgo24GEWx82Kdaff4KReZZtlwEUUAa4 +jd+OGbAClAYJW6DGYKBcoXXYCs8Kuaoyze3YNozAXl2n9W00FS/mAG3GTK6HbzEz +7KnrpgPNWQh/jjm9YnS02pTy1g2Gk2LW0CV1HxMkTOBRRdMM4ZZejLQPPftouYnv +ZebDCUUC8fV9vEowJ0FDqgcI2k640x3xDJwtQee3GUDPtietyYHV2QvsStcVbDdg +pGaMBYnbppafyJrh5nUT8Lyvolq3G1ejd1GEFatLuFxXTCUbJ+NKwl1dC0xaexVs +439ExdWlzGwkqSMEvyB9cV79ZWaYVtIf/SpGquO0ywTu/uU8FAossWuX907OVQtz +3LOIhGDcYrpZUqeK/gc8FrOjA27UwI9/+NGaLE18On1EkYIqnN2ncguPhZrGXwGR +dfuGgmpJxSSm55Wd4WvVmLYgX0xIUKVAUv6nl8oMPOh8GRAycFRAW50yNUWjriuw +RCGO2cWBeLQodtZ1G9+5oWq5T6KBsbeFjagUONVWo8aZX4cULLZsUD5Ay3yRLdnd +ACGI0bJ1HtRfHX6hMlXj7VCosaA/4IpjSUg5yOry5bzYQ5aOyWiLGY+EV9zM5Wl5 +/tfvGFGHVi1T6yjLlHytriq9xhbWdwA+D6jEGv24c05zQUoOsNUGUncEuonx4eBN +oSVmv5TIMxK/umqnZ6LrUMxDLi+B/CWnN/sNskZP4QRKnG56/KMVk9XdmYT1ql4m +Q0yTTsy9TbXmOkIkUmm+XTRPuLH/NFjX4+zE0O2jf4PvtzYyEzHCiA0uWwEq6zrv +gsuWsCr1Y588qK6W/VC9zgfqgh/2HhSnmv/uNi5bNqnj82m3eEyrlmp4b9wtRR3k +bgoq7PyOHmP2Bj4wdUQe2+QOMLySBJm3odA7NWkBeCaq6M3ZqdHf56q/nKVReUlS +9THEOrp3W81kStFZ0ueilyviJalJq575FAQntnlFy1wgBqBmk0/0qaU= +-----END ENCRYPTED PRIVATE KEY----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/missingIssuer/chain.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/missingIssuer/chain.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/missingIssuer/chain.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/missingIssuer/chain.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlEncodingError/crl-issuer.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/missingIssuer/crl-issuer.cert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlEncodingError/crl-issuer.cert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/missingIssuer/crl-issuer.cert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/missingIssuer/crl.crl b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/missingIssuer/crl.crl similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/missingIssuer/crl.crl rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/missingIssuer/crl.crl diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlAndSignCertRootIssuerMismatch/sign.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/missingIssuer/sign.cert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlAndSignCertRootIssuerMismatch/sign.cert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/missingIssuer/sign.cert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/multipleCrlIssuerCandidates.yml b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/multipleCrlIssuerCandidates.yml new file mode 100644 index 0000000000..28a382457b --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/multipleCrlIssuerCandidates.yml @@ -0,0 +1,113 @@ +external-url-prefix: "http://localhost.test" +keysets: + testkeys: + keys: + ca: + path: keys/root_key.pem + password: testpassphrase + intermediate: + path: keys/im_key.pem + password: testpassphrase + sign: + path: keys/sign-key.pem + password: testpassphrase + crl-issuer: + path: keys/crl-key.pem + password: testpassphrase + crl-issuer-candidate1: + path: keys/im_key.pem + password: testpassphrase + crl-issuer-candidate2: + path: keys/sign-key.pem + password: testpassphrase + +pki-architectures: + default: + keyset: testkeys + entity-defaults: + country-name: BE + organization-name: iText + entities: + ca: + common-name: iTextTestRoot + intermediate: + common-name: iTextTestIntermediate + sign: + common-name: iTextTestSign + crl-issuer: + common-name: iTextTestCrlIssuer + crl-issuer-candidate1: + common-name: iTextTestCrlIssuer + crl-issuer-candidate2: + common-name: iTextTestCrlIssuer + certs: + ca: + subject: ca + issuer: ca + validity: + valid-from: "2000-01-01T00:00:00+0000" + valid-to: "2500-01-01T00:00:00+0000" + extensions: + - id: basic_constraints + critical: true + value: + ca: true + - id: key_usage + critical: true + smart-value: + schema: key-usage + params: [digital_signature, non_repudiation, key_encipherment, key_cert_sign] + intermediate: + issuer: ca + validity: + valid-from: "2000-01-01T00:00:00+0000" + valid-to: "2450-01-01T00:00:00+0000" + extensions: + - id: key_usage + critical: true + smart-value: + schema: key-usage + params: [digital_signature, non_repudiation, key_encipherment, key_cert_sign, crl_sign] + sign: + issuer: intermediate + validity: + valid-from: "2000-01-01T00:00:00+0000" + valid-to: "2400-01-01T00:00:00+0000" + extensions: + - id: key_usage + critical: true + smart-value: + schema: key-usage + params: [digital_signature, non_repudiation] + crl-issuer: + issuer: ca + validity: + valid-from: "2000-01-01T00:00:00+0000" + valid-to: "2450-01-01T00:00:00+0000" + extensions: + - id: key_usage + critical: true + smart-value: + schema: key-usage + params: [ digital_signature, non_repudiation, crl_sign] + - id: crl_distribution_points + smart-value: + schema: crl-dist-url + params: + crl-repo-names: [crl] + crl-issuer-candidate1: + issuer: ca + validity: + valid-from: "2000-01-01T00:00:00+0000" + valid-to: "2450-01-01T00:00:00+0000" + crl-issuer-candidate2: + issuer: ca + validity: + valid-from: "2000-01-01T00:00:00+0000" + valid-to: "2450-01-01T00:00:00+0000" + services: + crl-repo: + crl: + for-issuer: crl-issuer + signing-key: crl-issuer + simulated-update-schedule: "P90D" \ No newline at end of file diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/multipleCrlIssuerCandidates/ca.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/multipleCrlIssuerCandidates/ca.cert.pem new file mode 100644 index 0000000000..efb7717302 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/multipleCrlIssuerCandidates/ca.cert.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDSzCCAjOgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI1MDAwMTAxMDAwMDAwWjA1MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxFjAUBgNVBAMMDWlUZXh0VGVzdFJvb3QwggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQDYxUs+SgZkRkOhOfddCnPeuE1QP2kAm6gAsg4qjNzr +rZpZvwziyWaz6bXXq8fATjXEAdypAiWL/BDZscdCM/M11jds9mMv7dMvCtLns6Oe +4GbChYxxloN2rVxElFPK2siKBaEeWyItr2Ms0P+hSR5uHjFt+krzl2zv828fyEnH +fPvln42SAcuCKsLmfjtutus5jFKBFF8oiqDFlI2eXYggKV7JELttgPLobv2ZyFa5 +nXo/xbtzlPb8AvV3/mxpX4prFhBXupJXuCwmqmzVRqGbwKSz/Bewb/4aJGSpg32x +yIWeXTld58f+Jntfes8xHwK0aJB/Tm2WrH+RWoV+TN/pAgMBAAGjYzBhMB0GA1Ud +DgQWBBR0MlTFwFzoq8mPVusDjIEnL5avqzAfBgNVHSMEGDAWgBR0MlTFwFzoq8mP +VusDjIEnL5avqzAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIC5DANBgkq +hkiG9w0BAQsFAAOCAQEAK2dbxbQ7jEdtqvnMpKOZsB55PDO5OZ2hPYilT5ZVZNt1 +jdE94HdCBHED3upmOeBH+XtsK/MLk+eYICM5SZwWVCBY0aQQR0URyTsX4SA/12A5 +VhrnP6bqy4b+3mO3J9s0go59cZOtSkxQ7191teEQMsDeh8GxXGLW/7Tf4x6v7U34 +B7UghMhUD2bHJ7U8MOqto9fVar/9S93tc9vRtYOXZbfRwjFKOYD4IFm7cH3VnrX7 +od3KUEKGKhQ2ZaqrtnW19xNTbdRcMT3+8QSai9DLV0kGGSSY09AHDO3WvxkAs9ZI +cIsMM/n+mLK0Km9fh5uE3k6NmiN3GV+QMyjbmFnVNg== +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/multipleCrlIssuerCandidates/chain.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/multipleCrlIssuerCandidates/chain.pem new file mode 100644 index 0000000000..c5a2a1b14e --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/multipleCrlIssuerCandidates/chain.pem @@ -0,0 +1,121 @@ +-----BEGIN CERTIFICATE----- +MIIDSzCCAjOgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI1MDAwMTAxMDAwMDAwWjA1MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxFjAUBgNVBAMMDWlUZXh0VGVzdFJvb3QwggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQDYxUs+SgZkRkOhOfddCnPeuE1QP2kAm6gAsg4qjNzr +rZpZvwziyWaz6bXXq8fATjXEAdypAiWL/BDZscdCM/M11jds9mMv7dMvCtLns6Oe +4GbChYxxloN2rVxElFPK2siKBaEeWyItr2Ms0P+hSR5uHjFt+krzl2zv828fyEnH +fPvln42SAcuCKsLmfjtutus5jFKBFF8oiqDFlI2eXYggKV7JELttgPLobv2ZyFa5 +nXo/xbtzlPb8AvV3/mxpX4prFhBXupJXuCwmqmzVRqGbwKSz/Bewb/4aJGSpg32x +yIWeXTld58f+Jntfes8xHwK0aJB/Tm2WrH+RWoV+TN/pAgMBAAGjYzBhMB0GA1Ud +DgQWBBR0MlTFwFzoq8mPVusDjIEnL5avqzAfBgNVHSMEGDAWgBR0MlTFwFzoq8mP +VusDjIEnL5avqzAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIC5DANBgkq +hkiG9w0BAQsFAAOCAQEAK2dbxbQ7jEdtqvnMpKOZsB55PDO5OZ2hPYilT5ZVZNt1 +jdE94HdCBHED3upmOeBH+XtsK/MLk+eYICM5SZwWVCBY0aQQR0URyTsX4SA/12A5 +VhrnP6bqy4b+3mO3J9s0go59cZOtSkxQ7191teEQMsDeh8GxXGLW/7Tf4x6v7U34 +B7UghMhUD2bHJ7U8MOqto9fVar/9S93tc9vRtYOXZbfRwjFKOYD4IFm7cH3VnrX7 +od3KUEKGKhQ2ZaqrtnW19xNTbdRcMT3+8QSai9DLV0kGGSSY09AHDO3WvxkAs9ZI +cIsMM/n+mLK0Km9fh5uE3k6NmiN3GV+QMyjbmFnVNg== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDLzCCAhegAwIBAgICEAMwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA6MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxGzAZBgNVBAMMEmlUZXh0VGVzdENybElzc3VlcjCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBAJ6M9OSQgx20Fw14rYFeM6HQuQxBD276e6kX +MpmdsbbkvExq5mrAWPvFGYHCmRAtH7pGm1pL91Zlgh1CbUPzwSa/Lfp9FeAX83G7 +OJn0sY3kJRthtj5B0dGinXSIFCIb6gx9ICzoVpY9Ljvl4tyBr0dkGmED3MBxSFlt +OMPplDhYwFekL7woNXMFIAxMnDWuS7dZ7xEpLAwNfH9D92I4lzSrQ9TrxwDPdW2g +WGvi2eu77W4YqFQgydgbKmFHAzDUTA01LNmKZkASBcLUoiLnLBMmVYgDMH4fo4oj ++2/J/OZNuGv5DK9dRCryAhnY3f8/9b8JzoPeRCmgRO9IU7ObZ/0CAwEAAaNCMEAw +HQYDVR0OBBYEFIlAkiqUVGkQL00y55tlNrfwvGTVMB8GA1UdIwQYMBaAFHQyVMXA +XOiryY9W6wOMgScvlq+rMA0GCSqGSIb3DQEBCwUAA4IBAQAPKoa+iFhdqGoBXjuj ++m/xG2NAetvfpN4Sfy8RGOhEypsre2Xk/MzL6UBa59IYK3cd/x8ceAqPoBozL+NZ +Xu3WzvD65zoLDJxBtHpOjaz3Mi/Yjxlfw7mb+loUj8tusouGhqhvJuKTzpXafFYu +Ue1gwk+Lb3KsunkMhPc5s2h/yTkgbnrBbHuP5g8HRW0pbk3xZC4qHmrMsWHFGLba +CAZ+AcyRaIGHqFQwnflWuMBNXr2KNL6J9IBs33mPNEaJZEqyIr5N7urXcTUS0Cog +ZA3eugW6tacN8hR+6RA4dBIpPVth/tV2V3OtyeRUFKPrFYmaalgfSXYQPzoKDZpr +SP8t +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDLzCCAhegAwIBAgICEAQwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA6MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxGzAZBgNVBAMMEmlUZXh0VGVzdENybElzc3VlcjCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBALMHHzTZo1BOQkZzEZl2Q3leNfBH20YfO4R0 +l0ZBWbnpg/099ON4I8ItO0f24Wq0gs//+1adlJqeUMeUVxQ0fpu0cHQOc9h7CWJL +nPAJjEvItZ5WXW4l8/ppo1bo4WLB1hToF42NfHgh7Laoj2gqVLWXS6Ngd8chVxIT +axfKA9PG56dje+PlJnTNi+ayudB/O57dhoaAu+sbxBhog/7zRAV87OsH9zxcNuw+ +3ZzHhss5Lpn6F+/WDcHPyXsT7QkX6rvbRvxUOpcysXtCH3v5+ZRKyUqRPlI63/hy +MMZBDqYtFDHiawk587hbMp2swHF6z56d10Za22Vq9lxiX4MdftsCAwEAAaNCMEAw +HQYDVR0OBBYEFFVqj/1gRbt6YJdo1/zMvcyOmY1cMB8GA1UdIwQYMBaAFHQyVMXA +XOiryY9W6wOMgScvlq+rMA0GCSqGSIb3DQEBCwUAA4IBAQC5ZQAycuP/G9srjdfF +nT33PWTfQn98+YybTBcb1Zj1zsD8ELBvN1esksMknNyYwL212CuY0pN32adV9eUQ +A3GrLWEeBICJB6TR6UJ/BSI/0kLeN5TaAb0aRzjENQDAe3tJPXD1vVmNWvYxrDCk +ncdKVOODsz4N+v0+EO8iUUNENDp69VyPBbw0oLjTHCwtqx5B3m35oHibXT3BuQPd +OVDxFfd3PB/CrDWibobVOWw6MaTt5Oiv9WKbo0l0qZ76vyKdjqbQwqHdSfr23k/Y +5PB9YYlqqPPxdSExzka/Oi7n21x1NhAr2T42p1Ff3ph3oQ2P3Qwn72ESu3riImmK +18vH +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDhTCCAm2gAwIBAgICEAIwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA6MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxGzAZBgNVBAMMEmlUZXh0VGVzdENybElzc3VlcjCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBAMJ7DjX87Zpw3SySm1nfLBP9rcaJse9hwZ6w +TNxtmy6Rn3LwBZvZ/xdFi39XTw2GPeCQBSrARhtBJ4eHgSe+d2R4LoP6sAyIheQ5 +0R+e3thLaCVsF43kpuSiyLGlnFLFBhyQ30vEn1g6jiAwqfqptpr9TPfKaCrCKOJU +R8jOFwy+RERlAGJJQNIeZ6Bz9VdSZwkNP+Gfo+HV9LX057MaeMAPgrvAJrHy/lD9 +y07u0qKN62xzLZ/Mn9do+3qITEU1+9XkX9X0dTXrNMAO9kT3ukR6XdZIl8lvD/2P +gTTaaro51v0ei3I7FZXNokjyuF6J8ARMVxqeOMlVUIxLeBv7j60CAwEAAaOBlzCB +lDAdBgNVHQ4EFgQUEm6hMPB11w1J72tXumBhewwWxnUwHwYDVR0jBBgwFoAUdDJU +xcBc6KvJj1brA4yBJy+Wr6swDgYDVR0PAQH/BAQDAgHCMEIGA1UdHwQ7MDkwN6A1 +oDOGMWh0dHA6Ly9sb2NhbGhvc3QudGVzdC9kZWZhdWx0L2NybHMvY3JsL2xhdGVz +dC5jcmwwDQYJKoZIhvcNAQELBQADggEBAEg69NBvQJkOO25o1UxRoJqKb7PdwF5K +xiidxXjJQTZHVR56rWoMfg/31eDwBdc6bmSAELd2wPSs3Ov3HJJP4f31+plXB3Qb +B5pQUEc5i4IZiE0jz7Be4GLqSVNaLh9ay4o8PnpvcIZiKNukJzPhGsOzW8xrTF7R +Cc6VSjmLHG2UnEt2CBbkaWnVXV8ibENSawv4Ar2AKpcU9LLoT1F92zx/7YpUQLr1 +k/RwWxkKByV5ko001DuwiWf/BjZ67pu5WTgdHQP9KaNMahnSqrjERCTLWVipdvJ2 +o3bHCe9I0OQMVlMeesKMWPRqLiAMpz7f7q09AXlqjvZT9+FPSi6nsss= +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDQjCCAiqgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA9MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxHjAcBgNVBAMMFWlUZXh0VGVzdEludGVybWVkaWF0ZTCCASIwDQYJ +KoZIhvcNAQEBBQADggEPADCCAQoCggEBAJ6M9OSQgx20Fw14rYFeM6HQuQxBD276 +e6kXMpmdsbbkvExq5mrAWPvFGYHCmRAtH7pGm1pL91Zlgh1CbUPzwSa/Lfp9FeAX +83G7OJn0sY3kJRthtj5B0dGinXSIFCIb6gx9ICzoVpY9Ljvl4tyBr0dkGmED3MBx +SFltOMPplDhYwFekL7woNXMFIAxMnDWuS7dZ7xEpLAwNfH9D92I4lzSrQ9TrxwDP +dW2gWGvi2eu77W4YqFQgydgbKmFHAzDUTA01LNmKZkASBcLUoiLnLBMmVYgDMH4f +o4oj+2/J/OZNuGv5DK9dRCryAhnY3f8/9b8JzoPeRCmgRO9IU7ObZ/0CAwEAAaNS +MFAwHQYDVR0OBBYEFIlAkiqUVGkQL00y55tlNrfwvGTVMB8GA1UdIwQYMBaAFHQy +VMXAXOiryY9W6wOMgScvlq+rMA4GA1UdDwEB/wQEAwIB5jANBgkqhkiG9w0BAQsF +AAOCAQEAMoIJ86nzczzR41l5EFHlxGvUEQY/w7BJ42LICN3F12WPmJ+A3i/GAJSQ +14W+Jy8CXEhEFZF3R45vuOAGhOkF7igtbXeeVXunM3rmi8XIlpGjqbBZxC5w1Fd8 +IPOTArrzcF8agwthRzKOEpFSklmpUDT4MYZkdzR7TVM6TkdL+ModYFrhf9/+OFGb +qHzKUPVv+dvNaKn6JvKfQ311MKG3fLU7vyKEUNoolAnLMy3VETsnhMTk6Wa5rfzJ +eq2sdBiLxgwC3xhYk33Cla0X3hsr++Yqb8BX1ztKaRxu0PSi+KKJ9kvXAxRkFlwh +Xa7iIRXelUhftWRF/4VgDsDhWx+eDQ== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDQjCCAiqgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MR4wHAYDVQQDDBVpVGV4dFRlc3RJbnRlcm1lZGlhdGUw +IBcNMDAwMTAxMDAwMDAwWhgPMjQwMDAxMDEwMDAwMDBaMDUxCzAJBgNVBAYTAkJF +MQ4wDAYDVQQKDAVpVGV4dDEWMBQGA1UEAwwNaVRleHRUZXN0U2lnbjCCASIwDQYJ +KoZIhvcNAQEBBQADggEPADCCAQoCggEBALMHHzTZo1BOQkZzEZl2Q3leNfBH20Yf +O4R0l0ZBWbnpg/099ON4I8ItO0f24Wq0gs//+1adlJqeUMeUVxQ0fpu0cHQOc9h7 +CWJLnPAJjEvItZ5WXW4l8/ppo1bo4WLB1hToF42NfHgh7Laoj2gqVLWXS6Ngd8ch +VxITaxfKA9PG56dje+PlJnTNi+ayudB/O57dhoaAu+sbxBhog/7zRAV87OsH9zxc +Nuw+3ZzHhss5Lpn6F+/WDcHPyXsT7QkX6rvbRvxUOpcysXtCH3v5+ZRKyUqRPlI6 +3/hyMMZBDqYtFDHiawk587hbMp2swHF6z56d10Za22Vq9lxiX4MdftsCAwEAAaNS +MFAwHQYDVR0OBBYEFFVqj/1gRbt6YJdo1/zMvcyOmY1cMB8GA1UdIwQYMBaAFIlA +kiqUVGkQL00y55tlNrfwvGTVMA4GA1UdDwEB/wQEAwIGwDANBgkqhkiG9w0BAQsF +AAOCAQEAMsIeJp6AHJwChOEddcGu5dD/Q4R6l7dMIe3Q8g8vDVz94572jmvHIOa5 +Q/xJALRFn5rG1oC06q6Gy4ffbUm5S1dNBXdmwyfNzAa5yAwXraIWkXLPM5zFUueB +qu2ekfPhHq0NjCqhVCCYkhngaf+mqeuw8usML6mMf8o0aC6TlQu7GXm/6Z4SSKmY +wDyM4iSVR3fZHb3R/VBP7+GNKsamapZPThdxueWnm6o2vsMKSfgGHRV/41BrUqb7 +t5SXDihXCImTpUr89EL7kix42Q/BFQ60hO3LYsKn4w8gjUQffQdlB2zR6cQJx2eK +9jrkP1+J6xcuWHHrn2l9YXw6rI7r0g== +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/multipleCrlIssuerCandidates/crl-issuer-candidate1.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/multipleCrlIssuerCandidates/crl-issuer-candidate1.cert.pem new file mode 100644 index 0000000000..cb1f374156 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/multipleCrlIssuerCandidates/crl-issuer-candidate1.cert.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDLzCCAhegAwIBAgICEAMwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA6MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxGzAZBgNVBAMMEmlUZXh0VGVzdENybElzc3VlcjCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBAJ6M9OSQgx20Fw14rYFeM6HQuQxBD276e6kX +MpmdsbbkvExq5mrAWPvFGYHCmRAtH7pGm1pL91Zlgh1CbUPzwSa/Lfp9FeAX83G7 +OJn0sY3kJRthtj5B0dGinXSIFCIb6gx9ICzoVpY9Ljvl4tyBr0dkGmED3MBxSFlt +OMPplDhYwFekL7woNXMFIAxMnDWuS7dZ7xEpLAwNfH9D92I4lzSrQ9TrxwDPdW2g +WGvi2eu77W4YqFQgydgbKmFHAzDUTA01LNmKZkASBcLUoiLnLBMmVYgDMH4fo4oj ++2/J/OZNuGv5DK9dRCryAhnY3f8/9b8JzoPeRCmgRO9IU7ObZ/0CAwEAAaNCMEAw +HQYDVR0OBBYEFIlAkiqUVGkQL00y55tlNrfwvGTVMB8GA1UdIwQYMBaAFHQyVMXA +XOiryY9W6wOMgScvlq+rMA0GCSqGSIb3DQEBCwUAA4IBAQAPKoa+iFhdqGoBXjuj ++m/xG2NAetvfpN4Sfy8RGOhEypsre2Xk/MzL6UBa59IYK3cd/x8ceAqPoBozL+NZ +Xu3WzvD65zoLDJxBtHpOjaz3Mi/Yjxlfw7mb+loUj8tusouGhqhvJuKTzpXafFYu +Ue1gwk+Lb3KsunkMhPc5s2h/yTkgbnrBbHuP5g8HRW0pbk3xZC4qHmrMsWHFGLba +CAZ+AcyRaIGHqFQwnflWuMBNXr2KNL6J9IBs33mPNEaJZEqyIr5N7urXcTUS0Cog +ZA3eugW6tacN8hR+6RA4dBIpPVth/tV2V3OtyeRUFKPrFYmaalgfSXYQPzoKDZpr +SP8t +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/multipleCrlIssuerCandidates/crl-issuer-candidate2.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/multipleCrlIssuerCandidates/crl-issuer-candidate2.cert.pem new file mode 100644 index 0000000000..dba77cd210 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/multipleCrlIssuerCandidates/crl-issuer-candidate2.cert.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDLzCCAhegAwIBAgICEAQwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA6MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxGzAZBgNVBAMMEmlUZXh0VGVzdENybElzc3VlcjCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBALMHHzTZo1BOQkZzEZl2Q3leNfBH20YfO4R0 +l0ZBWbnpg/099ON4I8ItO0f24Wq0gs//+1adlJqeUMeUVxQ0fpu0cHQOc9h7CWJL +nPAJjEvItZ5WXW4l8/ppo1bo4WLB1hToF42NfHgh7Laoj2gqVLWXS6Ngd8chVxIT +axfKA9PG56dje+PlJnTNi+ayudB/O57dhoaAu+sbxBhog/7zRAV87OsH9zxcNuw+ +3ZzHhss5Lpn6F+/WDcHPyXsT7QkX6rvbRvxUOpcysXtCH3v5+ZRKyUqRPlI63/hy +MMZBDqYtFDHiawk587hbMp2swHF6z56d10Za22Vq9lxiX4MdftsCAwEAAaNCMEAw +HQYDVR0OBBYEFFVqj/1gRbt6YJdo1/zMvcyOmY1cMB8GA1UdIwQYMBaAFHQyVMXA +XOiryY9W6wOMgScvlq+rMA0GCSqGSIb3DQEBCwUAA4IBAQC5ZQAycuP/G9srjdfF +nT33PWTfQn98+YybTBcb1Zj1zsD8ELBvN1esksMknNyYwL212CuY0pN32adV9eUQ +A3GrLWEeBICJB6TR6UJ/BSI/0kLeN5TaAb0aRzjENQDAe3tJPXD1vVmNWvYxrDCk +ncdKVOODsz4N+v0+EO8iUUNENDp69VyPBbw0oLjTHCwtqx5B3m35oHibXT3BuQPd +OVDxFfd3PB/CrDWibobVOWw6MaTt5Oiv9WKbo0l0qZ76vyKdjqbQwqHdSfr23k/Y +5PB9YYlqqPPxdSExzka/Oi7n21x1NhAr2T42p1Ff3ph3oQ2P3Qwn72ESu3riImmK +18vH +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/multipleCrlIssuerCandidates/crl-issuer.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/multipleCrlIssuerCandidates/crl-issuer.cert.pem new file mode 100644 index 0000000000..3656f9e733 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/multipleCrlIssuerCandidates/crl-issuer.cert.pem @@ -0,0 +1,21 @@ +-----BEGIN CERTIFICATE----- +MIIDhTCCAm2gAwIBAgICEAIwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA6MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxGzAZBgNVBAMMEmlUZXh0VGVzdENybElzc3VlcjCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBAMJ7DjX87Zpw3SySm1nfLBP9rcaJse9hwZ6w +TNxtmy6Rn3LwBZvZ/xdFi39XTw2GPeCQBSrARhtBJ4eHgSe+d2R4LoP6sAyIheQ5 +0R+e3thLaCVsF43kpuSiyLGlnFLFBhyQ30vEn1g6jiAwqfqptpr9TPfKaCrCKOJU +R8jOFwy+RERlAGJJQNIeZ6Bz9VdSZwkNP+Gfo+HV9LX057MaeMAPgrvAJrHy/lD9 +y07u0qKN62xzLZ/Mn9do+3qITEU1+9XkX9X0dTXrNMAO9kT3ukR6XdZIl8lvD/2P +gTTaaro51v0ei3I7FZXNokjyuF6J8ARMVxqeOMlVUIxLeBv7j60CAwEAAaOBlzCB +lDAdBgNVHQ4EFgQUEm6hMPB11w1J72tXumBhewwWxnUwHwYDVR0jBBgwFoAUdDJU +xcBc6KvJj1brA4yBJy+Wr6swDgYDVR0PAQH/BAQDAgHCMEIGA1UdHwQ7MDkwN6A1 +oDOGMWh0dHA6Ly9sb2NhbGhvc3QudGVzdC9kZWZhdWx0L2NybHMvY3JsL2xhdGVz +dC5jcmwwDQYJKoZIhvcNAQELBQADggEBAEg69NBvQJkOO25o1UxRoJqKb7PdwF5K +xiidxXjJQTZHVR56rWoMfg/31eDwBdc6bmSAELd2wPSs3Ov3HJJP4f31+plXB3Qb +B5pQUEc5i4IZiE0jz7Be4GLqSVNaLh9ay4o8PnpvcIZiKNukJzPhGsOzW8xrTF7R +Cc6VSjmLHG2UnEt2CBbkaWnVXV8ibENSawv4Ar2AKpcU9LLoT1F92zx/7YpUQLr1 +k/RwWxkKByV5ko001DuwiWf/BjZ67pu5WTgdHQP9KaNMahnSqrjERCTLWVipdvJ2 +o3bHCe9I0OQMVlMeesKMWPRqLiAMpz7f7q09AXlqjvZT9+FPSi6nsss= +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/multipleCrlIssuerCandidates/intermediate.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/multipleCrlIssuerCandidates/intermediate.cert.pem new file mode 100644 index 0000000000..ca4cf7ba9c --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/multipleCrlIssuerCandidates/intermediate.cert.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDQjCCAiqgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA9MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxHjAcBgNVBAMMFWlUZXh0VGVzdEludGVybWVkaWF0ZTCCASIwDQYJ +KoZIhvcNAQEBBQADggEPADCCAQoCggEBAJ6M9OSQgx20Fw14rYFeM6HQuQxBD276 +e6kXMpmdsbbkvExq5mrAWPvFGYHCmRAtH7pGm1pL91Zlgh1CbUPzwSa/Lfp9FeAX +83G7OJn0sY3kJRthtj5B0dGinXSIFCIb6gx9ICzoVpY9Ljvl4tyBr0dkGmED3MBx +SFltOMPplDhYwFekL7woNXMFIAxMnDWuS7dZ7xEpLAwNfH9D92I4lzSrQ9TrxwDP +dW2gWGvi2eu77W4YqFQgydgbKmFHAzDUTA01LNmKZkASBcLUoiLnLBMmVYgDMH4f +o4oj+2/J/OZNuGv5DK9dRCryAhnY3f8/9b8JzoPeRCmgRO9IU7ObZ/0CAwEAAaNS +MFAwHQYDVR0OBBYEFIlAkiqUVGkQL00y55tlNrfwvGTVMB8GA1UdIwQYMBaAFHQy +VMXAXOiryY9W6wOMgScvlq+rMA4GA1UdDwEB/wQEAwIB5jANBgkqhkiG9w0BAQsF +AAOCAQEAMoIJ86nzczzR41l5EFHlxGvUEQY/w7BJ42LICN3F12WPmJ+A3i/GAJSQ +14W+Jy8CXEhEFZF3R45vuOAGhOkF7igtbXeeVXunM3rmi8XIlpGjqbBZxC5w1Fd8 +IPOTArrzcF8agwthRzKOEpFSklmpUDT4MYZkdzR7TVM6TkdL+ModYFrhf9/+OFGb +qHzKUPVv+dvNaKn6JvKfQ311MKG3fLU7vyKEUNoolAnLMy3VETsnhMTk6Wa5rfzJ +eq2sdBiLxgwC3xhYk33Cla0X3hsr++Yqb8BX1ztKaRxu0PSi+KKJ9kvXAxRkFlwh +Xa7iIRXelUhftWRF/4VgDsDhWx+eDQ== +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/multipleCrlIssuerCandidates/sign.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/multipleCrlIssuerCandidates/sign.cert.pem new file mode 100644 index 0000000000..bfcfbf0242 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CRLValidatorTest/multipleCrlIssuerCandidates/sign.cert.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDQjCCAiqgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MR4wHAYDVQQDDBVpVGV4dFRlc3RJbnRlcm1lZGlhdGUw +IBcNMDAwMTAxMDAwMDAwWhgPMjQwMDAxMDEwMDAwMDBaMDUxCzAJBgNVBAYTAkJF +MQ4wDAYDVQQKDAVpVGV4dDEWMBQGA1UEAwwNaVRleHRUZXN0U2lnbjCCASIwDQYJ +KoZIhvcNAQEBBQADggEPADCCAQoCggEBALMHHzTZo1BOQkZzEZl2Q3leNfBH20Yf +O4R0l0ZBWbnpg/099ON4I8ItO0f24Wq0gs//+1adlJqeUMeUVxQ0fpu0cHQOc9h7 +CWJLnPAJjEvItZ5WXW4l8/ppo1bo4WLB1hToF42NfHgh7Laoj2gqVLWXS6Ngd8ch +VxITaxfKA9PG56dje+PlJnTNi+ayudB/O57dhoaAu+sbxBhog/7zRAV87OsH9zxc +Nuw+3ZzHhss5Lpn6F+/WDcHPyXsT7QkX6rvbRvxUOpcysXtCH3v5+ZRKyUqRPlI6 +3/hyMMZBDqYtFDHiawk587hbMp2swHF6z56d10Za22Vq9lxiX4MdftsCAwEAAaNS +MFAwHQYDVR0OBBYEFFVqj/1gRbt6YJdo1/zMvcyOmY1cMB8GA1UdIwQYMBaAFIlA +kiqUVGkQL00y55tlNrfwvGTVMA4GA1UdDwEB/wQEAwIGwDANBgkqhkiG9w0BAQsF +AAOCAQEAMsIeJp6AHJwChOEddcGu5dD/Q4R6l7dMIe3Q8g8vDVz94572jmvHIOa5 +Q/xJALRFn5rG1oC06q6Gy4ffbUm5S1dNBXdmwyfNzAa5yAwXraIWkXLPM5zFUueB +qu2ekfPhHq0NjCqhVCCYkhngaf+mqeuw8usML6mMf8o0aC6TlQu7GXm/6Z4SSKmY +wDyM4iSVR3fZHb3R/VBP7+GNKsamapZPThdxueWnm6o2vsMKSfgGHRV/41BrUqb7 +t5SXDihXCImTpUr89EL7kix42Q/BFQ60hO3LYsKn4w8gjUQffQdlB2zR6cQJx2eK +9jrkP1+J6xcuWHHrn2l9YXw6rI7r0g== +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/ca.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CertificateChainValidatorTest/ca.cert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/ca.cert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/CertificateChainValidatorTest/ca.cert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/chain.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CertificateChainValidatorTest/chain.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/chain.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/CertificateChainValidatorTest/chain.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/chainValidator.yml b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CertificateChainValidatorTest/chainValidator.yml similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/chainValidator.yml rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/CertificateChainValidatorTest/chainValidator.yml diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/expired-intermediate.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CertificateChainValidatorTest/expired-intermediate.cert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/expired-intermediate.cert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/CertificateChainValidatorTest/expired-intermediate.cert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/invalidCertsChain.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CertificateChainValidatorTest/invalidCertsChain.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/invalidCertsChain.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/CertificateChainValidatorTest/invalidCertsChain.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/not-yet-valid-intermediate.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CertificateChainValidatorTest/not-yet-valid-intermediate.cert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/not-yet-valid-intermediate.cert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/CertificateChainValidatorTest/not-yet-valid-intermediate.cert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/signChainWithInvalidNumericBasicConstraints.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CertificateChainValidatorTest/signChainWithInvalidNumericBasicConstraints.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/signChainWithInvalidNumericBasicConstraints.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/CertificateChainValidatorTest/signChainWithInvalidNumericBasicConstraints.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/signChainWithValidNumericBasicConstraints.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/CertificateChainValidatorTest/signChainWithValidNumericBasicConstraints.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/signChainWithValidNumericBasicConstraints.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/CertificateChainValidatorTest/signChainWithValidNumericBasicConstraints.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/certificationSignatureAfterApproval.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/certificationSignatureAfterApproval.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/certificationSignatureAfterApproval.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/certificationSignatureAfterApproval.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/complicatedTaggedDoc.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/complicatedTaggedDoc.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/complicatedTaggedDoc.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/complicatedTaggedDoc.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/danglingWidgetAnnotation.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/danglingWidgetAnnotation.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/danglingWidgetAnnotation.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/danglingWidgetAnnotation.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/differentFieldLockLevels.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/differentFieldLockLevels.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/differentFieldLockLevels.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/differentFieldLockLevels.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/eolNotIncludedIntoByteRange.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/eolNotIncludedIntoByteRange.pdf new file mode 100644 index 0000000000..419903479d Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/eolNotIncludedIntoByteRange.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/fieldLockChildModificationAllowed.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/fieldLockChildModificationAllowed.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/fieldLockChildModificationAllowed.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/fieldLockChildModificationAllowed.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/fieldLockChildModificationNotAllowed.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/fieldLockChildModificationNotAllowed.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/fieldLockChildModificationNotAllowed.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/fieldLockChildModificationNotAllowed.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/fieldLockKidsRemovedAndAdded.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/fieldLockKidsRemovedAndAdded.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/fieldLockKidsRemovedAndAdded.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/fieldLockKidsRemovedAndAdded.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/fieldLockLevelIncrease.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/fieldLockLevelIncrease.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/fieldLockLevelIncrease.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/fieldLockLevelIncrease.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/fieldLockRootModificationAllowed.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/fieldLockRootModificationAllowed.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/fieldLockRootModificationAllowed.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/fieldLockRootModificationAllowed.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/fieldLockRootModificationNotAllowed.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/fieldLockRootModificationNotAllowed.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/fieldLockRootModificationNotAllowed.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/fieldLockRootModificationNotAllowed.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/fieldLockSequentialExcludeValues.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/fieldLockSequentialExcludeValues.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/fieldLockSequentialExcludeValues.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/fieldLockSequentialExcludeValues.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/fieldLockSequentialIncludeValues.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/fieldLockSequentialIncludeValues.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/fieldLockSequentialIncludeValues.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/fieldLockSequentialIncludeValues.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/fullCompressionModeLevel1.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/fullCompressionModeLevel1.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/fullCompressionModeLevel1.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/fullCompressionModeLevel1.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/fullCompressionModeLevel2.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/fullCompressionModeLevel2.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/fullCompressionModeLevel2.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/fullCompressionModeLevel2.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/fullCompressionModeLevel3.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/fullCompressionModeLevel3.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/fullCompressionModeLevel3.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/fullCompressionModeLevel3.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/linearizedDoc.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/linearizedDoc.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/linearizedDoc.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/linearizedDoc.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/lockedFieldRemoveAddKidsEntry.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/lockedFieldRemoveAddKidsEntry.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/lockedFieldRemoveAddKidsEntry.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/lockedFieldRemoveAddKidsEntry.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/lockedSignatureFieldModified.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/lockedSignatureFieldModified.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/lockedSignatureFieldModified.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/lockedSignatureFieldModified.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/multipleRevisionsDocumentWithPermissions.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/multipleRevisionsDocumentWithPermissions.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/multipleRevisionsDocumentWithPermissions.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/multipleRevisionsDocumentWithPermissions.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/multipleRevisionsDocumentWithoutPermissions.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/multipleRevisionsDocumentWithoutPermissions.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/multipleRevisionsDocumentWithoutPermissions.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/multipleRevisionsDocumentWithoutPermissions.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/noSignaturesDoc.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/noSignaturesDoc.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/noSignaturesDoc.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/noSignaturesDoc.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/outlinesModified.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/outlinesModified.pdf new file mode 100644 index 0000000000..c802384f39 Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/outlinesModified.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/outlinesNotModified.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/outlinesNotModified.pdf new file mode 100644 index 0000000000..0ace1bc0ee Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/outlinesNotModified.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/pageAndParentIndirectReferenceModified.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/pageAndParentIndirectReferenceModified.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/pageAndParentIndirectReferenceModified.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/pageAndParentIndirectReferenceModified.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/pdfVersionAdded.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/pdfVersionAdded.pdf new file mode 100644 index 0000000000..844f68281b Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/pdfVersionAdded.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/removeAllAnnots.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/removeAllAnnots.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/removeAllAnnots.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/removeAllAnnots.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/removeFieldAnnots.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/removeFieldAnnots.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/removeFieldAnnots.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/removeFieldAnnots.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/removeUnnamedField.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/removeUnnamedField.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/removeUnnamedField.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/removeUnnamedField.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/removedLockedField.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/removedLockedField.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/removedLockedField.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/removedLockedField.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/signatureNotFound.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/signatureNotFound.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/signatureNotFound.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/signatureNotFound.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/simpleTaggedDoc.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/simpleTaggedDoc.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/simpleTaggedDoc.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/simpleTaggedDoc.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/taggedDocAddAndRemoveAnnotations.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/taggedDocAddAndRemoveAnnotations.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/taggedDocAddAndRemoveAnnotations.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/taggedDocAddAndRemoveAnnotations.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/taggedDocModifyAnnotation.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/taggedDocModifyAnnotation.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/taggedDocModifyAnnotation.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/taggedDocModifyAnnotation.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/taggedDocModifyAnnotationAndStructContent.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/taggedDocModifyAnnotationAndStructContent.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/taggedDocModifyAnnotationAndStructContent.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/taggedDocModifyAnnotationAndStructContent.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/taggedDocModifyAnnotationAndStructElement.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/taggedDocModifyAnnotationAndStructElement.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/taggedDocModifyAnnotationAndStructElement.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/taggedDocModifyAnnotationAndStructElement.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/taggedDocModifyStructElement.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/taggedDocModifyStructElement.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/taggedDocModifyStructElement.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/taggedDocModifyStructElement.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/taggedDocRemoveStructTreeAnnotation.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/taggedDocRemoveStructTreeAnnotation.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/taggedDocRemoveStructTreeAnnotation.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/taggedDocRemoveStructTreeAnnotation.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/taggedDocRemoveStructTreeElement.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/taggedDocRemoveStructTreeElement.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/taggedDocRemoveStructTreeElement.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/taggedDocRemoveStructTreeElement.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/twoCertificationSignatures.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/twoCertificationSignatures.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorIntegrationTest/twoCertificationSignatures.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorIntegrationTest/twoCertificationSignatures.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/addTextField.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/addTextField.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/addTextField.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/addTextField.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/addUnsignedSignatureField.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/addUnsignedSignatureField.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/addUnsignedSignatureField.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/addUnsignedSignatureField.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/brokenSignatureFieldDictionary.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/brokenSignatureFieldDictionary.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/brokenSignatureFieldDictionary.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/brokenSignatureFieldDictionary.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/catalogReferenceInRandomPlace.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/catalogReferenceInRandomPlace.pdf new file mode 100644 index 0000000000..1bea315b4d Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/catalogReferenceInRandomPlace.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/catalogReferenceInRandomPlaceModified.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/catalogReferenceInRandomPlaceModified.pdf new file mode 100644 index 0000000000..db762a13cb Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/catalogReferenceInRandomPlaceModified.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/changeExistingFont.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/changeExistingFont.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/changeExistingFont.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/changeExistingFont.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/changeExistingFontAndAddAsDss.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/changeExistingFontAndAddAsDss.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/changeExistingFontAndAddAsDss.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/changeExistingFontAndAddAsDss.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/completelyInvalidDocument.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/completelyInvalidDocument.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/completelyInvalidDocument.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/completelyInvalidDocument.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/extensionsModifications.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/extensionsModifications.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/extensionsModifications.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/extensionsModifications.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/fillInField.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/fillInField.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/fillInField.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/fillInField.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/gotoReferencesModifiedStructTreeElem.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/gotoReferencesModifiedStructTreeElem.pdf new file mode 100644 index 0000000000..03d96af0be Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/gotoReferencesModifiedStructTreeElem.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/hugeDocument.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/hugeDocument.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/hugeDocument.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/hugeDocument.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/makeFontDirectAndIndirect.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/makeFontDirectAndIndirect.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/makeFontDirectAndIndirect.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/makeFontDirectAndIndirect.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/modifyPageAnnots.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/modifyPageAnnots.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/modifyPageAnnots.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/modifyPageAnnots.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/multipleRevisionsDocument.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/multipleRevisionsDocument.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/multipleRevisionsDocument.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/multipleRevisionsDocument.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/multipleRevisionsDocument2.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/multipleRevisionsDocument2.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/multipleRevisionsDocument2.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/multipleRevisionsDocument2.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/multipleRevisionsDocument3.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/multipleRevisionsDocument3.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/multipleRevisionsDocument3.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/multipleRevisionsDocument3.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/randomEntryAdded.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/randomEntryAdded.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/randomEntryAdded.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/randomEntryAdded.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/randomEntryWithoutUsage.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/randomEntryWithoutUsage.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/randomEntryWithoutUsage.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/randomEntryWithoutUsage.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/removeAcroform.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/removeAcroform.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/removeAcroform.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/removeAcroform.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/removeDSS.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/removeDSS.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/removeDSS.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/removeDSS.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/removeField.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/removeField.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/removeField.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/removeField.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/removePermissions.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/removePermissions.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/removePermissions.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/removePermissions.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/renameField.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/renameField.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/DocumentRevisionsValidatorTest/renameField.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/DocumentRevisionsValidatorTest/renameField.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/OCSPValidatorTest/candidate1-ocsp-issuer.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/OCSPValidatorTest/candidate1-ocsp-issuer.cert.pem new file mode 100644 index 0000000000..d65da4d99c --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/OCSPValidatorTest/candidate1-ocsp-issuer.cert.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDMzCCAhugAwIBAgICEAMwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQlkx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA+MQswCQYDVQQGEwJCWTEOMAwGA1UE +CgwFaVRleHQxHzAdBgNVBAMMFmlUZXh0VGVzdE9jc3BSZXNwb25kZXIwggEiMA0G +CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCejPTkkIMdtBcNeK2BXjOh0LkMQQ9u ++nupFzKZnbG25LxMauZqwFj7xRmBwpkQLR+6RptaS/dWZYIdQm1D88Emvy36fRXg +F/NxuziZ9LGN5CUbYbY+QdHRop10iBQiG+oMfSAs6FaWPS475eLcga9HZBphA9zA +cUhZbTjD6ZQ4WMBXpC+8KDVzBSAMTJw1rku3We8RKSwMDXx/Q/diOJc0q0PU68cA +z3VtoFhr4tnru+1uGKhUIMnYGyphRwMw1EwNNSzZimZAEgXC1KIi5ywTJlWIAzB+ +H6OKI/tvyfzmTbhr+QyvXUQq8gIZ2N3/P/W/Cc6D3kQpoETvSFOzm2f9AgMBAAGj +QjBAMB0GA1UdDgQWBBSJQJIqlFRpEC9NMuebZTa38Lxk1TAfBgNVHSMEGDAWgBR0 +MlTFwFzoq8mPVusDjIEnL5avqzANBgkqhkiG9w0BAQsFAAOCAQEAlA1IOlUFvoOj +HM1VqwYmbTNUUSFpuZV9+njFCLNg6FaLDSB28uszcEzH4NhWfA8YydM+zPLwqIxg +0mOBjaeFaLgWAjPR3ejCexc4jcF6gc3hZTBx5m7i6REiDChWvodCwoa6fZ7dBDvH +3vd4Rlj/h3Ir67L7lTwI9AnBqmrQ49UhkGRHHK4RK9hHdhr1pqZnvRKjuAtApFWC +McTQYJxFIhZPdhF6fHjoozUbEtq6GrviuaYMBul306lXCd5/OzkW84CvOihgT1q7 +OtgCRuOawdMFZTqjk6OHqQ50GFhEfp3WqubYFkH7ADYNO5E8k3rWNVK08ldfKF1s +McB+a0FXzw== +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/OCSPValidatorTest/candidate2-ocsp-issuer.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/OCSPValidatorTest/candidate2-ocsp-issuer.cert.pem new file mode 100644 index 0000000000..25be340dad --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/OCSPValidatorTest/candidate2-ocsp-issuer.cert.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDMzCCAhugAwIBAgICEAQwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQlkx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA+MQswCQYDVQQGEwJCWTEOMAwGA1UE +CgwFaVRleHQxHzAdBgNVBAMMFmlUZXh0VGVzdE9jc3BSZXNwb25kZXIwggEiMA0G +CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCzBx802aNQTkJGcxGZdkN5XjXwR9tG +HzuEdJdGQVm56YP9PfTjeCPCLTtH9uFqtILP//tWnZSanlDHlFcUNH6btHB0DnPY +ewliS5zwCYxLyLWeVl1uJfP6aaNW6OFiwdYU6BeNjXx4Iey2qI9oKlS1l0ujYHfH +IVcSE2sXygPTxuenY3vj5SZ0zYvmsrnQfzue3YaGgLvrG8QYaIP+80QFfOzrB/c8 +XDbsPt2cx4bLOS6Z+hfv1g3Bz8l7E+0JF+q720b8VDqXMrF7Qh97+fmUSslKkT5S +Ot/4cjDGQQ6mLRQx4msJOfO4WzKdrMBxes+enddGWttlavZcYl+DHX7bAgMBAAGj +QjBAMB0GA1UdDgQWBBRVao/9YEW7emCXaNf8zL3MjpmNXDAfBgNVHSMEGDAWgBR0 +MlTFwFzoq8mPVusDjIEnL5avqzANBgkqhkiG9w0BAQsFAAOCAQEAte8X2bL+SorE +EK4pU75vmhr1X8W8rSNXJfy6p6m6GaigNIK4rmAu6bR9B4ai3qZNX9LE/eeKhwZu +yinLPGHema9vbG23FpHnM31mU7P3XAKprjrnrpxWBZ/dNx4IEYKtvDOKFIrR31Pt +stCOm7WXsPc8ovGQj+OnBh+lKaAy7yLNg7o8/8RxOwH9T2VbXcUBcMTnvKVsGiWa +tAiqa15EqnAEN7wAi9OpRkDKOfHdnR/bIv8CC6F3WWIwWmWcyi9st7ISv4ywtBmm +RriPwkjsBmyUu5DKBzFSfLEfnPpD1PjW+XMx0aHFuCf+HYAG8TDRkrhASwFCVb2B +6fFX5LBgew== +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/OCSPValidatorTest/ocsp/certomancer.yml b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/OCSPValidatorTest/ocsp/certomancer.yml similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/OCSPValidatorTest/ocsp/certomancer.yml rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/OCSPValidatorTest/ocsp/certomancer.yml diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/OCSPValidatorTest/ocspResponderCert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/OCSPValidatorTest/ocspResponderCert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/OCSPValidatorTest/ocspResponderCert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/OCSPValidatorTest/ocspResponderCert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/OCSPValidatorTest/ocspResponderCertForOcspTest.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/OCSPValidatorTest/ocspResponderCertForOcspTest.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/OCSPValidatorTest/ocspResponderCertForOcspTest.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/OCSPValidatorTest/ocspResponderCertForOcspTest.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/OCSPValidatorTest/ocspResponderCertWithoutOcspSigning.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/OCSPValidatorTest/ocspResponderCertWithoutOcspSigning.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/OCSPValidatorTest/ocspResponderCertWithoutOcspSigning.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/OCSPValidatorTest/ocspResponderCertWithoutOcspSigning.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/OCSPValidatorTest/rootCert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/OCSPValidatorTest/rootCert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/OCSPValidatorTest/rootCert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/OCSPValidatorTest/rootCert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/OCSPValidatorTest/rootCertForOcspTest.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/OCSPValidatorTest/rootCertForOcspTest.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/OCSPValidatorTest/rootCertForOcspTest.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/OCSPValidatorTest/rootCertForOcspTest.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/OCSPValidatorTest/signCert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/OCSPValidatorTest/signCert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/OCSPValidatorTest/signCert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/OCSPValidatorTest/signCert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/OCSPValidatorTest/signCertForOcspTest.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/OCSPValidatorTest/signCertForOcspTest.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/OCSPValidatorTest/signCertForOcspTest.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/OCSPValidatorTest/signCertForOcspTest.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/RevocationDataValidatorTest/noRevAvailCert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/RevocationDataValidatorTest/noRevAvailCert.pem new file mode 100644 index 0000000000..1b86f4122b --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/RevocationDataValidatorTest/noRevAvailCert.pem @@ -0,0 +1,18 @@ +-----BEGIN CERTIFICATE----- +MIIDijCCAnKgAwIBAgIGAZDC/HsyMA0GCSqGSIb3DQEBCwUAMDgxCzAJBgNVBAYTAkJZMQ4wDAYD +VQQKDAVpVGV4dDEZMBcGA1UEAwwQaVRleHRUZXN0Um9vdFJzYTAgFw0yNDA3MTcyMzE3MjRaGA8y +MTI0MDYyMzIzMTcyNFowPTEcMBoGA1UEAwwTaVRleHRUZXN0Tm9SZXZBdmFpbDENMAsGA1UECwwE +dGVzdDEOMAwGA1UECgwFaVRleHQwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCc9FG+ +7SqyynBdYM3sOxE8ls7lnlmNlyiHhIka7BjDlwu+7ANUta/a2xh5M3SGFJqyOQ9Z21SFyJ3/XRcQ +bvpn454ltu6QS0cusqKL3ipkF58v/shBBlxj/w+oGC+mkJiV8kKYA1n672aI04BZi0SI3dGWLxn9 +S90y6ewXYGAx+/mdPLxwtQWF67UZRfvyTSGRpRFgjSZLHrDydvp0UrbsZLFtJIsZm2kV/ALiX9Xj +BAD2ZdPa7vGfek695dOX03J/WsT/rBggRGKT9qxZMhBVzamdUV4y3bXnqcB7fPpqtVdYslBLKJaj +2XnBnfUrMUGv/DeBeK8KOjv91xBLRwczAgMBAAGjgZIwgY8wDwYDVR0TAQH/BAUwAwEB/zAPBgkr +BgEFBQcwAQUEAgUAMAsGA1UdDwQEAwIGwDATBgNVHSUEDDAKBggrBgEFBQcDCTAJBgNVHTgEAgUA +MB8GA1UdIwQYMBaAFCmDtomMMsK6Vi+UTmnCrNwKNIVBMB0GA1UdDgQWBBQpg7aJjDLCulYvlE5p +wqzcCjSFQTANBgkqhkiG9w0BAQsFAAOCAQEAQnCZWiSh43VOvCRNIo2/Iy6bNgqGEVTRpIo7c7i2 +pLBoln0LwSZq8qscba+0EZ16U6JRxpJ2qsQ1qSWCiv4OfwGDxqOKJT8EJxpR8MYjj2UVKHKPHdPI +cP2SWRNTxelVLg3A5Twgf/LhDXSUMXVmZ7oViYt/hQc37+tcmVmyHAfEkPnx0d8VQcpmS3TuF2/u +QfxtyRekPMAAmlYshwjeEGQ7tzO6QKdEvony+jSia+wnAvO/jyYVin17afwMcPYqEpQCXN0xC8QL +Im+4nIdVbeIVLkUD9wWmZyDulX6YCQwFkYqUnK9mop3nqNCYXxppKfdNYMk3MiPzPsFuCyapfQ== +-----END CERTIFICATE----- \ No newline at end of file diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/RevocationDataValidatorTest/noRevAvailCertWithoutCA.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/RevocationDataValidatorTest/noRevAvailCertWithoutCA.pem new file mode 100644 index 0000000000..fdc4799d97 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/RevocationDataValidatorTest/noRevAvailCertWithoutCA.pem @@ -0,0 +1,18 @@ +-----BEGIN CERTIFICATE----- +MIIDgTCCAmmgAwIBAgIGAZDFnFH8MA0GCSqGSIb3DQEBCwUAMDgxCzAJBgNVBAYTAkJZMQ4wDAYD +VQQKDAVpVGV4dDEZMBcGA1UEAwwQaVRleHRUZXN0Um9vdFJzYTAgFw0yNDA3MTgxMTMxMTRaGA8y +MTI0MDYyNDExMzExNFowRjElMCMGA1UEAwwcaVRleHRUZXN0Tm9SZXZBdmFpbFdpdGhvdXRDQTEN +MAsGA1UECwwEdGVzdDEOMAwGA1UECgwFaVRleHQwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK +AoIBAQCNLM4D1cmHha3WodOrf6DmKsSIDNMP/FlUXWnbIqDQ3dbeb/JwHKVe2UicPzqZq5Ees6Qq +Pg8z9TzT/YRQDQglci3v82yn3ufy5REw7dGaGzoHU/vgCeDlygRd25tbhdsLfIfedKtz0tQIbJab +0jFlvvzgrmY6Q4Pk22IF5ujQE+N/z4ft8xs5BuII8szCaAacV6MsswzqeNbfYhmnmbs+25fZD0qs +wlVsO9OjVOqLlDVQAeSIO7ip1Ws/6LBG8fAjXsPm0BX7a1MxkyDsrUUFWfq3Pz2aK7DW1F34MPWE +YX0LAFIP269fG+S91fVtrw8b7b8WBQxWi8jv4OOl6kkTAgMBAAGjgYAwfjAPBgkrBgEFBQcwAQUE +AgUAMAsGA1UdDwQEAwIGwDATBgNVHSUEDDAKBggrBgEFBQcDCTAJBgNVHTgEAgUAMB8GA1UdIwQY +MBaAFCmDtomMMsK6Vi+UTmnCrNwKNIVBMB0GA1UdDgQWBBQpg7aJjDLCulYvlE5pwqzcCjSFQTAN +BgkqhkiG9w0BAQsFAAOCAQEAK93ANxcNwQCqM/ZDqcpkHtk+fXcKFLgSkpAQWxWjxEeumlRD61Yi +8dJ6VfIy95Flh4Kbg6EH1UsrkiquOQ2+k/V1oE5hJu7RT7RqSDu3VCcMAtekRwdfY6AGCX/9IHqE +CazzShdcCr/YZ2jz3Uy/kr6/fu4sq1enAunsM6WMuO7bZU/WYimzHu9TTRQ00oFjCW5s3TFgP3HV +BfaL4oSh7Ksvjsu2ZqjwFb8J5DT/oObIdeAw/Pl3NShjALbQ5PJkzkLp00FcT4A1ItKkW+p/xwPk +QCR2NnYjIk9yvhFgse5/VrYkNlJEknzN4upJ2ldVCC2F5yVyQ+mG7b8l7MgEKA== +-----END CERTIFICATE----- \ No newline at end of file diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/RevocationDataValidatorTest/ocspResponderCert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/RevocationDataValidatorTest/ocspResponderCert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/RevocationDataValidatorTest/ocspResponderCert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/RevocationDataValidatorTest/ocspResponderCert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/RevocationDataValidatorTest/rootCert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/RevocationDataValidatorTest/rootCert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/RevocationDataValidatorTest/rootCert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/RevocationDataValidatorTest/rootCert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/RevocationDataValidatorTest/signCert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/RevocationDataValidatorTest/signCert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/RevocationDataValidatorTest/signCert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/RevocationDataValidatorTest/signCert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/RevocationDataValidatorTest/trustedOcspResponderCert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/RevocationDataValidatorTest/trustedOcspResponderCert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/RevocationDataValidatorTest/trustedOcspResponderCert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/RevocationDataValidatorTest/trustedOcspResponderCert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/RevocationDataValidatorTest/validityAssuredSigningCert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/RevocationDataValidatorTest/validityAssuredSigningCert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/RevocationDataValidatorTest/validityAssuredSigningCert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/RevocationDataValidatorTest/validityAssuredSigningCert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/certs/SHA256withRSA.cer b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/certs/SHA256withRSA.cer new file mode 100644 index 0000000000..fbaad2b382 Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/certs/SHA256withRSA.cer differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/certs/SHA256withRSA.key b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/certs/SHA256withRSA.key new file mode 100644 index 0000000000..d7e9b5e825 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/certs/SHA256withRSA.key @@ -0,0 +1,51 @@ +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQdOaEUfD0sZWtUR11 +xwgn0gICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEBaNXSfwUjF5SS7n +ce1JFoUEggTQ6eV+IsckiVP7I9VTldLkpP5OKB8brmw5t20fO11HyCnqkkhooR2b +t2fBj4fWv0IRUe266L+fVs7AOngjkWfezEvGR6nte4pNXEFrOwt/U8A6IYZXBdA5 +dvqs6VMPHbjQ8CufVLGvksuYFQVRcGy0rk1DH2Of44GU4X0GtROlFFJnkmfZhVPS +Hx2MXXGQ02Ko1i1eKoEGgvmSAsDcPijiX96DKlQZJ4YMtI/8rRsdvNJsJ2beyZDa +T3aJMmSSBF92mS2dtS21DwjzEu8utquguYA0KYzjZM9onOuBEEUifam8Fjnvlui6 +beQJya4zldoA6QZPSd2PUAP6l1U/d8UXqcisjzArDZDmRu58dPxn4rs0NgTOIO8h +fEUIvfS+wuknff1b/wdGnwXkXoeSrrjS9dhP9KVU1SJ/FWKc6BY+P+JmE5vLjAtn +AmbyZhXY0jX7ZHFh0z0y1y1fTIXL1aj4iB+cUwhJ1ZdlGkT5HdG4ts/oTGCnpB6O +F1GvGyhprmtjp/dspLH5ha0I+4aTn46yFpnBNyg8w9c2+xj8Jiqy9J/ppVtPdhxt +wrE1/ThUGIWUTsbGbLW87WIrZq6IlSGtztbxAMYxXoe4solYueE3pI3eYFzgnBcq +T6Byktr71gt9AGD/N/p+Kk5RM4JT8XpQjLjz9TlmsGpJzUoBGeG6KFLsqqLLSD+0 +c5lAGWsFhec3uCu4fCyBqxpQc0y5j2bgUiTRGYn1NOdyZg+ERO/aWGfkDOAtlL1i +B79NGIBxIXgt508g83UeaQC6KjuG/8hPY6UHmU5mlgRT9H5jvkSX3mEtl1Gdk2y0 +M5pZTTrhbG4p66GhBi8vM5tQfiBoLUKEM/kgiGXPC6Kob42nb3ufP0rmnKklcDGC ++898hW5ge+VNmOkHpVuV5ZD9aWUSVEU4+8QNZj8pcyL0GXFyEL/HxNxUESdz3k0S +bInuxO49mgGPjBqtx5ZvaxyWFnzOp6rmHZUHymejxxdnlnTnSnXKkJFjcm7n0sKO +575ofHtk0OdqIK6YiPgfeF6nZkIg3C0PbReZ05kTplrW182ZWuQQyJgv+RPzF4+9 +5rCe67nJhJrt7hXFRsUScHXNj+HF9Av8WR2RnHTRbpQBJszijM+Xgl+VeYcY5ckB +fk+AfcR9r0Jud4O9795OOWVxWqGVu/b1RGonfjMkGW+JdnZL0vkOYYcHt4iMZmzW +M0ZowZPGO5dFBV7/ZkVzb0fexw+f+E0lUBEK1cx0gxnzjmcGJO+C9if1uIEfwpon +3wBOTDsU7XKDx9v6ibcDMOXrZa+rcJWxgNkXt5nRpozZkddYctBkehGu+snV2g4n +SdOwr0eIVv/L+v4IywZmeWWEVnbSAvB0p7nB89bgLMr9tV0ly7MWxPH+gPnNJ1gE +7Mp3AgN5BxEmLfW3+ou3QLoqnOS2MCw/xcgLP0nJACSPI7/nWy95iKXKgkCkAgF9 +4Ztk7uBG4tiK14KcKq8ToCW2YNliT3g0CWjBLtVPUS6qboudMiuedxTxE8WEirpT +A77nfDNg4MVjl4kP9jhV0Phpn9rDMJ2jw0BqFc1Vou4aNDXYandAFJea44Wce9H+ +qAowcrfsWehD01HBQ2KwWVg3sLnwwBHw0nvbATS41hdxsP2OmCnxWkc= +-----END ENCRYPTED PRIVATE KEY----- +-----BEGIN CERTIFICATE----- +MIIDfzCCAmegAwIBAgIEUFic9zANBgkqhkiG9w0BAQsFADBvMQswCQYDVQQGEwJU +UzETMBEGA1UECBMKVGVzdCBTdGF0ZTESMBAGA1UEBxMJVGVzdCBUb3duMREwDwYD +VQQKEwhUZXN0IG9yZzEQMA4GA1UECxMHVGVzdCBPVTESMBAGA1UEAxMJVGVzdCBV +c2VyMCAXDTE0MDkyMjA5MTExMVoYDzIxMTQwODI5MDkxMTExWjBvMQswCQYDVQQG +EwJUUzETMBEGA1UECBMKVGVzdCBTdGF0ZTESMBAGA1UEBxMJVGVzdCBUb3duMREw +DwYDVQQKEwhUZXN0IG9yZzEQMA4GA1UECxMHVGVzdCBPVTESMBAGA1UEAxMJVGVz +dCBVc2VyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA+6g5sYzXiNOA +hR7C8wc8buxU/JgcbdHpHIR44iuXjpepBYAE7hRsWM7H4cuXrKiRxS9UMOadqkGF +Qqb5sG6lo2UUhcj4qlN6hKDc/+AMZMIW1mvQldiygCAkqgM8iso+kw56dpVuerG/ +k1nd8f+X9rjXN6/DIMznZcMy2d9ByIFuixFKElPvOWx9q9N4aiueOd5FM5eHxp+3 +F4uCTrpM5zkS7Rmf5GVtCofc8KgaTLLp4D0Ge5VUJm7yW8fuU3eIpin4ivjk+Gye +Q3t0BsrmNyQy3CmKGOBP/vX0+wEMvGN2xqNgAFP9dxA+AbJMiAfsmoWvxXaPktqC +DOspTCFqbwIDAQABoyEwHzAdBgNVHQ4EFgQUILviRCmSrhuLDmF0nus4pv2uu7gw +DQYJKoZIhvcNAQELBQADggEBAGnfGYL7nDm5taDPRxuGGMqUPwRnH2bXwef6S2Xb +/nIEFtNheVFQFtKNn5Ikq68DTFMP06yXLnI7F40+ZiQezRBB1EPPmDL2fYKc9fL1 +SHntu6HLgP/Y5nnCVegtL8l9745gQZnnXlMtkTs2HFwffznIHW/3STO0Bcj0+KMa +p8vebMjmvV7bZEGvrcrVXL55QPZXJwRuQMXJB3f5XhAEH1VqAhTW6DrvBUnuESwo +9fxxA5gmblt80SQYdKr2I08OTk0qmyF8zNuffTOiSS8/V6Cf7CntuPWjSuVf1EVP +MH6KkSjceLZ99Y7bvl7KKvQ4Kj5Bp27PwlRvtYbfCUmQEG8= +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/certs/rootCertKey.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/certs/rootCertKey.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/certs/rootCertKey.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/certs/rootCertKey.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/certs/rootRsa.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/certs/rootRsa.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/certs/rootRsa.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/certs/rootRsa.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/certs/root_cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/certs/root_cert.pem new file mode 100644 index 0000000000..9e88d77c4c --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/certs/root_cert.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDSzCCAjOgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx +DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw +MTAwMDAwMFoYDzI1MDAwMTAxMDAwMDAwWjA1MQswCQYDVQQGEwJCRTEOMAwGA1UE +CgwFaVRleHQxFjAUBgNVBAMMDWlUZXh0VGVzdFJvb3QwggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQCu7i/J0WEuTz8rwYTkQsAAwarnoiSYxEdolqz2b5jl +nSDjPs0uifW2bChiWWkGMeHgAtXl6NsaCaSR7UvgzZ2ah1PtyJ4IaYEG5uXsPH8L +X+m5BHt9RmplVYIYPFejb6ffdtpeCnwk7EPpd6UAc1WbFA6WwyEOG0D6HvjTRjW4 +OOIn48XVN8HzpGMvO9Afz5tunPuDCxhcdNGMn6BvBHJ9fLcl5xbyzURwUm4cE35V +q2RzbFfxsOh3saU2FHYY9w7Vh6VcOPPlP1RMARVP9KLt36mQlLfgPxW4xU3v97Ji +6NmkB7rbEi58jtrLs6T0FEPGkf2YFU451mFFqeVnLfh/AgMBAAGjYzBhMB0GA1Ud +DgQWBBTJedkaWwgZlvir4jCx+E02XFK+RjAfBgNVHSMEGDAWgBTJedkaWwgZlvir +4jCx+E02XFK+RjAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB5jANBgkq +hkiG9w0BAQsFAAOCAQEAQ+M7mqNO3sLxIM+TzG2tHIgKPke5Bju1s+/tk6b8rY65 +9CLYNtQYakturcq5ApjOk/1WvPEcypiRze6Jy+i6/38Fi0VeRi6fN0z4EMa7/6lL +P63QTkZ1BRI9OiP+p0dOCY2hUyjOvJ9mEJH1H6rFLONwgKIWInIBFh9zIkE7Qn98 +G/1+ebUXGkarlENknUcgMWgG0B9lSroC+as0TPt3N2HnYYoUIg8iIIk2kEan8iwx +n3FKAKDDHWB+9B1H49yY5YwGjXNo7XJsk6hmR97CMRmnKLnlaklKu4l2C2E/mnDb +6Mq9vMmwK6+VJZB75423I/7WvsX9QvNK+kti/xNIpg== +-----END CERTIFICATE----- \ No newline at end of file diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/certs/short_validity_root_cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/certs/short_validity_root_cert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/certs/short_validity_root_cert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/certs/short_validity_root_cert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/certs/signCertRsa01.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/certs/signCertRsa01.pem new file mode 100644 index 0000000000..5f2f1f25a8 --- /dev/null +++ b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/certs/signCertRsa01.pem @@ -0,0 +1,76 @@ +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQgLsVp4wmljjCRgEy +kw2LWgICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEELyxbQ1T8vAMXX6t +md0GgdwEggTQXjePuN2mrJ4C7uFP/ErLys5cwO7QSOL5z7jUUep96YkZgMjau99o +6JolOHyJRzDbUNbTCfku8PqwDfdPrCPfMZ+e9UU/Y5uVZbEL+UtIkcH/uyFCd1k7 +AVOhAux7KZwgHlq66iUHqTQFd58Ly7KOoMKGZS07CtIxjYluFZZbx44EZrgqRwEa +ZAbIsdR2xZ092Who4CzkuF31m2TuyzfYir7kocJsdQU6k9OdptfJRda2UpZiUXW8 +GMg/qvF7RwkAbfu7gLkcmc5FETlY+E3P8tYDutN737wnd/VqO9Bd25umOAl3CHUA +5+YSXvWOSuAJjz7kEI2DEG/ov//oO0wohJPLKRF7jUI2WbIwCAypPZPvSS506ulO +ofuLTY0+Jii0ZO5SyC4Uu90lh8RISvi9RzRx2G4sN+gyeCBBg1R1f5IRNeBImpEw +aKqk4VrcUrLe623Z3el1Z8ErJBJ6G0ZV/EAFC7dmpTknrVOFzdO6sohtnHygm0Ce +h5QdqiWvb0QKHv3GZumdtCcdh8vPMRT1PEWVvfV/cyIOc5BH6sYNtxiohosl6DLz +I84vj3n8I+cFHrYIFCtghy9iZJ0GvvPxaiJCS5A+eDiOO3rhk3ZMkmTlVCpOBiY2 +QKdljhmRaN1Y6XfQ8SRNmr/qVfwFJ4JgYnk3VVHVvzt0EvEImNusOvTH2U4zMryP +FRhgGNIL0f5gflo2LxSPqsnqNfJLRHCmXkYeB4Pu8/xv6biFqtwC2UBaL7FCjIgY +NI+hi9Mt9fJpYqF4XGHcT2b6Aq7otgxX+5iiQg10bEjqI/gcZrFvBvmz/97OBe7X +BFa5F8nYeSxnr5XQiJ04oBVBjdvAFeS7ZZ4Quq2beEgcgCj7EU/OXLLHwBCCmD8s +8kgkhsv7+sPtNnC1YeoW6xHezt/FSDYxS1lPWsnr4AE4jpxOJgM8CNSDq0E52e83 +2uDNm3gIo133RRn9V8gNQzfIJv1BZFRUtOn9CRxrJBTptSxUJX1at+btTM7hlY2z +MwXM5i7ZGDVQOPSpKrlbmA8bHDRHeGryXz0HNWs5RWiTVSEhCuVTrrlQG4nmbhVm +b6xbd/DWs3NdEXwLLdg1W+fbeS2qIJtJqu0LU+PcGkhaVXeobc6MFGw06hDVtVg9 +Hm1/AZJ4OuD/+GyH9ku4Z9tPDh4NmXsVVV8CpzxRJ37gLrGPwbxXwW3v6B6NBRvz +W8KuWQjlNDxVcFb9Si7Mj81xX2k1818hwSm3iEQIwT0Q7BNUj3oJhTsNlB/Id79J +tl7AKam1ofDZVmU7gPcv0FPKxhEZIyjoqeAzLGuW1Hmp45HbJ94tL2uvbgPq2Mj7 +j4jllaPoN9J1QBVDHBqEzLZGeWKZYK2L9Sw4SdkZjLp96hxoQ7MYvTrsX4eSV0HH +xMLp5hhIiM8zGIsMYlwcfOSpQh/H1AnbiQIJ0/tzO6uBZ73fq59rTReRf+PtXqqT +5vg89nN6kNvJcrwNLyEhdC7uaqsoimTMi59BE36ZZcL0jHKMmPl9g/vbPj9CiRdu +B0+4lQD0hAqK6FVfl6ENpj4zLdU6/EER5L7v+Syv8d5AeFtdKrqxH3oCGPXmXCol +j2rALoIlZt0D+jjmcDo6C32qtu8w40zBD/+J8iZXVWC/U9cauP00N9E= +-----END ENCRYPTED PRIVATE KEY----- +-----BEGIN CERTIFICATE----- +MIID6TCCAtGgAwIBAgIEWOew7DANBgkqhkiG9w0BAQsFADBUMQswCQYDVQQGEwJC +WTEOMAwGA1UEBwwFTWluc2sxDjAMBgNVBAoMBWlUZXh0MQ0wCwYDVQQLDAR0ZXN0 +MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTE3MDQwNzE1MzM0MFoYDzIxMTcw +NDA3MTUzMzQwWjBZMQswCQYDVQQGEwJCWTEOMAwGA1UEBwwFTWluc2sxDjAMBgNV +BAoMBWlUZXh0MQ0wCwYDVQQLDAR0ZXN0MRswGQYDVQQDDBJpVGV4dFRlc3RSc2FD +ZXJ0MDEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCfr2PnZ6DjvrSY +g0cWtDR6drgvCowB5hQH7CHSAMTeVGZxUOBT1ylfxySioRU4ckq3uQu7jOe7Te6Y +xEenjFhTv8bT0/ZrL2w6OGBH4iUs3Kwx5jzbRHPuZt7+gCKLBXhRH6ytDnbTHNgT +4tjGXUmGa4sMbal1mXvKN/xaK+hGDskRW6cHZq7ZtdgfM8yBQWZzshAz7dQepmUH +ZYWxplTwJ8cuVLqjgXMXWfTatio6yYwf+5AkWszBcCA6oxm16wN2pLUeNx5aBLiF +Dhtj6qqHLwN/7tPb0ojqXRU3AfocC2y8a4WeVOOp2du0ja4E9P7IQNKiBBlOfNcF +D700qPFpAgMBAAGjgbswgbgwCQYDVR0TBAIwADB/BgNVHSMEeDB2gBRdKnF1rt3Y +vlm6ILFmkcl2NlNc7qFYpFYwVDELMAkGA1UEBhMCQlkxDjAMBgNVBAcMBU1pbnNr +MQ4wDAYDVQQKDAVpVGV4dDENMAsGA1UECwwEdGVzdDEWMBQGA1UEAwwNaVRleHRU +ZXN0Um9vdIIEWOeR1jAdBgNVHQ4EFgQUz41Jo8H/HAqxhMN/inuhKuLZU8gwCwYD +VR0PBAQDAgXgMA0GCSqGSIb3DQEBCwUAA4IBAQCT597xhkVzrYP7NudRgIZCDwT3 +TDnL+Xv8H4c9p+CdHJtFMoxAQlzcQi4uEIo5nfBKMEXK0d1OnO8zEBfK98EPahUI +++PDnNk82kh64CbZQ95Ms1Usq1XGd31bkXWWRM3LY2P7VG0nR+eLutVAClIcbTLN +yL9ZhiL33jCk1W5PeXJy13kL3XV/Awt8zb9fcinkuXkV5LoZHxh2Ob19R//5fGxH +hnUywReGptnIbEPiWGYyX1QCQeOqi3vmqZaGr+RZfF8+zqtSP5p4gFpryuTJxkcZ +UOeroaBv3sHCI9rtzcwZPYsW0BroFliEhNIDq5HxJgdwdu6uDOMMrC2QxB17 +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIID6jCCAtKgAwIBAgIEWOeR1jANBgkqhkiG9w0BAQsFADBUMQswCQYDVQQGEwJC +WTEOMAwGA1UEBwwFTWluc2sxDjAMBgNVBAoMBWlUZXh0MQ0wCwYDVQQLDAR0ZXN0 +MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTE3MDQwNzEzMjAwMVoYDzIxMTcw +NDA3MTMyMDAxWjBUMQswCQYDVQQGEwJCWTEOMAwGA1UEBwwFTWluc2sxDjAMBgNV +BAoMBWlUZXh0MQ0wCwYDVQQLDAR0ZXN0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290 +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz/fz7iq1wzhMMYcGfmMm +teCY/ZtdE26PB1OTTBuDSN86sVNmur5FV/mLPU9ZK2ofrs+wMrqn0agmFlRl4dTh +f5u5WSEQ/ARwXzYOn2uEkwR/0dwwZUL3VWhrPSD5SxX5MzFo8UXTNlXW2bClLC0F +QU2qLjIwwRFwwWDSQPR8r/Mv181RljVpEjPk6DfkDtHWWA4daGlQU0nXbuZszplv +iPafXmyKn+2w4G9Jw/8pHIK2VhWYstLI+bUZk662ZVldNvnpMyHn12FfB0Nbf/Z6 +V2WTGviEr8EEE2cA7I+H7ZGUDzug7umNCCJn3ilC6vAt9i9OLaZRDh6jPMOjMUiz +TwIDAQABo4HBMIG+MA8GA1UdEwEB/wQFMAMBAf8wfwYDVR0jBHgwdoAUXSpxda7d +2L5ZuiCxZpHJdjZTXO6hWKRWMFQxCzAJBgNVBAYTAkJZMQ4wDAYDVQQHDAVNaW5z +azEOMAwGA1UECgwFaVRleHQxDTALBgNVBAsMBHRlc3QxFjAUBgNVBAMMDWlUZXh0 +VGVzdFJvb3SCBFjnkdYwHQYDVR0OBBYEFF0qcXWu3di+WbogsWaRyXY2U1zuMAsG +A1UdDwQEAwIB9jANBgkqhkiG9w0BAQsFAAOCAQEAdhby6EaopoUF8j7oR44Mhe/N +3y9hzGb/zLmmgTavPd2plv6NlAPt9W+8rezKO6jQCsBRFw8JY+Lx6j3W0K6rWigB +pPGU/B/0bXLlOIv2a4uW8nBmq6jxAe5Xbtwm8HcKOOLMzxPIChHJIJy5NWw9ArD4 +Ul+FEt/VuEW1NfPZm1U5ixMOrBfn0C8pxIX4+VSHN9I8WoFjSfYX4Y3ldRLTeqxQ +rhZQlbhGNymp3Kcvtuq5At6vopskyB8Q1b7L4e+hRWK2prz/7p4Bdhu2TmkEfWZc +YKpgrkVFqa/Z1uZ0q4KVBOP3cyaQmqRXTV37SfpNyHAJdol5ueF68VVVNZFRXw== +-----END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/certs/trustedCerts.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/certs/trustedCerts.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/certs/trustedCerts.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/certs/trustedCerts.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/certs/ts_root_cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/certs/ts_root_cert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/certs/ts_root_cert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/certs/ts_root_cert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/certs/validCertsChain.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/certs/validCertsChain.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/certs/validCertsChain.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/certs/validCertsChain.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/encryptedDoc.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/encryptedDoc.pdf new file mode 100644 index 0000000000..e4563ea8d0 Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/encryptedDoc.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/encryptedPublicKeyDocTest.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/encryptedPublicKeyDocTest.pdf new file mode 100644 index 0000000000..929f7454d5 Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/encryptedPublicKeyDocTest.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/revDataInTheSignatureContainer.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/revDataInTheSignatureContainer.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/revDataInTheSignatureContainer.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/revDataInTheSignatureContainer.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/revDataInTheSignerInfo.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/revDataInTheSignerInfo.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/revDataInTheSignerInfo.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/revDataInTheSignerInfo.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/shortValidityCertsWithCrl.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/shortValidityCertsWithCrl.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/shortValidityCertsWithCrl.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/shortValidityCertsWithCrl.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/shortValidityCertsWithOcsp.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/shortValidityCertsWithOcsp.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/shortValidityCertsWithOcsp.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/shortValidityCertsWithOcsp.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/signatureSigningCertExpired.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/signatureSigningCertExpired.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/signatureSigningCertExpired.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/signatureSigningCertExpired.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/timestampSignatureDoc.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/timestampSignatureDoc.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/timestampSignatureDoc.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/timestampSignatureDoc.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/validDoc.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/validDoc.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/validDoc.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/validDoc.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/validDocWithTimestamp.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/validDocWithTimestamp.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/validDocWithTimestamp.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/validDocWithTimestamp.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/validDocWithoutChain.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/validDocWithoutChain.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/validDocWithoutChain.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/validDocWithoutChain.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/validateSingleSignature1.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/validateSingleSignature1.pdf new file mode 100644 index 0000000000..218e5a36cb Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/validateSingleSignature1.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/validateSingleSignature2.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/validateSingleSignature2.pdf new file mode 100644 index 0000000000..fe7b0c6a0d Binary files /dev/null and b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorIntegrationTest/validateSingleSignature2.pdf differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/certs/rootCertKey.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorTest/certs/rootCertKey.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/certs/rootCertKey.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorTest/certs/rootCertKey.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/certs/timestamp.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorTest/certs/timestamp.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/certs/timestamp.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorTest/certs/timestamp.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/certs/validCertsChain.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorTest/certs/validCertsChain.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/certs/validCertsChain.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorTest/certs/validCertsChain.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/docWithBrokenDss.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorTest/docWithBrokenDss.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/docWithBrokenDss.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorTest/docWithBrokenDss.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/docWithBrokenTimestamp.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorTest/docWithBrokenTimestamp.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/docWithBrokenTimestamp.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorTest/docWithBrokenTimestamp.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/docWithDss.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorTest/docWithDss.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/docWithDss.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorTest/docWithDss.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/docWithMultipleSignaturesAndTimeStamp.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorTest/docWithMultipleSignaturesAndTimeStamp.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/docWithMultipleSignaturesAndTimeStamp.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorTest/docWithMultipleSignaturesAndTimeStamp.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/modifiedDoc.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorTest/modifiedDoc.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/modifiedDoc.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorTest/modifiedDoc.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/modifiedDocTimestampDate.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorTest/modifiedDocTimestampDate.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/modifiedDocTimestampDate.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorTest/modifiedDocTimestampDate.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/signatureWithModifiedTimestampDate.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorTest/signatureWithModifiedTimestampDate.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/signatureWithModifiedTimestampDate.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorTest/signatureWithModifiedTimestampDate.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/timestampSignatureDoc.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorTest/timestampSignatureDoc.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/timestampSignatureDoc.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorTest/timestampSignatureDoc.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/validDoc.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorTest/validDoc.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/validDoc.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/SignatureValidatorTest/validDoc.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/ValidationMetaInfoEventsTest/multipleRevisionsDocument.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/ValidationMetaInfoEventsTest/multipleRevisionsDocument.pdf similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/ValidationMetaInfoEventsTest/multipleRevisionsDocument.pdf rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/ValidationMetaInfoEventsTest/multipleRevisionsDocument.pdf diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/BasicConstraintsExtensionTest/basicConstraints10Cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/BasicConstraintsExtensionTest/basicConstraints10Cert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/BasicConstraintsExtensionTest/basicConstraints10Cert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/BasicConstraintsExtensionTest/basicConstraints10Cert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/BasicConstraintsExtensionTest/basicConstraints5Cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/BasicConstraintsExtensionTest/basicConstraints5Cert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/BasicConstraintsExtensionTest/basicConstraints5Cert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/BasicConstraintsExtensionTest/basicConstraints5Cert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/BasicConstraintsExtensionTest/basicConstraintsFalseCert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/BasicConstraintsExtensionTest/basicConstraintsFalseCert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/BasicConstraintsExtensionTest/basicConstraintsFalseCert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/BasicConstraintsExtensionTest/basicConstraintsFalseCert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/BasicConstraintsExtensionTest/basicConstraintsMaxCert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/BasicConstraintsExtensionTest/basicConstraintsMaxCert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/BasicConstraintsExtensionTest/basicConstraintsMaxCert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/BasicConstraintsExtensionTest/basicConstraintsMaxCert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/BasicConstraintsExtensionTest/basicConstraintsNotSetCert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/BasicConstraintsExtensionTest/basicConstraintsNotSetCert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/BasicConstraintsExtensionTest/basicConstraintsNotSetCert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/BasicConstraintsExtensionTest/basicConstraintsNotSetCert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/CertificateExtensionTest/keyUsageNotSetCert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/CertificateExtensionTest/keyUsageNotSetCert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/CertificateExtensionTest/keyUsageNotSetCert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/CertificateExtensionTest/keyUsageNotSetCert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/CertificateExtensionTest/keyUsageSeveralKeys1Cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/CertificateExtensionTest/keyUsageSeveralKeys1Cert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/CertificateExtensionTest/keyUsageSeveralKeys1Cert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/CertificateExtensionTest/keyUsageSeveralKeys1Cert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/ExtendedKeyUsageExtensionTest/extendedKeyUsageAnyUsageCert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/ExtendedKeyUsageExtensionTest/extendedKeyUsageAnyUsageCert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/ExtendedKeyUsageExtensionTest/extendedKeyUsageAnyUsageCert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/ExtendedKeyUsageExtensionTest/extendedKeyUsageAnyUsageCert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/ExtendedKeyUsageExtensionTest/extendedKeyUsageNoSetCert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/ExtendedKeyUsageExtensionTest/extendedKeyUsageNoSetCert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/ExtendedKeyUsageExtensionTest/extendedKeyUsageNoSetCert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/ExtendedKeyUsageExtensionTest/extendedKeyUsageNoSetCert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/ExtendedKeyUsageExtensionTest/extendedKeyUsageOcspSigningCert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/ExtendedKeyUsageExtensionTest/extendedKeyUsageOcspSigningCert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/ExtendedKeyUsageExtensionTest/extendedKeyUsageOcspSigningCert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/ExtendedKeyUsageExtensionTest/extendedKeyUsageOcspSigningCert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/ExtendedKeyUsageExtensionTest/extendedKeyUsageSeveralValues1Cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/ExtendedKeyUsageExtensionTest/extendedKeyUsageSeveralValues1Cert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/ExtendedKeyUsageExtensionTest/extendedKeyUsageSeveralValues1Cert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/ExtendedKeyUsageExtensionTest/extendedKeyUsageSeveralValues1Cert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/ExtendedKeyUsageExtensionTest/extendedKeyUsageSeveralValues2Cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/ExtendedKeyUsageExtensionTest/extendedKeyUsageSeveralValues2Cert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/ExtendedKeyUsageExtensionTest/extendedKeyUsageSeveralValues2Cert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/ExtendedKeyUsageExtensionTest/extendedKeyUsageSeveralValues2Cert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/ExtendedKeyUsageExtensionTest/extendedKeyUsageTimeStampingCert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/ExtendedKeyUsageExtensionTest/extendedKeyUsageTimeStampingCert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/ExtendedKeyUsageExtensionTest/extendedKeyUsageTimeStampingCert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/ExtendedKeyUsageExtensionTest/extendedKeyUsageTimeStampingCert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/KeyUsageExtensionTest/keyUsageDecipherOnlyCert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/KeyUsageExtensionTest/keyUsageDecipherOnlyCert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/KeyUsageExtensionTest/keyUsageDecipherOnlyCert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/KeyUsageExtensionTest/keyUsageDecipherOnlyCert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/KeyUsageExtensionTest/keyUsageDigitalSignatureCert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/KeyUsageExtensionTest/keyUsageDigitalSignatureCert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/KeyUsageExtensionTest/keyUsageDigitalSignatureCert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/KeyUsageExtensionTest/keyUsageDigitalSignatureCert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/KeyUsageExtensionTest/keyUsageKeyCertSignCert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/KeyUsageExtensionTest/keyUsageKeyCertSignCert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/KeyUsageExtensionTest/keyUsageKeyCertSignCert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/KeyUsageExtensionTest/keyUsageKeyCertSignCert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/KeyUsageExtensionTest/keyUsageNotSetCert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/KeyUsageExtensionTest/keyUsageNotSetCert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/KeyUsageExtensionTest/keyUsageNotSetCert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/KeyUsageExtensionTest/keyUsageNotSetCert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/KeyUsageExtensionTest/keyUsageSeveralKeys1Cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/KeyUsageExtensionTest/keyUsageSeveralKeys1Cert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/KeyUsageExtensionTest/keyUsageSeveralKeys1Cert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/KeyUsageExtensionTest/keyUsageSeveralKeys1Cert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/KeyUsageExtensionTest/keyUsageSeveralKeys2Cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/KeyUsageExtensionTest/keyUsageSeveralKeys2Cert.pem similarity index 100% rename from itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/extensions/KeyUsageExtensionTest/keyUsageSeveralKeys2Cert.pem rename to itext.tests/itext.sign.tests/resources/itext/signatures/validation/extensions/KeyUsageExtensionTest/keyUsageSeveralKeys2Cert.pem diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlAndSignCertRootIssuerMismatch/chain.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlAndSignCertRootIssuerMismatch/chain.pem deleted file mode 100644 index 07a850f63e..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlAndSignCertRootIssuerMismatch/chain.pem +++ /dev/null @@ -1,103 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDSzCCAjOgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw -MTAwMDAwMFoYDzI1MDAwMTAxMDAwMDAwWjA1MQswCQYDVQQGEwJCRTEOMAwGA1UE -CgwFaVRleHQxFjAUBgNVBAMMDWlUZXh0VGVzdFJvb3QwggEiMA0GCSqGSIb3DQEB -AQUAA4IBDwAwggEKAoIBAQDP6KUmxQzeXKuwodaQZ7IUoidvDeXWrjW7BNYmKhey -DX9SIeIwvuiKDVUD85pWyk6jhNUvQaYvGVOv/Pbu4NJHv9FKch2d9759ckMT+MXG -fGk/B6Ww1rlKsiHccWizQxah7R79eGweEvryPIx+hqxreCBH4yzMPjHld1C34/vC -nUGmozKT4KENiT6lXXiBm4D+u3siCPt1Gzxavvm2MUBTHBbhQ3/n1eS/FcqT4NhI -vXDpPiNouD9goI+4LwCW7b52dg7dXreQY/IfGCcHTcu7YK/OEW4Pqjpr13B5mEDS -DsCqrStoh8EQ+jB62n2Xv8TT4lQju/sZh0l65IiT8fUfAgMBAAGjYzBhMB0GA1Ud -DgQWBBRkxUEzwLkf0rdu5Txco5JSsf8WCzAfBgNVHSMEGDAWgBRkxUEzwLkf0rdu -5Txco5JSsf8WCzAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIC5DANBgkq -hkiG9w0BAQsFAAOCAQEARJOOUQkv9AgqElJmQjGDkRdJPxkDHZtRLGOk9p0E1KbL -lqQQdgzL7RuE4vfCROan6aBZmXFRviIPg/Gxw2hDSIv1NUZv3AIgM2b9+3y+4SQ6 -2a/sqh1JPLxwnLN+Mo5KwY/E/YlJ0N7rw3AONrLlqH89BRrBIiPjrg74zi6qPzGn -WB2awHsbl7AOtkD2dEud7lbyLda/hCw2RGPSBQMm50pWsuInWXzdtX/Ii9yTGMyD -kavUHX6DDVouZBSKOjmChP0fGPM17ORJNR92RbT2ygy+F0Zokh5XUgrKPr4/JTW5 -iIkycpjAXY9UEMfi8pFnnzVSRj65kkZvZZJzybelMQ== ------END CERTIFICATE----- ------BEGIN CERTIFICATE----- -MIIDQjCCAiqgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw -MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA9MQswCQYDVQQGEwJCRTEOMAwGA1UE -CgwFaVRleHQxHjAcBgNVBAMMFWlUZXh0VGVzdEludGVybWVkaWF0ZTCCASIwDQYJ -KoZIhvcNAQEBBQADggEPADCCAQoCggEBAM3t0dlZupS+5Z0EGHsnruz2ZRoVKwbp -IXwuOGuetobCTaaTfAyXmgXqcH1ZPi0u1dSzkWbHOdBNhRQLlk3ZtTfnCQrtijjU -U6jqkiMoMhap1/jEQPoU6CHP3bbwkSdZrnNriVxyGp2IKGwNDlg9fOBGuXdNei8N -fP5q9daV3oC9ckverNNKpcn9/0wYchISH9Y0a8N6FFUBqEYnjsEee7a5VIfgsP70 -jrhk53pNQJSObJhAFzhsbFNXxmWkZpi/YUJaBCSQYwQCUToRINyUMZOtsUIBh4es -8EpBt2utPkVifZvBo+prKUPTYX64iKko7zY5WHyP6vIV5BihYYv3Em8CAwEAAaNS -MFAwHQYDVR0OBBYEFKekg+UBOOgzMM6Ft6zCMa6k6H89MB8GA1UdIwQYMBaAFGTF -QTPAuR/St27lPFyjklKx/xYLMA4GA1UdDwEB/wQEAwIB5jANBgkqhkiG9w0BAQsF -AAOCAQEAadrnESocLAKEhOVcKC1tGOlDEI3oYkODcT4E3AOBqBq+gy4s5hfrQEpC -HqCje0pGNY1xgdcG5OPaKNSMT7+/PLE5As7aktNQxWuhDSH0SwKQPBbG+pfs0m3J -1R6M0WKsqvLWUtUgkzQp2f9pqu/XBrjqJnI5RwtNBBXJV8QBhLf4z/kGIk4noDM7 -2PcXdGNfl6dINcX8q3meZ1DkWTypgZ1pcEcvHU0rUPo+UPUpg6pOruOVnCERRiSx -z97Gqp1ZDa/jH1a+tjmbq4EN1vbULzVw+xsBIMuT7lsPTLdy/AHIx2UXVMGhHoYV -BHO096jz11DkzNKHloHf5sKPK2Ecjg== ------END CERTIFICATE----- ------BEGIN CERTIFICATE----- -MIIDQjCCAiqgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MR4wHAYDVQQDDBVpVGV4dFRlc3RJbnRlcm1lZGlhdGUw -IBcNMDAwMTAxMDAwMDAwWhgPMjQwMDAxMDEwMDAwMDBaMDUxCzAJBgNVBAYTAkJF -MQ4wDAYDVQQKDAVpVGV4dDEWMBQGA1UEAwwNaVRleHRUZXN0U2lnbjCCASIwDQYJ -KoZIhvcNAQEBBQADggEPADCCAQoCggEBAMaJ+B8HlKGXBhb64LuOiG/xGWn3RgU+ -D1i42xD4jRIjP3oL3hLefVtqQAgaP4HJa0mI1VWU2ezTbp5u11qo9eAefPq6jxaO -rbC3VyT/FE4EcoEvr48N/1ZB0jnKLQlO2lzzVCqnL9gyC+soakGwLzFs9SKjkI4h -/9YCnkoVtxOI/9ZDBf/QlJxrpknOPS9RQ8Y0OK+2OIb0kvK0f28EcvfopAnvOaVb -AHIWypIDabuRcw/YXRbmxvj2c+t1dGC7f4CLv7YKiFsEpydUJDWRUYGLnE7GvO9d -mS3oEFaI+Kre4HjSsaCF/Rgp9fpHKgaFTr8rKOGVgQHPlRFOrtGqXV8CAwEAAaNS -MFAwHQYDVR0OBBYEFKwAjNPp8T/Q6cWJGYu9aMR/ujVCMB8GA1UdIwQYMBaAFKek -g+UBOOgzMM6Ft6zCMa6k6H89MA4GA1UdDwEB/wQEAwIGwDANBgkqhkiG9w0BAQsF -AAOCAQEARWKct75OvbvIGRpTN4lvqyPJS/ZoVa/Dddbdo2rD669qltAce3/DFY2R -W0CNwIAxBh4CHqdlG5Od1qQ+BJH2pNGB6F2W/kmQuzaoo2PecDXNOfigRJASZO9O -nSFh+tQc+9DTNWrYyBb1MUEgZd4z0Q98dX3mWJ3YMG5Fb0pbexgpiAX5s9T3X+Da -olCzzmIRVIbce3UWv6T3fGvRJ/tyJ0VqvR8YBbVW15KaPabyZDE+v7QFizmoRFdw -7Dfv2tKIA/8ENO13BztYq1USTYhirfrR5Ki2oiul1Nmg48JgQRMHgfeBKMl9auyR -B6hPOeazdx/aJXMcZVIkYoWOPQsqVg== ------END CERTIFICATE----- ------BEGIN CERTIFICATE----- -MIIDvDCCAqSgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwTzELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MTAwLgYDVQQDDCdpVGV4dE1pc3NpbmdDZXJ0aWZpY2F0 -ZXNUZXN0Q1JMUm9vdENlcnQwIBcNMjAwMTAxMDAwMDAwWhgPMjQwMDAxMDEwMDAw -MDBaME8xCzAJBgNVBAYTAkJFMQ4wDAYDVQQKDAVpVGV4dDEwMC4GA1UEAwwnaVRl -eHRNaXNzaW5nQ2VydGlmaWNhdGVzVGVzdENSTFNpZ25DZXJ0MIIBIjANBgkqhkiG -9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk0rgFNDp8zelAj9o73RqZUK6pStgVbBL0Zn9 -HhM5O0e3OuWEgJtOm+foMayksOQHESxS6t/AiKdkTQc6nVl8cXncZURnsEi6SpHo -r/WMkOmKUvnYdXda2mPuRmxRopG4TMqW6S0A9N8E29+xdG3LcmV/HP4MU78nRoOH -WGi+Op1I4tyC9i8CfoRJcq7WI51fyh87TrxITS80Cjq9AXoBvmJrx90DgP7u7WUT -NAPvVayapLG3VtnexSDuM/7+73dT15a4QxPdLmFUYbyhSfH77iI11FZd/06i9v/f -uRcVZBobCs8+FzmN1OhSs1Uk7aAj/QkQkuyvVyK6uhrstfT4GwIDAQABo4GfMIGc -MB0GA1UdDgQWBBT3CXRcQ9OYneGbRjM5g/NWB0LT4DAfBgNVHSMEGDAWgBTDTbEm -iGJjiJdOu6soHhD/ha1kGjAOBgNVHQ8BAf8EBAMCBeAwSgYDVR0fBEMwQTA/oD2g -O4Y5aHR0cDovL3Rlc3QuZXhhbXBsZS5jb20vZXhhbXBsZS1jYS9jcmxzL2NhLWNy -bC9sYXRlc3QuY3JsMA0GCSqGSIb3DQEBCwUAA4IBAQAhTj5txV1IAyfe7K/bxDlK -nKRJYYLsY8iTCu3dNF7mjSD7eZf7wWvGdfR2a910uS6U0/ZDIYyKSOnxdlRvNrU5 -nGxk48JuUZgSlSmzq1RmvdPx6dBLJT3Dctm7hkzQHemYNNAlkvDVX2GMPrEgcoTY -S5gwKOvoQi5hXIYNxX43CaxVGyForNBMBn4502ThTs/M58EKNEZvUaNbYs2iLNkS -CU1M0KZ4fMlihP9xtAhTBeqHUqEubKP45T0KzqWOZPH/WyQPeIrNAnXk2H0gIZP5 -ElI5Wm7r+EhCWTDfaBK3OormNoBOYKU0tawzzKVh1MHOg+31BqJud7H+t5REbTck ------END CERTIFICATE----- ------BEGIN CERTIFICATE----- -MIIDfzCCAmegAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwTzELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MTAwLgYDVQQDDCdpVGV4dE1pc3NpbmdDZXJ0aWZpY2F0 -ZXNUZXN0Q1JMUm9vdENlcnQwIBcNMDAwMTAxMDAwMDAwWhgPMjUwMDAxMDEwMDAw -MDBaME8xCzAJBgNVBAYTAkJFMQ4wDAYDVQQKDAVpVGV4dDEwMC4GA1UEAwwnaVRl -eHRNaXNzaW5nQ2VydGlmaWNhdGVzVGVzdENSTFJvb3RDZXJ0MIIBIjANBgkqhkiG -9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu8ePfGsGJ2JOMKSzy1vSZW0vutjJCdi5mW+Y -vqYJ+kQLOr0+gb3Wu0BonyFzl8wF9ogfaAyBqjzswaKw9uGfhHanzh5vqNwSHNlR -/2aa56I1GidrprnaMSZiNy4lFAGxajFfb0D++UNjdLrkARjVcKenrwauR+GbT5bM -tQw3yJVyMzAA6uy4xGMMNW/ZZwEUmKvWPNXqJHq0BvJICWWlZFQI2dMQo4DR7Npk -D8dVd/Fdwtpp59E6xGz6WDk9/x6NH7wcZGW8xjZTtkrTOoppMG6A7Wrb+VWrXVbT -lKaCo/1DY4whfnkKUwDsNXIk4vn9sU6PRvp0iEZGqk5Z25wQJwIDAQABo2MwYTAd -BgNVHQ4EFgQUw02xJohiY4iXTrurKB4Q/4WtZBowHwYDVR0jBBgwFoAUw02xJohi -Y4iXTrurKB4Q/4WtZBowDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAeYw -DQYJKoZIhvcNAQELBQADggEBAC5DclkIZBL7k5uqMA+TwzwwPSE0pCNrN0wLMy8I -qaooT3IKuLLjo7FLH28ZRkrUYBdrg7W60NZfbDNcLoVSEyyOFMrplQNdUDPByrTU -BUERxQ7r+7g+pHuF93o/3DbwvN8fykm4pC7d0JlFwge+LOu7pICHa8Ctj6K+C0kN -lwhoz3Rafg+1tj5GUoGj2ZX82yXwb+rnSIn0hj6HhDpPXYRn2GssOqkOs1MJElw+ -GPn8vD7a3wI++4alki52TuR1Ydu41z4lQjfy3JSaFuflsPFf0KjNeCkH/D6PgwZg -KCcD7fbk2IcIj70d5xye3v53wkbc9wZhqYm9CtKYunrKGoM= ------END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlAndSignCertRootIssuerMismatch/crl-issuer.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlAndSignCertRootIssuerMismatch/crl-issuer.cert.pem deleted file mode 100644 index 10dca028c1..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlAndSignCertRootIssuerMismatch/crl-issuer.cert.pem +++ /dev/null @@ -1,22 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDvDCCAqSgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwTzELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MTAwLgYDVQQDDCdpVGV4dE1pc3NpbmdDZXJ0aWZpY2F0 -ZXNUZXN0Q1JMUm9vdENlcnQwIBcNMjAwMTAxMDAwMDAwWhgPMjQwMDAxMDEwMDAw -MDBaME8xCzAJBgNVBAYTAkJFMQ4wDAYDVQQKDAVpVGV4dDEwMC4GA1UEAwwnaVRl -eHRNaXNzaW5nQ2VydGlmaWNhdGVzVGVzdENSTFNpZ25DZXJ0MIIBIjANBgkqhkiG -9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk0rgFNDp8zelAj9o73RqZUK6pStgVbBL0Zn9 -HhM5O0e3OuWEgJtOm+foMayksOQHESxS6t/AiKdkTQc6nVl8cXncZURnsEi6SpHo -r/WMkOmKUvnYdXda2mPuRmxRopG4TMqW6S0A9N8E29+xdG3LcmV/HP4MU78nRoOH -WGi+Op1I4tyC9i8CfoRJcq7WI51fyh87TrxITS80Cjq9AXoBvmJrx90DgP7u7WUT -NAPvVayapLG3VtnexSDuM/7+73dT15a4QxPdLmFUYbyhSfH77iI11FZd/06i9v/f -uRcVZBobCs8+FzmN1OhSs1Uk7aAj/QkQkuyvVyK6uhrstfT4GwIDAQABo4GfMIGc -MB0GA1UdDgQWBBT3CXRcQ9OYneGbRjM5g/NWB0LT4DAfBgNVHSMEGDAWgBTDTbEm -iGJjiJdOu6soHhD/ha1kGjAOBgNVHQ8BAf8EBAMCBeAwSgYDVR0fBEMwQTA/oD2g -O4Y5aHR0cDovL3Rlc3QuZXhhbXBsZS5jb20vZXhhbXBsZS1jYS9jcmxzL2NhLWNy -bC9sYXRlc3QuY3JsMA0GCSqGSIb3DQEBCwUAA4IBAQAhTj5txV1IAyfe7K/bxDlK -nKRJYYLsY8iTCu3dNF7mjSD7eZf7wWvGdfR2a910uS6U0/ZDIYyKSOnxdlRvNrU5 -nGxk48JuUZgSlSmzq1RmvdPx6dBLJT3Dctm7hkzQHemYNNAlkvDVX2GMPrEgcoTY -S5gwKOvoQi5hXIYNxX43CaxVGyForNBMBn4502ThTs/M58EKNEZvUaNbYs2iLNkS -CU1M0KZ4fMlihP9xtAhTBeqHUqEubKP45T0KzqWOZPH/WyQPeIrNAnXk2H0gIZP5 -ElI5Wm7r+EhCWTDfaBK3OormNoBOYKU0tawzzKVh1MHOg+31BqJud7H+t5REbTck ------END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlAndSignCertRootIssuerMismatch/crl.crl b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlAndSignCertRootIssuerMismatch/crl.crl deleted file mode 100644 index 286fba41ce..0000000000 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlAndSignCertRootIssuerMismatch/crl.crl and /dev/null differ diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlAndSignCertRootIssuerMismatch/crlRoot.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlAndSignCertRootIssuerMismatch/crlRoot.pem deleted file mode 100644 index fcc6491e2e..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlAndSignCertRootIssuerMismatch/crlRoot.pem +++ /dev/null @@ -1,21 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDfzCCAmegAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwTzELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MTAwLgYDVQQDDCdpVGV4dE1pc3NpbmdDZXJ0aWZpY2F0 -ZXNUZXN0Q1JMUm9vdENlcnQwIBcNMDAwMTAxMDAwMDAwWhgPMjUwMDAxMDEwMDAw -MDBaME8xCzAJBgNVBAYTAkJFMQ4wDAYDVQQKDAVpVGV4dDEwMC4GA1UEAwwnaVRl -eHRNaXNzaW5nQ2VydGlmaWNhdGVzVGVzdENSTFJvb3RDZXJ0MIIBIjANBgkqhkiG -9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu8ePfGsGJ2JOMKSzy1vSZW0vutjJCdi5mW+Y -vqYJ+kQLOr0+gb3Wu0BonyFzl8wF9ogfaAyBqjzswaKw9uGfhHanzh5vqNwSHNlR -/2aa56I1GidrprnaMSZiNy4lFAGxajFfb0D++UNjdLrkARjVcKenrwauR+GbT5bM -tQw3yJVyMzAA6uy4xGMMNW/ZZwEUmKvWPNXqJHq0BvJICWWlZFQI2dMQo4DR7Npk -D8dVd/Fdwtpp59E6xGz6WDk9/x6NH7wcZGW8xjZTtkrTOoppMG6A7Wrb+VWrXVbT -lKaCo/1DY4whfnkKUwDsNXIk4vn9sU6PRvp0iEZGqk5Z25wQJwIDAQABo2MwYTAd -BgNVHQ4EFgQUw02xJohiY4iXTrurKB4Q/4WtZBowHwYDVR0jBBgwFoAUw02xJohi -Y4iXTrurKB4Q/4WtZBowDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAeYw -DQYJKoZIhvcNAQELBQADggEBAC5DclkIZBL7k5uqMA+TwzwwPSE0pCNrN0wLMy8I -qaooT3IKuLLjo7FLH28ZRkrUYBdrg7W60NZfbDNcLoVSEyyOFMrplQNdUDPByrTU -BUERxQ7r+7g+pHuF93o/3DbwvN8fykm4pC7d0JlFwge+LOu7pICHa8Ctj6K+C0kN -lwhoz3Rafg+1tj5GUoGj2ZX82yXwb+rnSIn0hj6HhDpPXYRn2GssOqkOs1MJElw+ -GPn8vD7a3wI++4alki52TuR1Ydu41z4lQjfy3JSaFuflsPFf0KjNeCkH/D6PgwZg -KCcD7fbk2IcIj70d5xye3v53wkbc9wZhqYm9CtKYunrKGoM= ------END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlEncodingError/chain.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlEncodingError/chain.pem deleted file mode 100644 index 1c28583267..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlEncodingError/chain.pem +++ /dev/null @@ -1,81 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDSzCCAjOgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw -MTAwMDAwMFoYDzI1MDAwMTAxMDAwMDAwWjA1MQswCQYDVQQGEwJCRTEOMAwGA1UE -CgwFaVRleHQxFjAUBgNVBAMMDWlUZXh0VGVzdFJvb3QwggEiMA0GCSqGSIb3DQEB -AQUAA4IBDwAwggEKAoIBAQDP6KUmxQzeXKuwodaQZ7IUoidvDeXWrjW7BNYmKhey -DX9SIeIwvuiKDVUD85pWyk6jhNUvQaYvGVOv/Pbu4NJHv9FKch2d9759ckMT+MXG -fGk/B6Ww1rlKsiHccWizQxah7R79eGweEvryPIx+hqxreCBH4yzMPjHld1C34/vC -nUGmozKT4KENiT6lXXiBm4D+u3siCPt1Gzxavvm2MUBTHBbhQ3/n1eS/FcqT4NhI -vXDpPiNouD9goI+4LwCW7b52dg7dXreQY/IfGCcHTcu7YK/OEW4Pqjpr13B5mEDS -DsCqrStoh8EQ+jB62n2Xv8TT4lQju/sZh0l65IiT8fUfAgMBAAGjYzBhMB0GA1Ud -DgQWBBRkxUEzwLkf0rdu5Txco5JSsf8WCzAfBgNVHSMEGDAWgBRkxUEzwLkf0rdu -5Txco5JSsf8WCzAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIC5DANBgkq -hkiG9w0BAQsFAAOCAQEARJOOUQkv9AgqElJmQjGDkRdJPxkDHZtRLGOk9p0E1KbL -lqQQdgzL7RuE4vfCROan6aBZmXFRviIPg/Gxw2hDSIv1NUZv3AIgM2b9+3y+4SQ6 -2a/sqh1JPLxwnLN+Mo5KwY/E/YlJ0N7rw3AONrLlqH89BRrBIiPjrg74zi6qPzGn -WB2awHsbl7AOtkD2dEud7lbyLda/hCw2RGPSBQMm50pWsuInWXzdtX/Ii9yTGMyD -kavUHX6DDVouZBSKOjmChP0fGPM17ORJNR92RbT2ygy+F0Zokh5XUgrKPr4/JTW5 -iIkycpjAXY9UEMfi8pFnnzVSRj65kkZvZZJzybelMQ== ------END CERTIFICATE----- ------BEGIN CERTIFICATE----- -MIIDhzCCAm+gAwIBAgICEAIwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw -MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA6MQswCQYDVQQGEwJCRTEOMAwGA1UE -CgwFaVRleHQxGzAZBgNVBAMMEmlUZXh0VGVzdENybElzc3VlcjCCASIwDQYJKoZI -hvcNAQEBBQADggEPADCCAQoCggEBAJV6eBrtpxfCCiAkgz3wdLUqRio0/TBHDHg5 -oU1lHNeKoNkEG/kwdgPFN4YN9qufVZBi5mRY54NaVySKHo2w7/CrscZhbXtrBIQY -WzR0vRptsbmqV2xfBlqtPyPlRMt2SRnwe3Q4XqZSnX13bUTLO0SBlddGt7h/HQfD -vSzbekJWd8bPt+cH5Ke3y0cdFNylwP5yXEZdDyU9CtkzaBpHFM8vAEO00/kqahap -8Ox+Tea7zrAfoT58juJdGOlt7DRJs6jsLXsDT04zk47cpZ904R29lzU1zoMoiEjf -UTDO0c5fj4q4RCYzSpT3jX5VJEfKlooP6TX/GDVtH58+A3YQXuMCAwEAAaOBmTCB -ljAdBgNVHQ4EFgQU0zydGfhFz0j/TGolSJNUJEx9j2UwHwYDVR0jBBgwFoAUZMVB -M8C5H9K3buU8XKOSUrH/FgswDgYDVR0PAQH/BAQDAgHCMEQGA1UdHwQ9MDswOaA3 -oDWGM2h0dHA6Ly9sb2NhbGhvc3QudGVzdC9oYXBweVBhdGgvY3Jscy9jcmwvbGF0 -ZXN0LmNybDANBgkqhkiG9w0BAQsFAAOCAQEALXE8wl8A0vUP0CDs8/2nTSramr3N -M8bwkiQx88d2QAvq5pq0j4U/kfxnQk6PqQ+mJJIRn2U+Mc8Z/48VcGpYwqmO3wXc -0pRSohNCyD7vj48Og0dWKsMDimrzUEDqy6qaODfczqtQIpkwRyn/A9HQDzCOwtAr -6A86xnrOn96xxt/cnBeJ6SIw9tE461ZJ/pDJevzt64GYJBvbB+QE+NsAA4SOZgVG -iZ39xNt7WFrBuaU/n5ysZVbvN8tDJYSnfFPxD0kHmvWCDVxVzk5cckoRv6RQRA1s -m6IHnGQuPEoXa+y0/oyaEUDby/0G2Pe1CoBpaHMX9n4CSSnhaPB5tPpjrw== ------END CERTIFICATE----- ------BEGIN CERTIFICATE----- -MIIDQjCCAiqgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw -MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA9MQswCQYDVQQGEwJCRTEOMAwGA1UE -CgwFaVRleHQxHjAcBgNVBAMMFWlUZXh0VGVzdEludGVybWVkaWF0ZTCCASIwDQYJ -KoZIhvcNAQEBBQADggEPADCCAQoCggEBAM3t0dlZupS+5Z0EGHsnruz2ZRoVKwbp -IXwuOGuetobCTaaTfAyXmgXqcH1ZPi0u1dSzkWbHOdBNhRQLlk3ZtTfnCQrtijjU -U6jqkiMoMhap1/jEQPoU6CHP3bbwkSdZrnNriVxyGp2IKGwNDlg9fOBGuXdNei8N -fP5q9daV3oC9ckverNNKpcn9/0wYchISH9Y0a8N6FFUBqEYnjsEee7a5VIfgsP70 -jrhk53pNQJSObJhAFzhsbFNXxmWkZpi/YUJaBCSQYwQCUToRINyUMZOtsUIBh4es -8EpBt2utPkVifZvBo+prKUPTYX64iKko7zY5WHyP6vIV5BihYYv3Em8CAwEAAaNS -MFAwHQYDVR0OBBYEFKekg+UBOOgzMM6Ft6zCMa6k6H89MB8GA1UdIwQYMBaAFGTF -QTPAuR/St27lPFyjklKx/xYLMA4GA1UdDwEB/wQEAwIB5jANBgkqhkiG9w0BAQsF -AAOCAQEAadrnESocLAKEhOVcKC1tGOlDEI3oYkODcT4E3AOBqBq+gy4s5hfrQEpC -HqCje0pGNY1xgdcG5OPaKNSMT7+/PLE5As7aktNQxWuhDSH0SwKQPBbG+pfs0m3J -1R6M0WKsqvLWUtUgkzQp2f9pqu/XBrjqJnI5RwtNBBXJV8QBhLf4z/kGIk4noDM7 -2PcXdGNfl6dINcX8q3meZ1DkWTypgZ1pcEcvHU0rUPo+UPUpg6pOruOVnCERRiSx -z97Gqp1ZDa/jH1a+tjmbq4EN1vbULzVw+xsBIMuT7lsPTLdy/AHIx2UXVMGhHoYV -BHO096jz11DkzNKHloHf5sKPK2Ecjg== ------END CERTIFICATE----- ------BEGIN CERTIFICATE----- -MIIDQjCCAiqgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MR4wHAYDVQQDDBVpVGV4dFRlc3RJbnRlcm1lZGlhdGUw -IBcNMDAwMTAxMDAwMDAwWhgPMjQwMDAxMDEwMDAwMDBaMDUxCzAJBgNVBAYTAkJF -MQ4wDAYDVQQKDAVpVGV4dDEWMBQGA1UEAwwNaVRleHRUZXN0U2lnbjCCASIwDQYJ -KoZIhvcNAQEBBQADggEPADCCAQoCggEBAMaJ+B8HlKGXBhb64LuOiG/xGWn3RgU+ -D1i42xD4jRIjP3oL3hLefVtqQAgaP4HJa0mI1VWU2ezTbp5u11qo9eAefPq6jxaO -rbC3VyT/FE4EcoEvr48N/1ZB0jnKLQlO2lzzVCqnL9gyC+soakGwLzFs9SKjkI4h -/9YCnkoVtxOI/9ZDBf/QlJxrpknOPS9RQ8Y0OK+2OIb0kvK0f28EcvfopAnvOaVb -AHIWypIDabuRcw/YXRbmxvj2c+t1dGC7f4CLv7YKiFsEpydUJDWRUYGLnE7GvO9d -mS3oEFaI+Kre4HjSsaCF/Rgp9fpHKgaFTr8rKOGVgQHPlRFOrtGqXV8CAwEAAaNS -MFAwHQYDVR0OBBYEFKwAjNPp8T/Q6cWJGYu9aMR/ujVCMB8GA1UdIwQYMBaAFKek -g+UBOOgzMM6Ft6zCMa6k6H89MA4GA1UdDwEB/wQEAwIGwDANBgkqhkiG9w0BAQsF -AAOCAQEARWKct75OvbvIGRpTN4lvqyPJS/ZoVa/Dddbdo2rD669qltAce3/DFY2R -W0CNwIAxBh4CHqdlG5Od1qQ+BJH2pNGB6F2W/kmQuzaoo2PecDXNOfigRJASZO9O -nSFh+tQc+9DTNWrYyBb1MUEgZd4z0Q98dX3mWJ3YMG5Fb0pbexgpiAX5s9T3X+Da -olCzzmIRVIbce3UWv6T3fGvRJ/tyJ0VqvR8YBbVW15KaPabyZDE+v7QFizmoRFdw -7Dfv2tKIA/8ENO13BztYq1USTYhirfrR5Ki2oiul1Nmg48JgQRMHgfeBKMl9auyR -B6hPOeazdx/aJXMcZVIkYoWOPQsqVg== ------END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlEncodingError/sign.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlEncodingError/sign.cert.pem deleted file mode 100644 index 26c2432936..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlEncodingError/sign.cert.pem +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDQjCCAiqgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MR4wHAYDVQQDDBVpVGV4dFRlc3RJbnRlcm1lZGlhdGUw -IBcNMDAwMTAxMDAwMDAwWhgPMjQwMDAxMDEwMDAwMDBaMDUxCzAJBgNVBAYTAkJF -MQ4wDAYDVQQKDAVpVGV4dDEWMBQGA1UEAwwNaVRleHRUZXN0U2lnbjCCASIwDQYJ -KoZIhvcNAQEBBQADggEPADCCAQoCggEBAMaJ+B8HlKGXBhb64LuOiG/xGWn3RgU+ -D1i42xD4jRIjP3oL3hLefVtqQAgaP4HJa0mI1VWU2ezTbp5u11qo9eAefPq6jxaO -rbC3VyT/FE4EcoEvr48N/1ZB0jnKLQlO2lzzVCqnL9gyC+soakGwLzFs9SKjkI4h -/9YCnkoVtxOI/9ZDBf/QlJxrpknOPS9RQ8Y0OK+2OIb0kvK0f28EcvfopAnvOaVb -AHIWypIDabuRcw/YXRbmxvj2c+t1dGC7f4CLv7YKiFsEpydUJDWRUYGLnE7GvO9d -mS3oEFaI+Kre4HjSsaCF/Rgp9fpHKgaFTr8rKOGVgQHPlRFOrtGqXV8CAwEAAaNS -MFAwHQYDVR0OBBYEFKwAjNPp8T/Q6cWJGYu9aMR/ujVCMB8GA1UdIwQYMBaAFKek -g+UBOOgzMM6Ft6zCMa6k6H89MA4GA1UdDwEB/wQEAwIGwDANBgkqhkiG9w0BAQsF -AAOCAQEARWKct75OvbvIGRpTN4lvqyPJS/ZoVa/Dddbdo2rD669qltAce3/DFY2R -W0CNwIAxBh4CHqdlG5Od1qQ+BJH2pNGB6F2W/kmQuzaoo2PecDXNOfigRJASZO9O -nSFh+tQc+9DTNWrYyBb1MUEgZd4z0Q98dX3mWJ3YMG5Fb0pbexgpiAX5s9T3X+Da -olCzzmIRVIbce3UWv6T3fGvRJ/tyJ0VqvR8YBbVW15KaPabyZDE+v7QFizmoRFdw -7Dfv2tKIA/8ENO13BztYq1USTYhirfrR5Ki2oiul1Nmg48JgQRMHgfeBKMl9auyR -B6hPOeazdx/aJXMcZVIkYoWOPQsqVg== ------END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/chain.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/chain.pem deleted file mode 100644 index d8645c076d..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/chain.pem +++ /dev/null @@ -1,101 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDSzCCAjOgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw -MTAwMDAwMFoYDzI1MDAwMTAxMDAwMDAwWjA1MQswCQYDVQQGEwJCRTEOMAwGA1UE -CgwFaVRleHQxFjAUBgNVBAMMDWlUZXh0VGVzdFJvb3QwggEiMA0GCSqGSIb3DQEB -AQUAA4IBDwAwggEKAoIBAQDP6KUmxQzeXKuwodaQZ7IUoidvDeXWrjW7BNYmKhey -DX9SIeIwvuiKDVUD85pWyk6jhNUvQaYvGVOv/Pbu4NJHv9FKch2d9759ckMT+MXG -fGk/B6Ww1rlKsiHccWizQxah7R79eGweEvryPIx+hqxreCBH4yzMPjHld1C34/vC -nUGmozKT4KENiT6lXXiBm4D+u3siCPt1Gzxavvm2MUBTHBbhQ3/n1eS/FcqT4NhI -vXDpPiNouD9goI+4LwCW7b52dg7dXreQY/IfGCcHTcu7YK/OEW4Pqjpr13B5mEDS -DsCqrStoh8EQ+jB62n2Xv8TT4lQju/sZh0l65IiT8fUfAgMBAAGjYzBhMB0GA1Ud -DgQWBBRkxUEzwLkf0rdu5Txco5JSsf8WCzAfBgNVHSMEGDAWgBRkxUEzwLkf0rdu -5Txco5JSsf8WCzAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIC5DANBgkq -hkiG9w0BAQsFAAOCAQEARJOOUQkv9AgqElJmQjGDkRdJPxkDHZtRLGOk9p0E1KbL -lqQQdgzL7RuE4vfCROan6aBZmXFRviIPg/Gxw2hDSIv1NUZv3AIgM2b9+3y+4SQ6 -2a/sqh1JPLxwnLN+Mo5KwY/E/YlJ0N7rw3AONrLlqH89BRrBIiPjrg74zi6qPzGn -WB2awHsbl7AOtkD2dEud7lbyLda/hCw2RGPSBQMm50pWsuInWXzdtX/Ii9yTGMyD -kavUHX6DDVouZBSKOjmChP0fGPM17ORJNR92RbT2ygy+F0Zokh5XUgrKPr4/JTW5 -iIkycpjAXY9UEMfi8pFnnzVSRj65kkZvZZJzybelMQ== ------END CERTIFICATE----- ------BEGIN CERTIFICATE----- -MIIDijCCAnKgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwOjELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MRswGQYDVQQDDBJpVGV4dE90aGVyVGVzdFJvb3QwIBcN -MDAwMTAxMDAwMDAwWhgPMjQ1MDAxMDEwMDAwMDBaMDoxCzAJBgNVBAYTAkJFMQ4w -DAYDVQQKDAVpVGV4dDEbMBkGA1UEAwwSaVRleHRUZXN0Q3JsSXNzdWVyMIIBIjAN -BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlXp4Gu2nF8IKICSDPfB0tSpGKjT9 -MEcMeDmhTWUc14qg2QQb+TB2A8U3hg32q59VkGLmZFjng1pXJIoejbDv8KuxxmFt -e2sEhBhbNHS9Gm2xuapXbF8GWq0/I+VEy3ZJGfB7dDheplKdfXdtRMs7RIGV10a3 -uH8dB8O9LNt6QlZ3xs+35wfkp7fLRx0U3KXA/nJcRl0PJT0K2TNoGkcUzy8AQ7TT -+SpqFqnw7H5N5rvOsB+hPnyO4l0Y6W3sNEmzqOwtewNPTjOTjtyln3ThHb2XNTXO -gyiISN9RMM7Rzl+PirhEJjNKlPeNflUkR8qWig/pNf8YNW0fnz4DdhBe4wIDAQAB -o4GXMIGUMB0GA1UdDgQWBBTTPJ0Z+EXPSP9MaiVIk1QkTH2PZTAfBgNVHSMEGDAW -gBSnpIPlATjoMzDOhbeswjGupOh/PTAOBgNVHQ8BAf8EBAMCAcIwQgYDVR0fBDsw -OTA3oDWgM4YxaHR0cDovL2xvY2FsaG9zdC50ZXN0L2RlZmF1bHQvY3Jscy9jcmwv -bGF0ZXN0LmNybDANBgkqhkiG9w0BAQsFAAOCAQEAoX9g8yKhzXz+FirY5WtC1nbJ -DSeggirm4NFWeNvZY/nahleeO4+0RXRYp3maIjaEieWqgov4KukdtGl1SjQfvy6a -ghoznl3fwTR/TO2d5ms6LFfETEptY0p6zDnLjMDeYFNjLLZiXFDtnEV1DjrafrXI -PGFgF+jaYiZUp9H3oFyMUpi+gQDWmAoCppt8XBqoyWUmSqwfEk6Ls5qBu1N5KJQU -TIV6zCK90cqGNvypKbynb0LAvQAkJiMoprOxf2PHoahNIsbuvasJp/LB2xJWbVjR -B3/Qb8SelSNFgwwHjGq7Zqx3zknNxSMKX+9wqAMGovgyJD411faSdBL9l4KaoA== ------END CERTIFICATE----- ------BEGIN CERTIFICATE----- -MIIDQjCCAiqgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw -MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA9MQswCQYDVQQGEwJCRTEOMAwGA1UE -CgwFaVRleHQxHjAcBgNVBAMMFWlUZXh0VGVzdEludGVybWVkaWF0ZTCCASIwDQYJ -KoZIhvcNAQEBBQADggEPADCCAQoCggEBAM3t0dlZupS+5Z0EGHsnruz2ZRoVKwbp -IXwuOGuetobCTaaTfAyXmgXqcH1ZPi0u1dSzkWbHOdBNhRQLlk3ZtTfnCQrtijjU -U6jqkiMoMhap1/jEQPoU6CHP3bbwkSdZrnNriVxyGp2IKGwNDlg9fOBGuXdNei8N -fP5q9daV3oC9ckverNNKpcn9/0wYchISH9Y0a8N6FFUBqEYnjsEee7a5VIfgsP70 -jrhk53pNQJSObJhAFzhsbFNXxmWkZpi/YUJaBCSQYwQCUToRINyUMZOtsUIBh4es -8EpBt2utPkVifZvBo+prKUPTYX64iKko7zY5WHyP6vIV5BihYYv3Em8CAwEAAaNS -MFAwHQYDVR0OBBYEFKekg+UBOOgzMM6Ft6zCMa6k6H89MB8GA1UdIwQYMBaAFGTF -QTPAuR/St27lPFyjklKx/xYLMA4GA1UdDwEB/wQEAwIB5jANBgkqhkiG9w0BAQsF -AAOCAQEAadrnESocLAKEhOVcKC1tGOlDEI3oYkODcT4E3AOBqBq+gy4s5hfrQEpC -HqCje0pGNY1xgdcG5OPaKNSMT7+/PLE5As7aktNQxWuhDSH0SwKQPBbG+pfs0m3J -1R6M0WKsqvLWUtUgkzQp2f9pqu/XBrjqJnI5RwtNBBXJV8QBhLf4z/kGIk4noDM7 -2PcXdGNfl6dINcX8q3meZ1DkWTypgZ1pcEcvHU0rUPo+UPUpg6pOruOVnCERRiSx -z97Gqp1ZDa/jH1a+tjmbq4EN1vbULzVw+xsBIMuT7lsPTLdy/AHIx2UXVMGhHoYV -BHO096jz11DkzNKHloHf5sKPK2Ecjg== ------END CERTIFICATE----- ------BEGIN CERTIFICATE----- -MIIDVTCCAj2gAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwOjELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MRswGQYDVQQDDBJpVGV4dE90aGVyVGVzdFJvb3QwIBcN -MDAwMTAxMDAwMDAwWhgPMjUwMDAxMDEwMDAwMDBaMDoxCzAJBgNVBAYTAkJFMQ4w -DAYDVQQKDAVpVGV4dDEbMBkGA1UEAwwSaVRleHRPdGhlclRlc3RSb290MIIBIjAN -BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAze3R2Vm6lL7lnQQYeyeu7PZlGhUr -BukhfC44a562hsJNppN8DJeaBepwfVk+LS7V1LORZsc50E2FFAuWTdm1N+cJCu2K -ONRTqOqSIygyFqnX+MRA+hToIc/dtvCRJ1muc2uJXHIanYgobA0OWD184Ea5d016 -Lw18/mr11pXegL1yS96s00qlyf3/TBhyEhIf1jRrw3oUVQGoRieOwR57trlUh+Cw -/vSOuGTnek1AlI5smEAXOGxsU1fGZaRmmL9hQloEJJBjBAJROhEg3JQxk62xQgGH -h6zwSkG3a60+RWJ9m8Gj6mspQ9NhfriIqSjvNjlYfI/q8hXkGKFhi/cSbwIDAQAB -o2MwYTAdBgNVHQ4EFgQUp6SD5QE46DMwzoW3rMIxrqTofz0wHwYDVR0jBBgwFoAU -p6SD5QE46DMwzoW3rMIxrqTofz0wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8E -BAMCAuQwDQYJKoZIhvcNAQELBQADggEBAB+QFs5zu6uD0+IEyAt8B+jxK2lV7025 -vENBQhFsnAKqsa7KJ5BCg4MrphMKvLTYopJz8TxQ4N6lmjS2VbdYZDqaP6M0mzwc -8E4biuW/6YptjLfoKZU73UqKPPvdh2qkll/nF/pMy8v6bf6Wg12b8pQAIrgaqu4/ -kopcba/2TftGy5/JUGVePif9+CUL95+UiUf9nvQr0KFL0+8k8L1DLs0wABKAPHXu -dFtfs1ofM5cC8pmVlJhoiIoHCWnIYOK2ea80Z2Xl/Y5ZtvAcluLW+0Ll+hsJ3pfy -80FH0UU7VsEJIOYrVCNx/JpXBH/AKQT0FcVzWU94FeSGb0vfihuL7nY= ------END CERTIFICATE----- ------BEGIN CERTIFICATE----- -MIIDQjCCAiqgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MR4wHAYDVQQDDBVpVGV4dFRlc3RJbnRlcm1lZGlhdGUw -IBcNMDAwMTAxMDAwMDAwWhgPMjQwMDAxMDEwMDAwMDBaMDUxCzAJBgNVBAYTAkJF -MQ4wDAYDVQQKDAVpVGV4dDEWMBQGA1UEAwwNaVRleHRUZXN0U2lnbjCCASIwDQYJ -KoZIhvcNAQEBBQADggEPADCCAQoCggEBAMaJ+B8HlKGXBhb64LuOiG/xGWn3RgU+ -D1i42xD4jRIjP3oL3hLefVtqQAgaP4HJa0mI1VWU2ezTbp5u11qo9eAefPq6jxaO -rbC3VyT/FE4EcoEvr48N/1ZB0jnKLQlO2lzzVCqnL9gyC+soakGwLzFs9SKjkI4h -/9YCnkoVtxOI/9ZDBf/QlJxrpknOPS9RQ8Y0OK+2OIb0kvK0f28EcvfopAnvOaVb -AHIWypIDabuRcw/YXRbmxvj2c+t1dGC7f4CLv7YKiFsEpydUJDWRUYGLnE7GvO9d -mS3oEFaI+Kre4HjSsaCF/Rgp9fpHKgaFTr8rKOGVgQHPlRFOrtGqXV8CAwEAAaNS -MFAwHQYDVR0OBBYEFKwAjNPp8T/Q6cWJGYu9aMR/ujVCMB8GA1UdIwQYMBaAFKek -g+UBOOgzMM6Ft6zCMa6k6H89MA4GA1UdDwEB/wQEAwIGwDANBgkqhkiG9w0BAQsF -AAOCAQEARWKct75OvbvIGRpTN4lvqyPJS/ZoVa/Dddbdo2rD669qltAce3/DFY2R -W0CNwIAxBh4CHqdlG5Od1qQ+BJH2pNGB6F2W/kmQuzaoo2PecDXNOfigRJASZO9O -nSFh+tQc+9DTNWrYyBb1MUEgZd4z0Q98dX3mWJ3YMG5Fb0pbexgpiAX5s9T3X+Da -olCzzmIRVIbce3UWv6T3fGvRJ/tyJ0VqvR8YBbVW15KaPabyZDE+v7QFizmoRFdw -7Dfv2tKIA/8ENO13BztYq1USTYhirfrR5Ki2oiul1Nmg48JgQRMHgfeBKMl9auyR -B6hPOeazdx/aJXMcZVIkYoWOPQsqVg== ------END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/crl-issuer.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/crl-issuer.cert.pem deleted file mode 100644 index f8c18553f3..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/crl-issuer.cert.pem +++ /dev/null @@ -1,21 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDijCCAnKgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwOjELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MRswGQYDVQQDDBJpVGV4dE90aGVyVGVzdFJvb3QwIBcN -MDAwMTAxMDAwMDAwWhgPMjQ1MDAxMDEwMDAwMDBaMDoxCzAJBgNVBAYTAkJFMQ4w -DAYDVQQKDAVpVGV4dDEbMBkGA1UEAwwSaVRleHRUZXN0Q3JsSXNzdWVyMIIBIjAN -BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlXp4Gu2nF8IKICSDPfB0tSpGKjT9 -MEcMeDmhTWUc14qg2QQb+TB2A8U3hg32q59VkGLmZFjng1pXJIoejbDv8KuxxmFt -e2sEhBhbNHS9Gm2xuapXbF8GWq0/I+VEy3ZJGfB7dDheplKdfXdtRMs7RIGV10a3 -uH8dB8O9LNt6QlZ3xs+35wfkp7fLRx0U3KXA/nJcRl0PJT0K2TNoGkcUzy8AQ7TT -+SpqFqnw7H5N5rvOsB+hPnyO4l0Y6W3sNEmzqOwtewNPTjOTjtyln3ThHb2XNTXO -gyiISN9RMM7Rzl+PirhEJjNKlPeNflUkR8qWig/pNf8YNW0fnz4DdhBe4wIDAQAB -o4GXMIGUMB0GA1UdDgQWBBTTPJ0Z+EXPSP9MaiVIk1QkTH2PZTAfBgNVHSMEGDAW -gBSnpIPlATjoMzDOhbeswjGupOh/PTAOBgNVHQ8BAf8EBAMCAcIwQgYDVR0fBDsw -OTA3oDWgM4YxaHR0cDovL2xvY2FsaG9zdC50ZXN0L2RlZmF1bHQvY3Jscy9jcmwv -bGF0ZXN0LmNybDANBgkqhkiG9w0BAQsFAAOCAQEAoX9g8yKhzXz+FirY5WtC1nbJ -DSeggirm4NFWeNvZY/nahleeO4+0RXRYp3maIjaEieWqgov4KukdtGl1SjQfvy6a -ghoznl3fwTR/TO2d5ms6LFfETEptY0p6zDnLjMDeYFNjLLZiXFDtnEV1DjrafrXI -PGFgF+jaYiZUp9H3oFyMUpi+gQDWmAoCppt8XBqoyWUmSqwfEk6Ls5qBu1N5KJQU -TIV6zCK90cqGNvypKbynb0LAvQAkJiMoprOxf2PHoahNIsbuvasJp/LB2xJWbVjR -B3/Qb8SelSNFgwwHjGq7Zqx3zknNxSMKX+9wqAMGovgyJD411faSdBL9l4KaoA== ------END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/intermediate.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/intermediate.cert.pem deleted file mode 100644 index 420f53b153..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/intermediate.cert.pem +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDQjCCAiqgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw -MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA9MQswCQYDVQQGEwJCRTEOMAwGA1UE -CgwFaVRleHQxHjAcBgNVBAMMFWlUZXh0VGVzdEludGVybWVkaWF0ZTCCASIwDQYJ -KoZIhvcNAQEBBQADggEPADCCAQoCggEBAM3t0dlZupS+5Z0EGHsnruz2ZRoVKwbp -IXwuOGuetobCTaaTfAyXmgXqcH1ZPi0u1dSzkWbHOdBNhRQLlk3ZtTfnCQrtijjU -U6jqkiMoMhap1/jEQPoU6CHP3bbwkSdZrnNriVxyGp2IKGwNDlg9fOBGuXdNei8N -fP5q9daV3oC9ckverNNKpcn9/0wYchISH9Y0a8N6FFUBqEYnjsEee7a5VIfgsP70 -jrhk53pNQJSObJhAFzhsbFNXxmWkZpi/YUJaBCSQYwQCUToRINyUMZOtsUIBh4es -8EpBt2utPkVifZvBo+prKUPTYX64iKko7zY5WHyP6vIV5BihYYv3Em8CAwEAAaNS -MFAwHQYDVR0OBBYEFKekg+UBOOgzMM6Ft6zCMa6k6H89MB8GA1UdIwQYMBaAFGTF -QTPAuR/St27lPFyjklKx/xYLMA4GA1UdDwEB/wQEAwIB5jANBgkqhkiG9w0BAQsF -AAOCAQEAadrnESocLAKEhOVcKC1tGOlDEI3oYkODcT4E3AOBqBq+gy4s5hfrQEpC -HqCje0pGNY1xgdcG5OPaKNSMT7+/PLE5As7aktNQxWuhDSH0SwKQPBbG+pfs0m3J -1R6M0WKsqvLWUtUgkzQp2f9pqu/XBrjqJnI5RwtNBBXJV8QBhLf4z/kGIk4noDM7 -2PcXdGNfl6dINcX8q3meZ1DkWTypgZ1pcEcvHU0rUPo+UPUpg6pOruOVnCERRiSx -z97Gqp1ZDa/jH1a+tjmbq4EN1vbULzVw+xsBIMuT7lsPTLdy/AHIx2UXVMGhHoYV -BHO096jz11DkzNKHloHf5sKPK2Ecjg== ------END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/otherca.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/otherca.cert.pem deleted file mode 100644 index e66c160433..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/otherca.cert.pem +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDVTCCAj2gAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwOjELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MRswGQYDVQQDDBJpVGV4dE90aGVyVGVzdFJvb3QwIBcN -MDAwMTAxMDAwMDAwWhgPMjUwMDAxMDEwMDAwMDBaMDoxCzAJBgNVBAYTAkJFMQ4w -DAYDVQQKDAVpVGV4dDEbMBkGA1UEAwwSaVRleHRPdGhlclRlc3RSb290MIIBIjAN -BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAze3R2Vm6lL7lnQQYeyeu7PZlGhUr -BukhfC44a562hsJNppN8DJeaBepwfVk+LS7V1LORZsc50E2FFAuWTdm1N+cJCu2K -ONRTqOqSIygyFqnX+MRA+hToIc/dtvCRJ1muc2uJXHIanYgobA0OWD184Ea5d016 -Lw18/mr11pXegL1yS96s00qlyf3/TBhyEhIf1jRrw3oUVQGoRieOwR57trlUh+Cw -/vSOuGTnek1AlI5smEAXOGxsU1fGZaRmmL9hQloEJJBjBAJROhEg3JQxk62xQgGH -h6zwSkG3a60+RWJ9m8Gj6mspQ9NhfriIqSjvNjlYfI/q8hXkGKFhi/cSbwIDAQAB -o2MwYTAdBgNVHQ4EFgQUp6SD5QE46DMwzoW3rMIxrqTofz0wHwYDVR0jBBgwFoAU -p6SD5QE46DMwzoW3rMIxrqTofz0wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8E -BAMCAuQwDQYJKoZIhvcNAQELBQADggEBAB+QFs5zu6uD0+IEyAt8B+jxK2lV7025 -vENBQhFsnAKqsa7KJ5BCg4MrphMKvLTYopJz8TxQ4N6lmjS2VbdYZDqaP6M0mzwc -8E4biuW/6YptjLfoKZU73UqKPPvdh2qkll/nF/pMy8v6bf6Wg12b8pQAIrgaqu4/ -kopcba/2TftGy5/JUGVePif9+CUL95+UiUf9nvQr0KFL0+8k8L1DLs0wABKAPHXu -dFtfs1ofM5cC8pmVlJhoiIoHCWnIYOK2ea80Z2Xl/Y5ZtvAcluLW+0Ll+hsJ3pfy -80FH0UU7VsEJIOYrVCNx/JpXBH/AKQT0FcVzWU94FeSGb0vfihuL7nY= ------END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/sign.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/sign.cert.pem deleted file mode 100644 index 26c2432936..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerAndSignCertHaveNoSharedRoot/sign.cert.pem +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDQjCCAiqgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MR4wHAYDVQQDDBVpVGV4dFRlc3RJbnRlcm1lZGlhdGUw -IBcNMDAwMTAxMDAwMDAwWhgPMjQwMDAxMDEwMDAwMDBaMDUxCzAJBgNVBAYTAkJF -MQ4wDAYDVQQKDAVpVGV4dDEWMBQGA1UEAwwNaVRleHRUZXN0U2lnbjCCASIwDQYJ -KoZIhvcNAQEBBQADggEPADCCAQoCggEBAMaJ+B8HlKGXBhb64LuOiG/xGWn3RgU+ -D1i42xD4jRIjP3oL3hLefVtqQAgaP4HJa0mI1VWU2ezTbp5u11qo9eAefPq6jxaO -rbC3VyT/FE4EcoEvr48N/1ZB0jnKLQlO2lzzVCqnL9gyC+soakGwLzFs9SKjkI4h -/9YCnkoVtxOI/9ZDBf/QlJxrpknOPS9RQ8Y0OK+2OIb0kvK0f28EcvfopAnvOaVb -AHIWypIDabuRcw/YXRbmxvj2c+t1dGC7f4CLv7YKiFsEpydUJDWRUYGLnE7GvO9d -mS3oEFaI+Kre4HjSsaCF/Rgp9fpHKgaFTr8rKOGVgQHPlRFOrtGqXV8CAwEAAaNS -MFAwHQYDVR0OBBYEFKwAjNPp8T/Q6cWJGYu9aMR/ujVCMB8GA1UdIwQYMBaAFKek -g+UBOOgzMM6Ft6zCMa6k6H89MA4GA1UdDwEB/wQEAwIGwDANBgkqhkiG9w0BAQsF -AAOCAQEARWKct75OvbvIGRpTN4lvqyPJS/ZoVa/Dddbdo2rD669qltAce3/DFY2R -W0CNwIAxBh4CHqdlG5Od1qQ+BJH2pNGB6F2W/kmQuzaoo2PecDXNOfigRJASZO9O -nSFh+tQc+9DTNWrYyBb1MUEgZd4z0Q98dX3mWJ3YMG5Fb0pbexgpiAX5s9T3X+Da -olCzzmIRVIbce3UWv6T3fGvRJ/tyJ0VqvR8YBbVW15KaPabyZDE+v7QFizmoRFdw -7Dfv2tKIA/8ENO13BztYq1USTYhirfrR5Ki2oiul1Nmg48JgQRMHgfeBKMl9auyR -B6hPOeazdx/aJXMcZVIkYoWOPQsqVg== ------END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/ca.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/ca.cert.pem deleted file mode 100644 index 607e8e4816..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/ca.cert.pem +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDSzCCAjOgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw -MTAwMDAwMFoYDzI1MDAwMTAxMDAwMDAwWjA1MQswCQYDVQQGEwJCRTEOMAwGA1UE -CgwFaVRleHQxFjAUBgNVBAMMDWlUZXh0VGVzdFJvb3QwggEiMA0GCSqGSIb3DQEB -AQUAA4IBDwAwggEKAoIBAQDP6KUmxQzeXKuwodaQZ7IUoidvDeXWrjW7BNYmKhey -DX9SIeIwvuiKDVUD85pWyk6jhNUvQaYvGVOv/Pbu4NJHv9FKch2d9759ckMT+MXG -fGk/B6Ww1rlKsiHccWizQxah7R79eGweEvryPIx+hqxreCBH4yzMPjHld1C34/vC -nUGmozKT4KENiT6lXXiBm4D+u3siCPt1Gzxavvm2MUBTHBbhQ3/n1eS/FcqT4NhI -vXDpPiNouD9goI+4LwCW7b52dg7dXreQY/IfGCcHTcu7YK/OEW4Pqjpr13B5mEDS -DsCqrStoh8EQ+jB62n2Xv8TT4lQju/sZh0l65IiT8fUfAgMBAAGjYzBhMB0GA1Ud -DgQWBBRkxUEzwLkf0rdu5Txco5JSsf8WCzAfBgNVHSMEGDAWgBRkxUEzwLkf0rdu -5Txco5JSsf8WCzAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIC5DANBgkq -hkiG9w0BAQsFAAOCAQEARJOOUQkv9AgqElJmQjGDkRdJPxkDHZtRLGOk9p0E1KbL -lqQQdgzL7RuE4vfCROan6aBZmXFRviIPg/Gxw2hDSIv1NUZv3AIgM2b9+3y+4SQ6 -2a/sqh1JPLxwnLN+Mo5KwY/E/YlJ0N7rw3AONrLlqH89BRrBIiPjrg74zi6qPzGn -WB2awHsbl7AOtkD2dEud7lbyLda/hCw2RGPSBQMm50pWsuInWXzdtX/Ii9yTGMyD -kavUHX6DDVouZBSKOjmChP0fGPM17ORJNR92RbT2ygy+F0Zokh5XUgrKPr4/JTW5 -iIkycpjAXY9UEMfi8pFnnzVSRj65kkZvZZJzybelMQ== ------END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/chain.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/chain.pem deleted file mode 100644 index cab4cb8209..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/chain.pem +++ /dev/null @@ -1,81 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDSzCCAjOgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw -MTAwMDAwMFoYDzI1MDAwMTAxMDAwMDAwWjA1MQswCQYDVQQGEwJCRTEOMAwGA1UE -CgwFaVRleHQxFjAUBgNVBAMMDWlUZXh0VGVzdFJvb3QwggEiMA0GCSqGSIb3DQEB -AQUAA4IBDwAwggEKAoIBAQDP6KUmxQzeXKuwodaQZ7IUoidvDeXWrjW7BNYmKhey -DX9SIeIwvuiKDVUD85pWyk6jhNUvQaYvGVOv/Pbu4NJHv9FKch2d9759ckMT+MXG -fGk/B6Ww1rlKsiHccWizQxah7R79eGweEvryPIx+hqxreCBH4yzMPjHld1C34/vC -nUGmozKT4KENiT6lXXiBm4D+u3siCPt1Gzxavvm2MUBTHBbhQ3/n1eS/FcqT4NhI -vXDpPiNouD9goI+4LwCW7b52dg7dXreQY/IfGCcHTcu7YK/OEW4Pqjpr13B5mEDS -DsCqrStoh8EQ+jB62n2Xv8TT4lQju/sZh0l65IiT8fUfAgMBAAGjYzBhMB0GA1Ud -DgQWBBRkxUEzwLkf0rdu5Txco5JSsf8WCzAfBgNVHSMEGDAWgBRkxUEzwLkf0rdu -5Txco5JSsf8WCzAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIC5DANBgkq -hkiG9w0BAQsFAAOCAQEARJOOUQkv9AgqElJmQjGDkRdJPxkDHZtRLGOk9p0E1KbL -lqQQdgzL7RuE4vfCROan6aBZmXFRviIPg/Gxw2hDSIv1NUZv3AIgM2b9+3y+4SQ6 -2a/sqh1JPLxwnLN+Mo5KwY/E/YlJ0N7rw3AONrLlqH89BRrBIiPjrg74zi6qPzGn -WB2awHsbl7AOtkD2dEud7lbyLda/hCw2RGPSBQMm50pWsuInWXzdtX/Ii9yTGMyD -kavUHX6DDVouZBSKOjmChP0fGPM17ORJNR92RbT2ygy+F0Zokh5XUgrKPr4/JTW5 -iIkycpjAXY9UEMfi8pFnnzVSRj65kkZvZZJzybelMQ== ------END CERTIFICATE----- ------BEGIN CERTIFICATE----- -MIIDiTCCAnGgAwIBAgICEAIwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw -MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA6MQswCQYDVQQGEwJCRTEOMAwGA1UE -CgwFaVRleHQxGzAZBgNVBAMMEmlUZXh0VGVzdENybElzc3VlcjCCASIwDQYJKoZI -hvcNAQEBBQADggEPADCCAQoCggEBAJV6eBrtpxfCCiAkgz3wdLUqRio0/TBHDHg5 -oU1lHNeKoNkEG/kwdgPFN4YN9qufVZBi5mRY54NaVySKHo2w7/CrscZhbXtrBIQY -WzR0vRptsbmqV2xfBlqtPyPlRMt2SRnwe3Q4XqZSnX13bUTLO0SBlddGt7h/HQfD -vSzbekJWd8bPt+cH5Ke3y0cdFNylwP5yXEZdDyU9CtkzaBpHFM8vAEO00/kqahap -8Ox+Tea7zrAfoT58juJdGOlt7DRJs6jsLXsDT04zk47cpZ904R29lzU1zoMoiEjf -UTDO0c5fj4q4RCYzSpT3jX5VJEfKlooP6TX/GDVtH58+A3YQXuMCAwEAAaOBmzCB -mDAdBgNVHQ4EFgQU0zydGfhFz0j/TGolSJNUJEx9j2UwHwYDVR0jBBgwFoAUZMVB -M8C5H9K3buU8XKOSUrH/FgswDgYDVR0PAQH/BAQDAgHCMEYGA1UdHwQ/MD0wO6A5 -oDeGNWh0dHA6Ly9sb2NhbGhvc3QudGVzdC9kZWZhdWx0L2NybHMvZGVmYXVsdC9s -YXRlc3QuY3JsMA0GCSqGSIb3DQEBCwUAA4IBAQC21PZDRIiPsN/mNQYZYxrpLksz -XYEgl0ZWJzv5noTRmcDY4ZCqR+eOm2BT86QPTNAhjM8CxBMd0Y23vayojh8UYihO -EmLrBJI/DsiWABgBXOvKWyI0EWXciOamVhSprmrgE2ff8Q9v1ZeraukPZwT03lL9 -obaQOa2aUsUMuPyZn46fDZq2j1O+V9M1K7OEtv/+exK9YZdi5mDZwgvOMp0pSRk6 -8Un/564/WsmRrRFaNw+dd0JxQrO08EAM7mOzFmbzCxfeUEKT+KF4qt5JWP/gOPSY -TDgbYqv5t1Co4woZCS2nVwKaJi0KhqEhOdFvPv12yGBoDvlDceAx8TSIl+Ym ------END CERTIFICATE----- ------BEGIN CERTIFICATE----- -MIIDQjCCAiqgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw -MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA9MQswCQYDVQQGEwJCRTEOMAwGA1UE -CgwFaVRleHQxHjAcBgNVBAMMFWlUZXh0VGVzdEludGVybWVkaWF0ZTCCASIwDQYJ -KoZIhvcNAQEBBQADggEPADCCAQoCggEBAM3t0dlZupS+5Z0EGHsnruz2ZRoVKwbp -IXwuOGuetobCTaaTfAyXmgXqcH1ZPi0u1dSzkWbHOdBNhRQLlk3ZtTfnCQrtijjU -U6jqkiMoMhap1/jEQPoU6CHP3bbwkSdZrnNriVxyGp2IKGwNDlg9fOBGuXdNei8N -fP5q9daV3oC9ckverNNKpcn9/0wYchISH9Y0a8N6FFUBqEYnjsEee7a5VIfgsP70 -jrhk53pNQJSObJhAFzhsbFNXxmWkZpi/YUJaBCSQYwQCUToRINyUMZOtsUIBh4es -8EpBt2utPkVifZvBo+prKUPTYX64iKko7zY5WHyP6vIV5BihYYv3Em8CAwEAAaNS -MFAwHQYDVR0OBBYEFKekg+UBOOgzMM6Ft6zCMa6k6H89MB8GA1UdIwQYMBaAFGTF -QTPAuR/St27lPFyjklKx/xYLMA4GA1UdDwEB/wQEAwIB5jANBgkqhkiG9w0BAQsF -AAOCAQEAadrnESocLAKEhOVcKC1tGOlDEI3oYkODcT4E3AOBqBq+gy4s5hfrQEpC -HqCje0pGNY1xgdcG5OPaKNSMT7+/PLE5As7aktNQxWuhDSH0SwKQPBbG+pfs0m3J -1R6M0WKsqvLWUtUgkzQp2f9pqu/XBrjqJnI5RwtNBBXJV8QBhLf4z/kGIk4noDM7 -2PcXdGNfl6dINcX8q3meZ1DkWTypgZ1pcEcvHU0rUPo+UPUpg6pOruOVnCERRiSx -z97Gqp1ZDa/jH1a+tjmbq4EN1vbULzVw+xsBIMuT7lsPTLdy/AHIx2UXVMGhHoYV -BHO096jz11DkzNKHloHf5sKPK2Ecjg== ------END CERTIFICATE----- ------BEGIN CERTIFICATE----- -MIIDQjCCAiqgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MR4wHAYDVQQDDBVpVGV4dFRlc3RJbnRlcm1lZGlhdGUw -IBcNMDAwMTAxMDAwMDAwWhgPMjQwMDAxMDEwMDAwMDBaMDUxCzAJBgNVBAYTAkJF -MQ4wDAYDVQQKDAVpVGV4dDEWMBQGA1UEAwwNaVRleHRUZXN0U2lnbjCCASIwDQYJ -KoZIhvcNAQEBBQADggEPADCCAQoCggEBAMaJ+B8HlKGXBhb64LuOiG/xGWn3RgU+ -D1i42xD4jRIjP3oL3hLefVtqQAgaP4HJa0mI1VWU2ezTbp5u11qo9eAefPq6jxaO -rbC3VyT/FE4EcoEvr48N/1ZB0jnKLQlO2lzzVCqnL9gyC+soakGwLzFs9SKjkI4h -/9YCnkoVtxOI/9ZDBf/QlJxrpknOPS9RQ8Y0OK+2OIb0kvK0f28EcvfopAnvOaVb -AHIWypIDabuRcw/YXRbmxvj2c+t1dGC7f4CLv7YKiFsEpydUJDWRUYGLnE7GvO9d -mS3oEFaI+Kre4HjSsaCF/Rgp9fpHKgaFTr8rKOGVgQHPlRFOrtGqXV8CAwEAAaNS -MFAwHQYDVR0OBBYEFKwAjNPp8T/Q6cWJGYu9aMR/ujVCMB8GA1UdIwQYMBaAFKek -g+UBOOgzMM6Ft6zCMa6k6H89MA4GA1UdDwEB/wQEAwIGwDANBgkqhkiG9w0BAQsF -AAOCAQEARWKct75OvbvIGRpTN4lvqyPJS/ZoVa/Dddbdo2rD669qltAce3/DFY2R -W0CNwIAxBh4CHqdlG5Od1qQ+BJH2pNGB6F2W/kmQuzaoo2PecDXNOfigRJASZO9O -nSFh+tQc+9DTNWrYyBb1MUEgZd4z0Q98dX3mWJ3YMG5Fb0pbexgpiAX5s9T3X+Da -olCzzmIRVIbce3UWv6T3fGvRJ/tyJ0VqvR8YBbVW15KaPabyZDE+v7QFizmoRFdw -7Dfv2tKIA/8ENO13BztYq1USTYhirfrR5Ki2oiul1Nmg48JgQRMHgfeBKMl9auyR -B6hPOeazdx/aJXMcZVIkYoWOPQsqVg== ------END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/crl-issuer.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/crl-issuer.cert.pem deleted file mode 100644 index 6236fcbf96..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/crl-issuer.cert.pem +++ /dev/null @@ -1,21 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDiTCCAnGgAwIBAgICEAIwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw -MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA6MQswCQYDVQQGEwJCRTEOMAwGA1UE -CgwFaVRleHQxGzAZBgNVBAMMEmlUZXh0VGVzdENybElzc3VlcjCCASIwDQYJKoZI -hvcNAQEBBQADggEPADCCAQoCggEBAJV6eBrtpxfCCiAkgz3wdLUqRio0/TBHDHg5 -oU1lHNeKoNkEG/kwdgPFN4YN9qufVZBi5mRY54NaVySKHo2w7/CrscZhbXtrBIQY -WzR0vRptsbmqV2xfBlqtPyPlRMt2SRnwe3Q4XqZSnX13bUTLO0SBlddGt7h/HQfD -vSzbekJWd8bPt+cH5Ke3y0cdFNylwP5yXEZdDyU9CtkzaBpHFM8vAEO00/kqahap -8Ox+Tea7zrAfoT58juJdGOlt7DRJs6jsLXsDT04zk47cpZ904R29lzU1zoMoiEjf -UTDO0c5fj4q4RCYzSpT3jX5VJEfKlooP6TX/GDVtH58+A3YQXuMCAwEAAaOBmzCB -mDAdBgNVHQ4EFgQU0zydGfhFz0j/TGolSJNUJEx9j2UwHwYDVR0jBBgwFoAUZMVB -M8C5H9K3buU8XKOSUrH/FgswDgYDVR0PAQH/BAQDAgHCMEYGA1UdHwQ/MD0wO6A5 -oDeGNWh0dHA6Ly9sb2NhbGhvc3QudGVzdC9kZWZhdWx0L2NybHMvZGVmYXVsdC9s -YXRlc3QuY3JsMA0GCSqGSIb3DQEBCwUAA4IBAQC21PZDRIiPsN/mNQYZYxrpLksz -XYEgl0ZWJzv5noTRmcDY4ZCqR+eOm2BT86QPTNAhjM8CxBMd0Y23vayojh8UYihO -EmLrBJI/DsiWABgBXOvKWyI0EWXciOamVhSprmrgE2ff8Q9v1ZeraukPZwT03lL9 -obaQOa2aUsUMuPyZn46fDZq2j1O+V9M1K7OEtv/+exK9YZdi5mDZwgvOMp0pSRk6 -8Un/564/WsmRrRFaNw+dd0JxQrO08EAM7mOzFmbzCxfeUEKT+KF4qt5JWP/gOPSY -TDgbYqv5t1Co4woZCS2nVwKaJi0KhqEhOdFvPv12yGBoDvlDceAx8TSIl+Ym ------END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/intermediate.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/intermediate.cert.pem deleted file mode 100644 index 420f53b153..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/intermediate.cert.pem +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDQjCCAiqgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw -MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA9MQswCQYDVQQGEwJCRTEOMAwGA1UE -CgwFaVRleHQxHjAcBgNVBAMMFWlUZXh0VGVzdEludGVybWVkaWF0ZTCCASIwDQYJ -KoZIhvcNAQEBBQADggEPADCCAQoCggEBAM3t0dlZupS+5Z0EGHsnruz2ZRoVKwbp -IXwuOGuetobCTaaTfAyXmgXqcH1ZPi0u1dSzkWbHOdBNhRQLlk3ZtTfnCQrtijjU -U6jqkiMoMhap1/jEQPoU6CHP3bbwkSdZrnNriVxyGp2IKGwNDlg9fOBGuXdNei8N -fP5q9daV3oC9ckverNNKpcn9/0wYchISH9Y0a8N6FFUBqEYnjsEee7a5VIfgsP70 -jrhk53pNQJSObJhAFzhsbFNXxmWkZpi/YUJaBCSQYwQCUToRINyUMZOtsUIBh4es -8EpBt2utPkVifZvBo+prKUPTYX64iKko7zY5WHyP6vIV5BihYYv3Em8CAwEAAaNS -MFAwHQYDVR0OBBYEFKekg+UBOOgzMM6Ft6zCMa6k6H89MB8GA1UdIwQYMBaAFGTF -QTPAuR/St27lPFyjklKx/xYLMA4GA1UdDwEB/wQEAwIB5jANBgkqhkiG9w0BAQsF -AAOCAQEAadrnESocLAKEhOVcKC1tGOlDEI3oYkODcT4E3AOBqBq+gy4s5hfrQEpC -HqCje0pGNY1xgdcG5OPaKNSMT7+/PLE5As7aktNQxWuhDSH0SwKQPBbG+pfs0m3J -1R6M0WKsqvLWUtUgkzQp2f9pqu/XBrjqJnI5RwtNBBXJV8QBhLf4z/kGIk4noDM7 -2PcXdGNfl6dINcX8q3meZ1DkWTypgZ1pcEcvHU0rUPo+UPUpg6pOruOVnCERRiSx -z97Gqp1ZDa/jH1a+tjmbq4EN1vbULzVw+xsBIMuT7lsPTLdy/AHIx2UXVMGhHoYV -BHO096jz11DkzNKHloHf5sKPK2Ecjg== ------END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/sign.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/sign.cert.pem deleted file mode 100644 index 26c2432936..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/crlIssuerRevokedBeforeSigningDate/sign.cert.pem +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDQjCCAiqgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MR4wHAYDVQQDDBVpVGV4dFRlc3RJbnRlcm1lZGlhdGUw -IBcNMDAwMTAxMDAwMDAwWhgPMjQwMDAxMDEwMDAwMDBaMDUxCzAJBgNVBAYTAkJF -MQ4wDAYDVQQKDAVpVGV4dDEWMBQGA1UEAwwNaVRleHRUZXN0U2lnbjCCASIwDQYJ -KoZIhvcNAQEBBQADggEPADCCAQoCggEBAMaJ+B8HlKGXBhb64LuOiG/xGWn3RgU+ -D1i42xD4jRIjP3oL3hLefVtqQAgaP4HJa0mI1VWU2ezTbp5u11qo9eAefPq6jxaO -rbC3VyT/FE4EcoEvr48N/1ZB0jnKLQlO2lzzVCqnL9gyC+soakGwLzFs9SKjkI4h -/9YCnkoVtxOI/9ZDBf/QlJxrpknOPS9RQ8Y0OK+2OIb0kvK0f28EcvfopAnvOaVb -AHIWypIDabuRcw/YXRbmxvj2c+t1dGC7f4CLv7YKiFsEpydUJDWRUYGLnE7GvO9d -mS3oEFaI+Kre4HjSsaCF/Rgp9fpHKgaFTr8rKOGVgQHPlRFOrtGqXV8CAwEAAaNS -MFAwHQYDVR0OBBYEFKwAjNPp8T/Q6cWJGYu9aMR/ujVCMB8GA1UdIwQYMBaAFKek -g+UBOOgzMM6Ft6zCMa6k6H89MA4GA1UdDwEB/wQEAwIGwDANBgkqhkiG9w0BAQsF -AAOCAQEARWKct75OvbvIGRpTN4lvqyPJS/ZoVa/Dddbdo2rD669qltAce3/DFY2R -W0CNwIAxBh4CHqdlG5Od1qQ+BJH2pNGB6F2W/kmQuzaoo2PecDXNOfigRJASZO9O -nSFh+tQc+9DTNWrYyBb1MUEgZd4z0Q98dX3mWJ3YMG5Fb0pbexgpiAX5s9T3X+Da -olCzzmIRVIbce3UWv6T3fGvRJ/tyJ0VqvR8YBbVW15KaPabyZDE+v7QFizmoRFdw -7Dfv2tKIA/8ENO13BztYq1USTYhirfrR5Ki2oiul1Nmg48JgQRMHgfeBKMl9auyR -B6hPOeazdx/aJXMcZVIkYoWOPQsqVg== ------END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/happyPath/ca.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/happyPath/ca.cert.pem deleted file mode 100644 index 607e8e4816..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/happyPath/ca.cert.pem +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDSzCCAjOgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw -MTAwMDAwMFoYDzI1MDAwMTAxMDAwMDAwWjA1MQswCQYDVQQGEwJCRTEOMAwGA1UE -CgwFaVRleHQxFjAUBgNVBAMMDWlUZXh0VGVzdFJvb3QwggEiMA0GCSqGSIb3DQEB -AQUAA4IBDwAwggEKAoIBAQDP6KUmxQzeXKuwodaQZ7IUoidvDeXWrjW7BNYmKhey -DX9SIeIwvuiKDVUD85pWyk6jhNUvQaYvGVOv/Pbu4NJHv9FKch2d9759ckMT+MXG -fGk/B6Ww1rlKsiHccWizQxah7R79eGweEvryPIx+hqxreCBH4yzMPjHld1C34/vC -nUGmozKT4KENiT6lXXiBm4D+u3siCPt1Gzxavvm2MUBTHBbhQ3/n1eS/FcqT4NhI -vXDpPiNouD9goI+4LwCW7b52dg7dXreQY/IfGCcHTcu7YK/OEW4Pqjpr13B5mEDS -DsCqrStoh8EQ+jB62n2Xv8TT4lQju/sZh0l65IiT8fUfAgMBAAGjYzBhMB0GA1Ud -DgQWBBRkxUEzwLkf0rdu5Txco5JSsf8WCzAfBgNVHSMEGDAWgBRkxUEzwLkf0rdu -5Txco5JSsf8WCzAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIC5DANBgkq -hkiG9w0BAQsFAAOCAQEARJOOUQkv9AgqElJmQjGDkRdJPxkDHZtRLGOk9p0E1KbL -lqQQdgzL7RuE4vfCROan6aBZmXFRviIPg/Gxw2hDSIv1NUZv3AIgM2b9+3y+4SQ6 -2a/sqh1JPLxwnLN+Mo5KwY/E/YlJ0N7rw3AONrLlqH89BRrBIiPjrg74zi6qPzGn -WB2awHsbl7AOtkD2dEud7lbyLda/hCw2RGPSBQMm50pWsuInWXzdtX/Ii9yTGMyD -kavUHX6DDVouZBSKOjmChP0fGPM17ORJNR92RbT2ygy+F0Zokh5XUgrKPr4/JTW5 -iIkycpjAXY9UEMfi8pFnnzVSRj65kkZvZZJzybelMQ== ------END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/happyPath/chain.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/happyPath/chain.pem deleted file mode 100644 index 2275b63aaa..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/happyPath/chain.pem +++ /dev/null @@ -1,81 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDSzCCAjOgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw -MTAwMDAwMFoYDzI1MDAwMTAxMDAwMDAwWjA1MQswCQYDVQQGEwJCRTEOMAwGA1UE -CgwFaVRleHQxFjAUBgNVBAMMDWlUZXh0VGVzdFJvb3QwggEiMA0GCSqGSIb3DQEB -AQUAA4IBDwAwggEKAoIBAQDP6KUmxQzeXKuwodaQZ7IUoidvDeXWrjW7BNYmKhey -DX9SIeIwvuiKDVUD85pWyk6jhNUvQaYvGVOv/Pbu4NJHv9FKch2d9759ckMT+MXG -fGk/B6Ww1rlKsiHccWizQxah7R79eGweEvryPIx+hqxreCBH4yzMPjHld1C34/vC -nUGmozKT4KENiT6lXXiBm4D+u3siCPt1Gzxavvm2MUBTHBbhQ3/n1eS/FcqT4NhI -vXDpPiNouD9goI+4LwCW7b52dg7dXreQY/IfGCcHTcu7YK/OEW4Pqjpr13B5mEDS -DsCqrStoh8EQ+jB62n2Xv8TT4lQju/sZh0l65IiT8fUfAgMBAAGjYzBhMB0GA1Ud -DgQWBBRkxUEzwLkf0rdu5Txco5JSsf8WCzAfBgNVHSMEGDAWgBRkxUEzwLkf0rdu -5Txco5JSsf8WCzAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIC5DANBgkq -hkiG9w0BAQsFAAOCAQEARJOOUQkv9AgqElJmQjGDkRdJPxkDHZtRLGOk9p0E1KbL -lqQQdgzL7RuE4vfCROan6aBZmXFRviIPg/Gxw2hDSIv1NUZv3AIgM2b9+3y+4SQ6 -2a/sqh1JPLxwnLN+Mo5KwY/E/YlJ0N7rw3AONrLlqH89BRrBIiPjrg74zi6qPzGn -WB2awHsbl7AOtkD2dEud7lbyLda/hCw2RGPSBQMm50pWsuInWXzdtX/Ii9yTGMyD -kavUHX6DDVouZBSKOjmChP0fGPM17ORJNR92RbT2ygy+F0Zokh5XUgrKPr4/JTW5 -iIkycpjAXY9UEMfi8pFnnzVSRj65kkZvZZJzybelMQ== ------END CERTIFICATE----- ------BEGIN CERTIFICATE----- -MIIDhTCCAm2gAwIBAgICEAIwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw -MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA6MQswCQYDVQQGEwJCRTEOMAwGA1UE -CgwFaVRleHQxGzAZBgNVBAMMEmlUZXh0VGVzdENybElzc3VlcjCCASIwDQYJKoZI -hvcNAQEBBQADggEPADCCAQoCggEBAJV6eBrtpxfCCiAkgz3wdLUqRio0/TBHDHg5 -oU1lHNeKoNkEG/kwdgPFN4YN9qufVZBi5mRY54NaVySKHo2w7/CrscZhbXtrBIQY -WzR0vRptsbmqV2xfBlqtPyPlRMt2SRnwe3Q4XqZSnX13bUTLO0SBlddGt7h/HQfD -vSzbekJWd8bPt+cH5Ke3y0cdFNylwP5yXEZdDyU9CtkzaBpHFM8vAEO00/kqahap -8Ox+Tea7zrAfoT58juJdGOlt7DRJs6jsLXsDT04zk47cpZ904R29lzU1zoMoiEjf -UTDO0c5fj4q4RCYzSpT3jX5VJEfKlooP6TX/GDVtH58+A3YQXuMCAwEAAaOBlzCB -lDAdBgNVHQ4EFgQU0zydGfhFz0j/TGolSJNUJEx9j2UwHwYDVR0jBBgwFoAUZMVB -M8C5H9K3buU8XKOSUrH/FgswDgYDVR0PAQH/BAQDAgHCMEIGA1UdHwQ7MDkwN6A1 -oDOGMWh0dHA6Ly9sb2NhbGhvc3QudGVzdC9kZWZhdWx0L2NybHMvY3JsL2xhdGVz -dC5jcmwwDQYJKoZIhvcNAQELBQADggEBALybI7Erkso0mOvu9ZVU2jzfE+aSZd9m -cCIQyytQtv8xi6Q4BfsEc/QLvLViybqkBvmrME/kFqVrFeEONgTy0LUO+OOZl1yZ -d/SWk81YVL3PJ2txHpehfHF5wlorDnZ5d/pn0sXu+tg55dmXQDniiZEHJxKQUEW2 -bYnC4qXhx0AXhpuTe6QbBZEY5DVNUVnenjtaixtlKqxA5hbTxkMiNol6A3wcTAgS -7yn8Bv5EzJobSI9rKoQuKMvnlj1FRX/0zr6hONAF6EOUjGG82GA2Aw4CrT4wOixL -s+fOY2SRtpZRMqD2hOF0t3kVKUDQx5HH87xc2ruGUM/rPLOYksnD7IQ= ------END CERTIFICATE----- ------BEGIN CERTIFICATE----- -MIIDQjCCAiqgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw -MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA9MQswCQYDVQQGEwJCRTEOMAwGA1UE -CgwFaVRleHQxHjAcBgNVBAMMFWlUZXh0VGVzdEludGVybWVkaWF0ZTCCASIwDQYJ -KoZIhvcNAQEBBQADggEPADCCAQoCggEBAM3t0dlZupS+5Z0EGHsnruz2ZRoVKwbp -IXwuOGuetobCTaaTfAyXmgXqcH1ZPi0u1dSzkWbHOdBNhRQLlk3ZtTfnCQrtijjU -U6jqkiMoMhap1/jEQPoU6CHP3bbwkSdZrnNriVxyGp2IKGwNDlg9fOBGuXdNei8N -fP5q9daV3oC9ckverNNKpcn9/0wYchISH9Y0a8N6FFUBqEYnjsEee7a5VIfgsP70 -jrhk53pNQJSObJhAFzhsbFNXxmWkZpi/YUJaBCSQYwQCUToRINyUMZOtsUIBh4es -8EpBt2utPkVifZvBo+prKUPTYX64iKko7zY5WHyP6vIV5BihYYv3Em8CAwEAAaNS -MFAwHQYDVR0OBBYEFKekg+UBOOgzMM6Ft6zCMa6k6H89MB8GA1UdIwQYMBaAFGTF -QTPAuR/St27lPFyjklKx/xYLMA4GA1UdDwEB/wQEAwIB5jANBgkqhkiG9w0BAQsF -AAOCAQEAadrnESocLAKEhOVcKC1tGOlDEI3oYkODcT4E3AOBqBq+gy4s5hfrQEpC -HqCje0pGNY1xgdcG5OPaKNSMT7+/PLE5As7aktNQxWuhDSH0SwKQPBbG+pfs0m3J -1R6M0WKsqvLWUtUgkzQp2f9pqu/XBrjqJnI5RwtNBBXJV8QBhLf4z/kGIk4noDM7 -2PcXdGNfl6dINcX8q3meZ1DkWTypgZ1pcEcvHU0rUPo+UPUpg6pOruOVnCERRiSx -z97Gqp1ZDa/jH1a+tjmbq4EN1vbULzVw+xsBIMuT7lsPTLdy/AHIx2UXVMGhHoYV -BHO096jz11DkzNKHloHf5sKPK2Ecjg== ------END CERTIFICATE----- ------BEGIN CERTIFICATE----- -MIIDQjCCAiqgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MR4wHAYDVQQDDBVpVGV4dFRlc3RJbnRlcm1lZGlhdGUw -IBcNMDAwMTAxMDAwMDAwWhgPMjQwMDAxMDEwMDAwMDBaMDUxCzAJBgNVBAYTAkJF -MQ4wDAYDVQQKDAVpVGV4dDEWMBQGA1UEAwwNaVRleHRUZXN0U2lnbjCCASIwDQYJ -KoZIhvcNAQEBBQADggEPADCCAQoCggEBAMaJ+B8HlKGXBhb64LuOiG/xGWn3RgU+ -D1i42xD4jRIjP3oL3hLefVtqQAgaP4HJa0mI1VWU2ezTbp5u11qo9eAefPq6jxaO -rbC3VyT/FE4EcoEvr48N/1ZB0jnKLQlO2lzzVCqnL9gyC+soakGwLzFs9SKjkI4h -/9YCnkoVtxOI/9ZDBf/QlJxrpknOPS9RQ8Y0OK+2OIb0kvK0f28EcvfopAnvOaVb -AHIWypIDabuRcw/YXRbmxvj2c+t1dGC7f4CLv7YKiFsEpydUJDWRUYGLnE7GvO9d -mS3oEFaI+Kre4HjSsaCF/Rgp9fpHKgaFTr8rKOGVgQHPlRFOrtGqXV8CAwEAAaNS -MFAwHQYDVR0OBBYEFKwAjNPp8T/Q6cWJGYu9aMR/ujVCMB8GA1UdIwQYMBaAFKek -g+UBOOgzMM6Ft6zCMa6k6H89MA4GA1UdDwEB/wQEAwIGwDANBgkqhkiG9w0BAQsF -AAOCAQEARWKct75OvbvIGRpTN4lvqyPJS/ZoVa/Dddbdo2rD669qltAce3/DFY2R -W0CNwIAxBh4CHqdlG5Od1qQ+BJH2pNGB6F2W/kmQuzaoo2PecDXNOfigRJASZO9O -nSFh+tQc+9DTNWrYyBb1MUEgZd4z0Q98dX3mWJ3YMG5Fb0pbexgpiAX5s9T3X+Da -olCzzmIRVIbce3UWv6T3fGvRJ/tyJ0VqvR8YBbVW15KaPabyZDE+v7QFizmoRFdw -7Dfv2tKIA/8ENO13BztYq1USTYhirfrR5Ki2oiul1Nmg48JgQRMHgfeBKMl9auyR -B6hPOeazdx/aJXMcZVIkYoWOPQsqVg== ------END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/happyPath/crl-issuer.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/happyPath/crl-issuer.cert.pem deleted file mode 100644 index 030a6784df..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/happyPath/crl-issuer.cert.pem +++ /dev/null @@ -1,21 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDhTCCAm2gAwIBAgICEAIwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw -MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA6MQswCQYDVQQGEwJCRTEOMAwGA1UE -CgwFaVRleHQxGzAZBgNVBAMMEmlUZXh0VGVzdENybElzc3VlcjCCASIwDQYJKoZI -hvcNAQEBBQADggEPADCCAQoCggEBAJV6eBrtpxfCCiAkgz3wdLUqRio0/TBHDHg5 -oU1lHNeKoNkEG/kwdgPFN4YN9qufVZBi5mRY54NaVySKHo2w7/CrscZhbXtrBIQY -WzR0vRptsbmqV2xfBlqtPyPlRMt2SRnwe3Q4XqZSnX13bUTLO0SBlddGt7h/HQfD -vSzbekJWd8bPt+cH5Ke3y0cdFNylwP5yXEZdDyU9CtkzaBpHFM8vAEO00/kqahap -8Ox+Tea7zrAfoT58juJdGOlt7DRJs6jsLXsDT04zk47cpZ904R29lzU1zoMoiEjf -UTDO0c5fj4q4RCYzSpT3jX5VJEfKlooP6TX/GDVtH58+A3YQXuMCAwEAAaOBlzCB -lDAdBgNVHQ4EFgQU0zydGfhFz0j/TGolSJNUJEx9j2UwHwYDVR0jBBgwFoAUZMVB -M8C5H9K3buU8XKOSUrH/FgswDgYDVR0PAQH/BAQDAgHCMEIGA1UdHwQ7MDkwN6A1 -oDOGMWh0dHA6Ly9sb2NhbGhvc3QudGVzdC9kZWZhdWx0L2NybHMvY3JsL2xhdGVz -dC5jcmwwDQYJKoZIhvcNAQELBQADggEBALybI7Erkso0mOvu9ZVU2jzfE+aSZd9m -cCIQyytQtv8xi6Q4BfsEc/QLvLViybqkBvmrME/kFqVrFeEONgTy0LUO+OOZl1yZ -d/SWk81YVL3PJ2txHpehfHF5wlorDnZ5d/pn0sXu+tg55dmXQDniiZEHJxKQUEW2 -bYnC4qXhx0AXhpuTe6QbBZEY5DVNUVnenjtaixtlKqxA5hbTxkMiNol6A3wcTAgS -7yn8Bv5EzJobSI9rKoQuKMvnlj1FRX/0zr6hONAF6EOUjGG82GA2Aw4CrT4wOixL -s+fOY2SRtpZRMqD2hOF0t3kVKUDQx5HH87xc2ruGUM/rPLOYksnD7IQ= ------END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/happyPath/intermediate.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/happyPath/intermediate.cert.pem deleted file mode 100644 index 420f53b153..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/happyPath/intermediate.cert.pem +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDQjCCAiqgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw -MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA9MQswCQYDVQQGEwJCRTEOMAwGA1UE -CgwFaVRleHQxHjAcBgNVBAMMFWlUZXh0VGVzdEludGVybWVkaWF0ZTCCASIwDQYJ -KoZIhvcNAQEBBQADggEPADCCAQoCggEBAM3t0dlZupS+5Z0EGHsnruz2ZRoVKwbp -IXwuOGuetobCTaaTfAyXmgXqcH1ZPi0u1dSzkWbHOdBNhRQLlk3ZtTfnCQrtijjU -U6jqkiMoMhap1/jEQPoU6CHP3bbwkSdZrnNriVxyGp2IKGwNDlg9fOBGuXdNei8N -fP5q9daV3oC9ckverNNKpcn9/0wYchISH9Y0a8N6FFUBqEYnjsEee7a5VIfgsP70 -jrhk53pNQJSObJhAFzhsbFNXxmWkZpi/YUJaBCSQYwQCUToRINyUMZOtsUIBh4es -8EpBt2utPkVifZvBo+prKUPTYX64iKko7zY5WHyP6vIV5BihYYv3Em8CAwEAAaNS -MFAwHQYDVR0OBBYEFKekg+UBOOgzMM6Ft6zCMa6k6H89MB8GA1UdIwQYMBaAFGTF -QTPAuR/St27lPFyjklKx/xYLMA4GA1UdDwEB/wQEAwIB5jANBgkqhkiG9w0BAQsF -AAOCAQEAadrnESocLAKEhOVcKC1tGOlDEI3oYkODcT4E3AOBqBq+gy4s5hfrQEpC -HqCje0pGNY1xgdcG5OPaKNSMT7+/PLE5As7aktNQxWuhDSH0SwKQPBbG+pfs0m3J -1R6M0WKsqvLWUtUgkzQp2f9pqu/XBrjqJnI5RwtNBBXJV8QBhLf4z/kGIk4noDM7 -2PcXdGNfl6dINcX8q3meZ1DkWTypgZ1pcEcvHU0rUPo+UPUpg6pOruOVnCERRiSx -z97Gqp1ZDa/jH1a+tjmbq4EN1vbULzVw+xsBIMuT7lsPTLdy/AHIx2UXVMGhHoYV -BHO096jz11DkzNKHloHf5sKPK2Ecjg== ------END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/happyPath/sign.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/happyPath/sign.cert.pem deleted file mode 100644 index 26c2432936..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/happyPath/sign.cert.pem +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDQjCCAiqgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MR4wHAYDVQQDDBVpVGV4dFRlc3RJbnRlcm1lZGlhdGUw -IBcNMDAwMTAxMDAwMDAwWhgPMjQwMDAxMDEwMDAwMDBaMDUxCzAJBgNVBAYTAkJF -MQ4wDAYDVQQKDAVpVGV4dDEWMBQGA1UEAwwNaVRleHRUZXN0U2lnbjCCASIwDQYJ -KoZIhvcNAQEBBQADggEPADCCAQoCggEBAMaJ+B8HlKGXBhb64LuOiG/xGWn3RgU+ -D1i42xD4jRIjP3oL3hLefVtqQAgaP4HJa0mI1VWU2ezTbp5u11qo9eAefPq6jxaO -rbC3VyT/FE4EcoEvr48N/1ZB0jnKLQlO2lzzVCqnL9gyC+soakGwLzFs9SKjkI4h -/9YCnkoVtxOI/9ZDBf/QlJxrpknOPS9RQ8Y0OK+2OIb0kvK0f28EcvfopAnvOaVb -AHIWypIDabuRcw/YXRbmxvj2c+t1dGC7f4CLv7YKiFsEpydUJDWRUYGLnE7GvO9d -mS3oEFaI+Kre4HjSsaCF/Rgp9fpHKgaFTr8rKOGVgQHPlRFOrtGqXV8CAwEAAaNS -MFAwHQYDVR0OBBYEFKwAjNPp8T/Q6cWJGYu9aMR/ujVCMB8GA1UdIwQYMBaAFKek -g+UBOOgzMM6Ft6zCMa6k6H89MA4GA1UdDwEB/wQEAwIGwDANBgkqhkiG9w0BAQsF -AAOCAQEARWKct75OvbvIGRpTN4lvqyPJS/ZoVa/Dddbdo2rD669qltAce3/DFY2R -W0CNwIAxBh4CHqdlG5Od1qQ+BJH2pNGB6F2W/kmQuzaoo2PecDXNOfigRJASZO9O -nSFh+tQc+9DTNWrYyBb1MUEgZd4z0Q98dX3mWJ3YMG5Fb0pbexgpiAX5s9T3X+Da -olCzzmIRVIbce3UWv6T3fGvRJ/tyJ0VqvR8YBbVW15KaPabyZDE+v7QFizmoRFdw -7Dfv2tKIA/8ENO13BztYq1USTYhirfrR5Ki2oiul1Nmg48JgQRMHgfeBKMl9auyR -B6hPOeazdx/aJXMcZVIkYoWOPQsqVg== ------END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/keys/crl-key.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/keys/crl-key.pem deleted file mode 100644 index de681e12e4..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/keys/crl-key.pem +++ /dev/null @@ -1,28 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCVenga7acXwgog -JIM98HS1KkYqNP0wRwx4OaFNZRzXiqDZBBv5MHYDxTeGDfarn1WQYuZkWOeDWlck -ih6NsO/wq7HGYW17awSEGFs0dL0abbG5qldsXwZarT8j5UTLdkkZ8Ht0OF6mUp19 -d21EyztEgZXXRre4fx0Hw70s23pCVnfGz7fnB+Snt8tHHRTcpcD+clxGXQ8lPQrZ -M2gaRxTPLwBDtNP5KmoWqfDsfk3mu86wH6E+fI7iXRjpbew0SbOo7C17A09OM5OO -3KWfdOEdvZc1Nc6DKIhI31EwztHOX4+KuEQmM0qU941+VSRHypaKD+k1/xg1bR+f -PgN2EF7jAgMBAAECggEAA5Go5urOYYi59dT0A+sjg49l1iVC2ziRuYoHm849PJw9 -9yXcFK5KFp71Lvs2l4nEtjvyuk2Gc1s113Erd5Xw7Y+YWdEC0BPnDuxcnnQf/Yep -ohyswJThI2ePVAu/Omv4sxOE9jGJBzma3UMJ8k0bC37qXGspudBTmayjUZFsafxd -2mfQZOIUtMU0/LZPwr/TTdqFlHZmBIuUkcH8P9vIEyKXaFC/lfrhnRAi9Hu56S/H -VWiYFX/tSX7Up0DqAKruCVTEzSvskWp9xICs6IzfwB6Y4LEFi9QD7SezA5DdDX8k -wyqCJosOM2ZS+vHf33qGoCaYANUlEQcpYhItNB/6GQKBgQDOgb57wvRArXeG/cxe -L3qZgSVToRBhODi9UkbuXusPjl48nBj/QcxmFfEN3PFVe2Hw7TqcN1b6GoxYuc2I -0PCGzo37gru+OUPrGmnCAPECsDqRXwmA7NbJCvVwN1S7S3aZ0W2psPOTFDlYy9+T -7JgVXkRVgNWheMOrTzXky3eQPwKBgQC5Tbz1Wdw6iI/tAlYI+ektgRxDnhYfHGZV -/0ew9r3iIPxpYU6p3FsL4grZLfpo6zFad72aG6r81a8iMA+TwVuIPtCV4rX8Xe3Y -t+OiXBw94ZgEzsqFePqpCXDJOiNCf2NBSxthObNaLPKa8L4RtQ7udIs4VID4hHRq -o+dyCSEIXQKBgC++b3vNpwsNEAV1yDo+X+n9odOj+VWA2h1rWFrkNxRxpff9Xwok -/Ezd5c1+t4076Xj6YAKeCM3qNWiODKcFJ5cDSnBL2XwxYTKJ+MmRzicA94mEn33f -RAlXL0eygzSKTfFiKiiBcM8gbeHJwPdCTCcklEfwcXPTp+mDdsJfCFWhAoGAMQf1 -0MHXORG7a44rr7JY1baNAQNKfS7pkSW8FYIkWjo6L7QUuXNaD/nevvqggLSC2ZpH -bAiYJNBxx80JwiHuk01zqcVUPBOqhKabr/FJc8JGlDcXdVu+j4207znX7JeCbttt -wjsfTuQHyaGb2VmcOtJRqDUL7zY1C6aU7iKmP+0CgYEAl3AtXkFCGhHJDOHLD25z -Se4qR1u2rr3mQnqjcpkoGzvI26UoQbcGHHvh6m8G7Vl1xdIbeGBQQhGR5iL0Mw0e -FsasXqhh9YiG7Zf3eOwCJ/rGL4OJhCWLZVrcCX4eWaq2eVuQ5W3SARDKYb7mVhkr -TdVlWVdlYXCWQHqp1jQ6cio= ------END PRIVATE KEY----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/keys/im_key.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/keys/im_key.pem deleted file mode 100644 index 7a85540d40..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/keys/im_key.pem +++ /dev/null @@ -1,28 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDN7dHZWbqUvuWd -BBh7J67s9mUaFSsG6SF8LjhrnraGwk2mk3wMl5oF6nB9WT4tLtXUs5FmxznQTYUU -C5ZN2bU35wkK7Yo41FOo6pIjKDIWqdf4xED6FOghz9228JEnWa5za4lcchqdiChs -DQ5YPXzgRrl3TXovDXz+avXWld6AvXJL3qzTSqXJ/f9MGHISEh/WNGvDehRVAahG -J47BHnu2uVSH4LD+9I64ZOd6TUCUjmyYQBc4bGxTV8ZlpGaYv2FCWgQkkGMEAlE6 -ESDclDGTrbFCAYeHrPBKQbdrrT5FYn2bwaPqaylD02F+uIipKO82OVh8j+ryFeQY -oWGL9xJvAgMBAAECggEADxzAVTSOCkN2I089IrCXWEF+yuq5xSCPugbEUjWMDJiu -zSYuqNfpUDzTs4c8lmFFBP6GkaXWOtCtjvqItb7f2zHjyn8DMUd3ukI4pkbZYitl -s5ZndFLbdDvGeBnwdRRSRpsiMfwXsu7elItivZwJkYXvL2+qo1BYl20vDGfkM8tR -mrCDFmW9RG73XKpn6Dd9C5HPV27r1nNQTjFNKx+Vv2ALNkNN1Ap3tZ7cTibY/Bt/ -muCU7SWWBXwjJsKQkkZUjVajWDRBA3wq9rnOilMt7rRbVyq6QIT6uCZYd9ouBBg0 -gcKjbA0FdUqJIdHWPSaJobuvtIAhoN6onhULOdq4hQKBgQDy3qbFpsmonXctY5mC -WV8PkX+YQZC0jC6YGLYbWO7lZ4rfrQvKEI8VbkMS82XzGLoSN05rAJonccsb0/Ch -4Z5AeR77o2z+AE71EzvEKXWGABWf1n+kiiu/2S6TfvTui3ToAPMrFr5p8y6Qer2h -V+1r2o5akm9JQQsEJ9e/z3Zm3QKBgQDZD+dNFWmBs9HbDm7iYZ/BJFMoVwXBweWS -qmPik99hIvyak76srnQtkW1kKXrzKICB9dbiBPYb8eicQZv1Nu9efrOIGa82gdCO -6QV3ToHYzMWnyan/j38nYtU0CtABQO3YWr0pxfHqpw9NmnUPBqwFpVGLppcA+Dg5 -xs8LbQk7uwKBgB9dwgwkzkaIj6u9AUZkZHKOR/xR+25V7G6YQmylv7TA+p6Iqs0d -9ly+MMtxw+jxeJaBrg8DtOUDPUgKxzkg+l85RVcadCkZwRjFsyJSeGsl96T8/t8x -ORU951YFP3zPZfnQpZcbCNyGG61tLLB5uqADSf9Iijbbv6B5xNNw58nBAoGAY4pd -ggX9ulMiO5ik1P/76PCliexOYYpvoxCsea1iVQNcX+69FCd0c6krRzGWhofeVrrM -bh3kVvBawb18rbkhkG3+Gr3ckdx6Le9CaHICLc/KHKXoZaACqaczKoiC1vBVolAK -S2vRAtDVvbrFT7y5imVDvg0JVpJ+BlDbhdvczh0CgYA14jJLY+IWAjxNzo8NdCi7 -iayF+nM4n0z0eW7/5T3hEPDan7DSg1O1cEUiKckt5LjZWv6xoxQcqYoN3H9jkchM -kMUOqvkb2UE+MllGVX+GLZkCJdTXpmDIXL/o23sM8awmiIpYWAbgQ9cSBoR13Pka -Nn3HfG6ejOSPFRHun+cw7g== ------END PRIVATE KEY----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/keys/root_key.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/keys/root_key.pem deleted file mode 100644 index 971c1f3141..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/keys/root_key.pem +++ /dev/null @@ -1,28 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDP6KUmxQzeXKuw -odaQZ7IUoidvDeXWrjW7BNYmKheyDX9SIeIwvuiKDVUD85pWyk6jhNUvQaYvGVOv -/Pbu4NJHv9FKch2d9759ckMT+MXGfGk/B6Ww1rlKsiHccWizQxah7R79eGweEvry -PIx+hqxreCBH4yzMPjHld1C34/vCnUGmozKT4KENiT6lXXiBm4D+u3siCPt1Gzxa -vvm2MUBTHBbhQ3/n1eS/FcqT4NhIvXDpPiNouD9goI+4LwCW7b52dg7dXreQY/If -GCcHTcu7YK/OEW4Pqjpr13B5mEDSDsCqrStoh8EQ+jB62n2Xv8TT4lQju/sZh0l6 -5IiT8fUfAgMBAAECggEAN3LV/PGHvZQcjBaVeVzWfy9B8hnURv2eQdsH3BTUzf1Q -jBCSWSrJLOxiVJP3AReignTOQHSzRBNuoNyH5Oyb2FvdjwvBP1yP9rfvENgDsyyC -CzfYZkHWGAhLBJZQdKK7WgM6BSLFPv4T5F/mnmX/fQgEH/gD/hLGTusT4X9RqTS4 -1cnScT+zPn/FedqLHiNQ3MTAQQBrSl/DoUPU8HyDDN1uF9/TbvEaMYl/iXyBPYpZ -AqhS7Je6Hue5Q86Tqd7Hj044OzRcjci2X6XeB0aAQc9VppAoI92hYsv59zLiHpw7 -81fRXazsyzQuctu8ep6Q08YMBN2YJN2XLj0IANs6lQKBgQD/lxTVtP1nffeV/Csj -j051N7N0SYASZtAXjM4x2z/0dRpka0C05kimT5ZpYGIVmWmTb4EzGYzIBOO4mEyz -1AawmDLkFDELc03XM7Ng8YrMvi0pl7TpPorc1fvVjcEXCfzRC5FiQ8kTBZ68zcMA -5+6uNt4lxaCiiqWswWQWl8l2xQKBgQDQPf2hHYOkNtUg7AsSdou3+dTQj90DlXOE -V/SotkStwIQcWefD/IcGQbAI1NGzXwipXsxQ//G9slDXZSKgxHpXT+pmrUDc5FHW -v8XMH+dtzOkCrExh9S2r7HFp6UlwOWomwePkMEKWWCZIV/wz8HzuERH7MZvgcTYU -Cb1mlZPakwKBgQCvC3XFdxMl0evC2NVioT8GoINS3RPNhoR13IVLN/FxJtJQe/Pw -8NZIsLE+sjf6uvrHctJ1gMYeJtsfDY9aiZebUmFoOzvrr6hb/piXiFWbK5QarD/G -joLkA9lZxJ+9e6WeNeH3/pyzXmH8xJ8M+8tHnWQ/Uj5Vk8crrbcykfn0UQKBgH0O -TUs9SzoJx9I+jqOm119DxF7/lk25qaa3n3DWDMZ/j5brEvkqpPfH6OxUyh47GxuD -l5WpLsap2EySKsp7U7Eth+njb8l3wAIEJsff/P5+iQwW5sQJFkVh9/YPqA+iGzJt -S+tUZBiflVXqqMWUTaI2VCMS9rZBpqU/+CMr/p/LAoGBAIWfEfkqU2miHOcyEVjr -6PmTzhii9nXjV/E5tK84v3a9B+ItLLYiiPiD15t1l7tu3Rq2hnwItM4/8nM6AxNR -Q9kDjj+UdTiK2sc2vxry/nlrnyjl/ls8z02QUiIGMNZLdqf58dROc5h5QEM+dNaU -LuDLIIf61vUhT2UHcQXJ33N+ ------END PRIVATE KEY----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/keys/sign-key.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/keys/sign-key.pem deleted file mode 100644 index 61f32d1105..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/keys/sign-key.pem +++ /dev/null @@ -1,28 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDGifgfB5ShlwYW -+uC7johv8Rlp90YFPg9YuNsQ+I0SIz96C94S3n1bakAIGj+ByWtJiNVVlNns026e -btdaqPXgHnz6uo8Wjq2wt1ck/xROBHKBL6+PDf9WQdI5yi0JTtpc81Qqpy/YMgvr -KGpBsC8xbPUio5COIf/WAp5KFbcTiP/WQwX/0JSca6ZJzj0vUUPGNDivtjiG9JLy -tH9vBHL36KQJ7zmlWwByFsqSA2m7kXMP2F0W5sb49nPrdXRgu3+Ai7+2CohbBKcn -VCQ1kVGBi5xOxrzvXZkt6BBWiPiq3uB40rGghf0YKfX6RyoGhU6/KyjhlYEBz5UR -Tq7Rql1fAgMBAAECggEAFCf+sjvFSbB49E1NEo2SaXb7QwhRKggWa8X8q5joTY6Z -i6z3w0emR2kejhQIHYeS5ljHe9RMWaBPizMqlvAvYi0GODhHfZ1HofjDFqT07UTD -UT1DoAzmPt4Y1zgg4WCJh8VGZrwpfdP65MlqHDgkWmq66mTbsKpf/FywsEnLF+bz -WWgKJP8NIxtI+iSipgGLOW+DtYO9gvmF9dDjPHISWkcYGetuz2k+a3n1NE6vwx6S -NZVC7pkzFGTg+IH8b4e64mN3jUoxSi9+KBZRApFYJRL07v8wBeJf7cN58NEzQjhG -5RwpBEjpcqEP/dYUbze6WBXC8G2KGrteBFBSqdb+5QKBgQDyMlDVblRWDBjD8RYL -9bXBooXsMIeP+i2fiTEEzpTsumha4T8KmPJr33bXOW9CZw/SUJ5WI3bBIzdzbxf9 -elBCoUJgO94wmnJdZNHeuLLb0AwTc0CMW5V8/5gu7e9Kxkyh6hojEo6POlWagGJz -3B1deqpJVe76oyLXMY4tavgLfQKBgQDR2q6zbHuubTeowDJD8CsrORB2+SJEo4Pe -1WzkP+0PX9y6n8Uk9FvjyU3MIPdD3hVruJwj7cHfpNg/UksTOjaWMI26VBKUfcQo -uZ84i4iwRrREAasgPc+evm1xAkmH5qDcXwIx7PxYW1tnRd8BuJZ6DpNDiY3rEf5D -Q2k0TumLCwKBgQDFHUJAkmy9I1c8kYgZ774ffAB2/AA4o6ph/ywP93mpOQUZgdzm -6RfTx6lW/P2aE3sC9m4HORG7msfUgQQLXnLX55q368Gn2OtfK2DLXZLj520Mn25X -TWpas0LOXwOz3bQcywS+qqmv1BA7kGWQWgLkQ6M30GKRRhhi/4fxWu/JmQKBgC6G -r2j0Sk+Xw1lUk1BgtRF2K2JVRfW10wzagLPyQFrCRCvUNF9HFgBgpzD0th2D5Xfm -jCejFPLCl3cihaaTp3qQ9Ts0XJIzeAQXc2eT+BAs/NZ/EDOrwJZPXfBKM4c/6LYz -EkeDZUcpqhAxe4nkJOiWxquYmbBeYuMC1RZV0I2VAoGAac0Kt0+Rk1jJithh6STu -BNQgswvfE2XFuMtySyByeNClzJofE4fHFhAHlhoHszPGSiNEDw4RvOxPWgBdLyFz -cWUXtL0GMzkwLfLCwRedFx65ijXbxUMIZXWYiG0GQA3w9fcDFYwugRMP5wKC9vMm -nTRzEOnBVWIXKLw7RdTBV4o= ------END PRIVATE KEY----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/missingIssuer/crl-issuer.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/missingIssuer/crl-issuer.cert.pem deleted file mode 100644 index 030a6784df..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/missingIssuer/crl-issuer.cert.pem +++ /dev/null @@ -1,21 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDhTCCAm2gAwIBAgICEAIwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw -MTAwMDAwMFoYDzI0NTAwMTAxMDAwMDAwWjA6MQswCQYDVQQGEwJCRTEOMAwGA1UE -CgwFaVRleHQxGzAZBgNVBAMMEmlUZXh0VGVzdENybElzc3VlcjCCASIwDQYJKoZI -hvcNAQEBBQADggEPADCCAQoCggEBAJV6eBrtpxfCCiAkgz3wdLUqRio0/TBHDHg5 -oU1lHNeKoNkEG/kwdgPFN4YN9qufVZBi5mRY54NaVySKHo2w7/CrscZhbXtrBIQY -WzR0vRptsbmqV2xfBlqtPyPlRMt2SRnwe3Q4XqZSnX13bUTLO0SBlddGt7h/HQfD -vSzbekJWd8bPt+cH5Ke3y0cdFNylwP5yXEZdDyU9CtkzaBpHFM8vAEO00/kqahap -8Ox+Tea7zrAfoT58juJdGOlt7DRJs6jsLXsDT04zk47cpZ904R29lzU1zoMoiEjf -UTDO0c5fj4q4RCYzSpT3jX5VJEfKlooP6TX/GDVtH58+A3YQXuMCAwEAAaOBlzCB -lDAdBgNVHQ4EFgQU0zydGfhFz0j/TGolSJNUJEx9j2UwHwYDVR0jBBgwFoAUZMVB -M8C5H9K3buU8XKOSUrH/FgswDgYDVR0PAQH/BAQDAgHCMEIGA1UdHwQ7MDkwN6A1 -oDOGMWh0dHA6Ly9sb2NhbGhvc3QudGVzdC9kZWZhdWx0L2NybHMvY3JsL2xhdGVz -dC5jcmwwDQYJKoZIhvcNAQELBQADggEBALybI7Erkso0mOvu9ZVU2jzfE+aSZd9m -cCIQyytQtv8xi6Q4BfsEc/QLvLViybqkBvmrME/kFqVrFeEONgTy0LUO+OOZl1yZ -d/SWk81YVL3PJ2txHpehfHF5wlorDnZ5d/pn0sXu+tg55dmXQDniiZEHJxKQUEW2 -bYnC4qXhx0AXhpuTe6QbBZEY5DVNUVnenjtaixtlKqxA5hbTxkMiNol6A3wcTAgS -7yn8Bv5EzJobSI9rKoQuKMvnlj1FRX/0zr6hONAF6EOUjGG82GA2Aw4CrT4wOixL -s+fOY2SRtpZRMqD2hOF0t3kVKUDQx5HH87xc2ruGUM/rPLOYksnD7IQ= ------END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/missingIssuer/sign.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/missingIssuer/sign.cert.pem deleted file mode 100644 index 26c2432936..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CRLValidatorTest/missingIssuer/sign.cert.pem +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDQjCCAiqgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MR4wHAYDVQQDDBVpVGV4dFRlc3RJbnRlcm1lZGlhdGUw -IBcNMDAwMTAxMDAwMDAwWhgPMjQwMDAxMDEwMDAwMDBaMDUxCzAJBgNVBAYTAkJF -MQ4wDAYDVQQKDAVpVGV4dDEWMBQGA1UEAwwNaVRleHRUZXN0U2lnbjCCASIwDQYJ -KoZIhvcNAQEBBQADggEPADCCAQoCggEBAMaJ+B8HlKGXBhb64LuOiG/xGWn3RgU+ -D1i42xD4jRIjP3oL3hLefVtqQAgaP4HJa0mI1VWU2ezTbp5u11qo9eAefPq6jxaO -rbC3VyT/FE4EcoEvr48N/1ZB0jnKLQlO2lzzVCqnL9gyC+soakGwLzFs9SKjkI4h -/9YCnkoVtxOI/9ZDBf/QlJxrpknOPS9RQ8Y0OK+2OIb0kvK0f28EcvfopAnvOaVb -AHIWypIDabuRcw/YXRbmxvj2c+t1dGC7f4CLv7YKiFsEpydUJDWRUYGLnE7GvO9d -mS3oEFaI+Kre4HjSsaCF/Rgp9fpHKgaFTr8rKOGVgQHPlRFOrtGqXV8CAwEAAaNS -MFAwHQYDVR0OBBYEFKwAjNPp8T/Q6cWJGYu9aMR/ujVCMB8GA1UdIwQYMBaAFKek -g+UBOOgzMM6Ft6zCMa6k6H89MA4GA1UdDwEB/wQEAwIGwDANBgkqhkiG9w0BAQsF -AAOCAQEARWKct75OvbvIGRpTN4lvqyPJS/ZoVa/Dddbdo2rD669qltAce3/DFY2R -W0CNwIAxBh4CHqdlG5Od1qQ+BJH2pNGB6F2W/kmQuzaoo2PecDXNOfigRJASZO9O -nSFh+tQc+9DTNWrYyBb1MUEgZd4z0Q98dX3mWJ3YMG5Fb0pbexgpiAX5s9T3X+Da -olCzzmIRVIbce3UWv6T3fGvRJ/tyJ0VqvR8YBbVW15KaPabyZDE+v7QFizmoRFdw -7Dfv2tKIA/8ENO13BztYq1USTYhirfrR5Ki2oiul1Nmg48JgQRMHgfeBKMl9auyR -B6hPOeazdx/aJXMcZVIkYoWOPQsqVg== ------END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/ca.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/ca.cert.pem deleted file mode 100644 index 607e8e4816..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/ca.cert.pem +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDSzCCAjOgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw -MTAwMDAwMFoYDzI1MDAwMTAxMDAwMDAwWjA1MQswCQYDVQQGEwJCRTEOMAwGA1UE -CgwFaVRleHQxFjAUBgNVBAMMDWlUZXh0VGVzdFJvb3QwggEiMA0GCSqGSIb3DQEB -AQUAA4IBDwAwggEKAoIBAQDP6KUmxQzeXKuwodaQZ7IUoidvDeXWrjW7BNYmKhey -DX9SIeIwvuiKDVUD85pWyk6jhNUvQaYvGVOv/Pbu4NJHv9FKch2d9759ckMT+MXG -fGk/B6Ww1rlKsiHccWizQxah7R79eGweEvryPIx+hqxreCBH4yzMPjHld1C34/vC -nUGmozKT4KENiT6lXXiBm4D+u3siCPt1Gzxavvm2MUBTHBbhQ3/n1eS/FcqT4NhI -vXDpPiNouD9goI+4LwCW7b52dg7dXreQY/IfGCcHTcu7YK/OEW4Pqjpr13B5mEDS -DsCqrStoh8EQ+jB62n2Xv8TT4lQju/sZh0l65IiT8fUfAgMBAAGjYzBhMB0GA1Ud -DgQWBBRkxUEzwLkf0rdu5Txco5JSsf8WCzAfBgNVHSMEGDAWgBRkxUEzwLkf0rdu -5Txco5JSsf8WCzAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIC5DANBgkq -hkiG9w0BAQsFAAOCAQEARJOOUQkv9AgqElJmQjGDkRdJPxkDHZtRLGOk9p0E1KbL -lqQQdgzL7RuE4vfCROan6aBZmXFRviIPg/Gxw2hDSIv1NUZv3AIgM2b9+3y+4SQ6 -2a/sqh1JPLxwnLN+Mo5KwY/E/YlJ0N7rw3AONrLlqH89BRrBIiPjrg74zi6qPzGn -WB2awHsbl7AOtkD2dEud7lbyLda/hCw2RGPSBQMm50pWsuInWXzdtX/Ii9yTGMyD -kavUHX6DDVouZBSKOjmChP0fGPM17ORJNR92RbT2ygy+F0Zokh5XUgrKPr4/JTW5 -iIkycpjAXY9UEMfi8pFnnzVSRj65kkZvZZJzybelMQ== ------END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/intermediate.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/intermediate.cert.pem deleted file mode 100644 index 07b60159ef..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/intermediate.cert.pem +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDUTCCAjmgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MB4XDTAyMDEw -MTAwMDAwMFoXDTAzMDEwMTAwMDAwMFowPTELMAkGA1UEBhMCQkUxDjAMBgNVBAoM -BWlUZXh0MR4wHAYDVQQDDBVpVGV4dFRlc3RJbnRlcm1lZGlhdGUwggEiMA0GCSqG -SIb3DQEBAQUAA4IBDwAwggEKAoIBAQDN7dHZWbqUvuWdBBh7J67s9mUaFSsG6SF8 -LjhrnraGwk2mk3wMl5oF6nB9WT4tLtXUs5FmxznQTYUUC5ZN2bU35wkK7Yo41FOo -6pIjKDIWqdf4xED6FOghz9228JEnWa5za4lcchqdiChsDQ5YPXzgRrl3TXovDXz+ -avXWld6AvXJL3qzTSqXJ/f9MGHISEh/WNGvDehRVAahGJ47BHnu2uVSH4LD+9I64 -ZOd6TUCUjmyYQBc4bGxTV8ZlpGaYv2FCWgQkkGMEAlE6ESDclDGTrbFCAYeHrPBK -QbdrrT5FYn2bwaPqaylD02F+uIipKO82OVh8j+ryFeQYoWGL9xJvAgMBAAGjYzBh -MB0GA1UdDgQWBBSnpIPlATjoMzDOhbeswjGupOh/PTAfBgNVHSMEGDAWgBRkxUEz -wLkf0rdu5Txco5JSsf8WCzAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB -5jANBgkqhkiG9w0BAQsFAAOCAQEAjhn3BZ/n3Pj7nwJrkdjANCphv9xS/gHiVMrz -InVr7ltMFl8f+pCWNLvhMIDJ5jJpDE02nJ1uMQH2lzkaoG+/m1ZHgPeXUIK9wYOm -il1zG2YxT8PPHdV3fnghbh1gsIUTqCb69zdxe/Lm0tMYRgSbcdknxVuezBTFSfYJ -dSVIMHhbmiUyje7hPnJ8wGz9kF08ZxcMuV1gvRCDBxN8+4gPa8AYJ1zCJBERF8Tf -DyqvSAbQ71Bbxw2YWpOxNEM2IaQCpHvQs1c1W7coRip7kTJUgYjZy3aM9M+1d4UL -eJ7XkcroOjajfuySyS66csCB12uInGF6FKJAQnEDAc5YSWEZ/w== ------END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/keys/im_key.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/keys/im_key.pem deleted file mode 100644 index 7a85540d40..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/keys/im_key.pem +++ /dev/null @@ -1,28 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDN7dHZWbqUvuWd -BBh7J67s9mUaFSsG6SF8LjhrnraGwk2mk3wMl5oF6nB9WT4tLtXUs5FmxznQTYUU -C5ZN2bU35wkK7Yo41FOo6pIjKDIWqdf4xED6FOghz9228JEnWa5za4lcchqdiChs -DQ5YPXzgRrl3TXovDXz+avXWld6AvXJL3qzTSqXJ/f9MGHISEh/WNGvDehRVAahG -J47BHnu2uVSH4LD+9I64ZOd6TUCUjmyYQBc4bGxTV8ZlpGaYv2FCWgQkkGMEAlE6 -ESDclDGTrbFCAYeHrPBKQbdrrT5FYn2bwaPqaylD02F+uIipKO82OVh8j+ryFeQY -oWGL9xJvAgMBAAECggEADxzAVTSOCkN2I089IrCXWEF+yuq5xSCPugbEUjWMDJiu -zSYuqNfpUDzTs4c8lmFFBP6GkaXWOtCtjvqItb7f2zHjyn8DMUd3ukI4pkbZYitl -s5ZndFLbdDvGeBnwdRRSRpsiMfwXsu7elItivZwJkYXvL2+qo1BYl20vDGfkM8tR -mrCDFmW9RG73XKpn6Dd9C5HPV27r1nNQTjFNKx+Vv2ALNkNN1Ap3tZ7cTibY/Bt/ -muCU7SWWBXwjJsKQkkZUjVajWDRBA3wq9rnOilMt7rRbVyq6QIT6uCZYd9ouBBg0 -gcKjbA0FdUqJIdHWPSaJobuvtIAhoN6onhULOdq4hQKBgQDy3qbFpsmonXctY5mC -WV8PkX+YQZC0jC6YGLYbWO7lZ4rfrQvKEI8VbkMS82XzGLoSN05rAJonccsb0/Ch -4Z5AeR77o2z+AE71EzvEKXWGABWf1n+kiiu/2S6TfvTui3ToAPMrFr5p8y6Qer2h -V+1r2o5akm9JQQsEJ9e/z3Zm3QKBgQDZD+dNFWmBs9HbDm7iYZ/BJFMoVwXBweWS -qmPik99hIvyak76srnQtkW1kKXrzKICB9dbiBPYb8eicQZv1Nu9efrOIGa82gdCO -6QV3ToHYzMWnyan/j38nYtU0CtABQO3YWr0pxfHqpw9NmnUPBqwFpVGLppcA+Dg5 -xs8LbQk7uwKBgB9dwgwkzkaIj6u9AUZkZHKOR/xR+25V7G6YQmylv7TA+p6Iqs0d -9ly+MMtxw+jxeJaBrg8DtOUDPUgKxzkg+l85RVcadCkZwRjFsyJSeGsl96T8/t8x -ORU951YFP3zPZfnQpZcbCNyGG61tLLB5uqADSf9Iijbbv6B5xNNw58nBAoGAY4pd -ggX9ulMiO5ik1P/76PCliexOYYpvoxCsea1iVQNcX+69FCd0c6krRzGWhofeVrrM -bh3kVvBawb18rbkhkG3+Gr3ckdx6Le9CaHICLc/KHKXoZaACqaczKoiC1vBVolAK -S2vRAtDVvbrFT7y5imVDvg0JVpJ+BlDbhdvczh0CgYA14jJLY+IWAjxNzo8NdCi7 -iayF+nM4n0z0eW7/5T3hEPDan7DSg1O1cEUiKckt5LjZWv6xoxQcqYoN3H9jkchM -kMUOqvkb2UE+MllGVX+GLZkCJdTXpmDIXL/o23sM8awmiIpYWAbgQ9cSBoR13Pka -Nn3HfG6ejOSPFRHun+cw7g== ------END PRIVATE KEY----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/keys/root_key.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/keys/root_key.pem deleted file mode 100644 index 971c1f3141..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/keys/root_key.pem +++ /dev/null @@ -1,28 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDP6KUmxQzeXKuw -odaQZ7IUoidvDeXWrjW7BNYmKheyDX9SIeIwvuiKDVUD85pWyk6jhNUvQaYvGVOv -/Pbu4NJHv9FKch2d9759ckMT+MXGfGk/B6Ww1rlKsiHccWizQxah7R79eGweEvry -PIx+hqxreCBH4yzMPjHld1C34/vCnUGmozKT4KENiT6lXXiBm4D+u3siCPt1Gzxa -vvm2MUBTHBbhQ3/n1eS/FcqT4NhIvXDpPiNouD9goI+4LwCW7b52dg7dXreQY/If -GCcHTcu7YK/OEW4Pqjpr13B5mEDSDsCqrStoh8EQ+jB62n2Xv8TT4lQju/sZh0l6 -5IiT8fUfAgMBAAECggEAN3LV/PGHvZQcjBaVeVzWfy9B8hnURv2eQdsH3BTUzf1Q -jBCSWSrJLOxiVJP3AReignTOQHSzRBNuoNyH5Oyb2FvdjwvBP1yP9rfvENgDsyyC -CzfYZkHWGAhLBJZQdKK7WgM6BSLFPv4T5F/mnmX/fQgEH/gD/hLGTusT4X9RqTS4 -1cnScT+zPn/FedqLHiNQ3MTAQQBrSl/DoUPU8HyDDN1uF9/TbvEaMYl/iXyBPYpZ -AqhS7Je6Hue5Q86Tqd7Hj044OzRcjci2X6XeB0aAQc9VppAoI92hYsv59zLiHpw7 -81fRXazsyzQuctu8ep6Q08YMBN2YJN2XLj0IANs6lQKBgQD/lxTVtP1nffeV/Csj -j051N7N0SYASZtAXjM4x2z/0dRpka0C05kimT5ZpYGIVmWmTb4EzGYzIBOO4mEyz -1AawmDLkFDELc03XM7Ng8YrMvi0pl7TpPorc1fvVjcEXCfzRC5FiQ8kTBZ68zcMA -5+6uNt4lxaCiiqWswWQWl8l2xQKBgQDQPf2hHYOkNtUg7AsSdou3+dTQj90DlXOE -V/SotkStwIQcWefD/IcGQbAI1NGzXwipXsxQ//G9slDXZSKgxHpXT+pmrUDc5FHW -v8XMH+dtzOkCrExh9S2r7HFp6UlwOWomwePkMEKWWCZIV/wz8HzuERH7MZvgcTYU -Cb1mlZPakwKBgQCvC3XFdxMl0evC2NVioT8GoINS3RPNhoR13IVLN/FxJtJQe/Pw -8NZIsLE+sjf6uvrHctJ1gMYeJtsfDY9aiZebUmFoOzvrr6hb/piXiFWbK5QarD/G -joLkA9lZxJ+9e6WeNeH3/pyzXmH8xJ8M+8tHnWQ/Uj5Vk8crrbcykfn0UQKBgH0O -TUs9SzoJx9I+jqOm119DxF7/lk25qaa3n3DWDMZ/j5brEvkqpPfH6OxUyh47GxuD -l5WpLsap2EySKsp7U7Eth+njb8l3wAIEJsff/P5+iQwW5sQJFkVh9/YPqA+iGzJt -S+tUZBiflVXqqMWUTaI2VCMS9rZBpqU/+CMr/p/LAoGBAIWfEfkqU2miHOcyEVjr -6PmTzhii9nXjV/E5tK84v3a9B+ItLLYiiPiD15t1l7tu3Rq2hnwItM4/8nM6AxNR -Q9kDjj+UdTiK2sc2vxry/nlrnyjl/ls8z02QUiIGMNZLdqf58dROc5h5QEM+dNaU -LuDLIIf61vUhT2UHcQXJ33N+ ------END PRIVATE KEY----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/keys/sign-key.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/keys/sign-key.pem deleted file mode 100644 index 61f32d1105..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/keys/sign-key.pem +++ /dev/null @@ -1,28 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDGifgfB5ShlwYW -+uC7johv8Rlp90YFPg9YuNsQ+I0SIz96C94S3n1bakAIGj+ByWtJiNVVlNns026e -btdaqPXgHnz6uo8Wjq2wt1ck/xROBHKBL6+PDf9WQdI5yi0JTtpc81Qqpy/YMgvr -KGpBsC8xbPUio5COIf/WAp5KFbcTiP/WQwX/0JSca6ZJzj0vUUPGNDivtjiG9JLy -tH9vBHL36KQJ7zmlWwByFsqSA2m7kXMP2F0W5sb49nPrdXRgu3+Ai7+2CohbBKcn -VCQ1kVGBi5xOxrzvXZkt6BBWiPiq3uB40rGghf0YKfX6RyoGhU6/KyjhlYEBz5UR -Tq7Rql1fAgMBAAECggEAFCf+sjvFSbB49E1NEo2SaXb7QwhRKggWa8X8q5joTY6Z -i6z3w0emR2kejhQIHYeS5ljHe9RMWaBPizMqlvAvYi0GODhHfZ1HofjDFqT07UTD -UT1DoAzmPt4Y1zgg4WCJh8VGZrwpfdP65MlqHDgkWmq66mTbsKpf/FywsEnLF+bz -WWgKJP8NIxtI+iSipgGLOW+DtYO9gvmF9dDjPHISWkcYGetuz2k+a3n1NE6vwx6S -NZVC7pkzFGTg+IH8b4e64mN3jUoxSi9+KBZRApFYJRL07v8wBeJf7cN58NEzQjhG -5RwpBEjpcqEP/dYUbze6WBXC8G2KGrteBFBSqdb+5QKBgQDyMlDVblRWDBjD8RYL -9bXBooXsMIeP+i2fiTEEzpTsumha4T8KmPJr33bXOW9CZw/SUJ5WI3bBIzdzbxf9 -elBCoUJgO94wmnJdZNHeuLLb0AwTc0CMW5V8/5gu7e9Kxkyh6hojEo6POlWagGJz -3B1deqpJVe76oyLXMY4tavgLfQKBgQDR2q6zbHuubTeowDJD8CsrORB2+SJEo4Pe -1WzkP+0PX9y6n8Uk9FvjyU3MIPdD3hVruJwj7cHfpNg/UksTOjaWMI26VBKUfcQo -uZ84i4iwRrREAasgPc+evm1xAkmH5qDcXwIx7PxYW1tnRd8BuJZ6DpNDiY3rEf5D -Q2k0TumLCwKBgQDFHUJAkmy9I1c8kYgZ774ffAB2/AA4o6ph/ywP93mpOQUZgdzm -6RfTx6lW/P2aE3sC9m4HORG7msfUgQQLXnLX55q368Gn2OtfK2DLXZLj520Mn25X -TWpas0LOXwOz3bQcywS+qqmv1BA7kGWQWgLkQ6M30GKRRhhi/4fxWu/JmQKBgC6G -r2j0Sk+Xw1lUk1BgtRF2K2JVRfW10wzagLPyQFrCRCvUNF9HFgBgpzD0th2D5Xfm -jCejFPLCl3cihaaTp3qQ9Ts0XJIzeAQXc2eT+BAs/NZ/EDOrwJZPXfBKM4c/6LYz -EkeDZUcpqhAxe4nkJOiWxquYmbBeYuMC1RZV0I2VAoGAac0Kt0+Rk1jJithh6STu -BNQgswvfE2XFuMtySyByeNClzJofE4fHFhAHlhoHszPGSiNEDw4RvOxPWgBdLyFz -cWUXtL0GMzkwLfLCwRedFx65ijXbxUMIZXWYiG0GQA3w9fcDFYwugRMP5wKC9vMm -nTRzEOnBVWIXKLw7RdTBV4o= ------END PRIVATE KEY----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/sign.cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/sign.cert.pem deleted file mode 100644 index 26c2432936..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/CertificateChainValidatorTest/sign.cert.pem +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDQjCCAiqgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MR4wHAYDVQQDDBVpVGV4dFRlc3RJbnRlcm1lZGlhdGUw -IBcNMDAwMTAxMDAwMDAwWhgPMjQwMDAxMDEwMDAwMDBaMDUxCzAJBgNVBAYTAkJF -MQ4wDAYDVQQKDAVpVGV4dDEWMBQGA1UEAwwNaVRleHRUZXN0U2lnbjCCASIwDQYJ -KoZIhvcNAQEBBQADggEPADCCAQoCggEBAMaJ+B8HlKGXBhb64LuOiG/xGWn3RgU+ -D1i42xD4jRIjP3oL3hLefVtqQAgaP4HJa0mI1VWU2ezTbp5u11qo9eAefPq6jxaO -rbC3VyT/FE4EcoEvr48N/1ZB0jnKLQlO2lzzVCqnL9gyC+soakGwLzFs9SKjkI4h -/9YCnkoVtxOI/9ZDBf/QlJxrpknOPS9RQ8Y0OK+2OIb0kvK0f28EcvfopAnvOaVb -AHIWypIDabuRcw/YXRbmxvj2c+t1dGC7f4CLv7YKiFsEpydUJDWRUYGLnE7GvO9d -mS3oEFaI+Kre4HjSsaCF/Rgp9fpHKgaFTr8rKOGVgQHPlRFOrtGqXV8CAwEAAaNS -MFAwHQYDVR0OBBYEFKwAjNPp8T/Q6cWJGYu9aMR/ujVCMB8GA1UdIwQYMBaAFKek -g+UBOOgzMM6Ft6zCMa6k6H89MA4GA1UdDwEB/wQEAwIGwDANBgkqhkiG9w0BAQsF -AAOCAQEARWKct75OvbvIGRpTN4lvqyPJS/ZoVa/Dddbdo2rD669qltAce3/DFY2R -W0CNwIAxBh4CHqdlG5Od1qQ+BJH2pNGB6F2W/kmQuzaoo2PecDXNOfigRJASZO9O -nSFh+tQc+9DTNWrYyBb1MUEgZd4z0Q98dX3mWJ3YMG5Fb0pbexgpiAX5s9T3X+Da -olCzzmIRVIbce3UWv6T3fGvRJ/tyJ0VqvR8YBbVW15KaPabyZDE+v7QFizmoRFdw -7Dfv2tKIA/8ENO13BztYq1USTYhirfrR5Ki2oiul1Nmg48JgQRMHgfeBKMl9auyR -B6hPOeazdx/aJXMcZVIkYoWOPQsqVg== ------END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/OCSPValidatorTest/ocsp/keys/key.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/OCSPValidatorTest/ocsp/keys/key.pem deleted file mode 100644 index 5fb891d53b..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/OCSPValidatorTest/ocsp/keys/key.pem +++ /dev/null @@ -1,30 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -Proc-Type: 4,ENCRYPTED -DEK-Info: AES-128-CBC,1C5866CA354FCFAF85B1B5DF8D373D52 - -b90+S05shvUKtr7iOJ061wwv0mKHkN92uq9v0MvObA+IuazjuI3DHcAQSU9l5eCM -N2rHq+cW/mBdgQeNVFG4IyOWDpGKUj5Rq0BGovAIrYAKrLsZS8RsTosNb/ICP74k -ZK+OloFnJFehNH5NfRTUdfnuJj9jq3q/7XrA3E41bsOFMbQPsRESVjO424vjPkN4 -KQwsIaDLOPGu0kzZmsuO2FPN7l5dMuS7Bf29Ns/U1w5JEcDIEPt8kWrQF3FN3bxv -7pJGzOe33s/7jby83VtGtEcWYjoZW0l+x72yQxz3PkCzgvqeq1MWy6EGCcGtX4af -ss7SQVmEMDkIAZrJ0Sw64chSqhk4ZBG43tejrn6Ed9eLHBrDIShERgq+Unw2xf4U -ILjBB4reZzDf9H7Jo//XgMa+8Wp+kuR7fXLtcCebUW/C5zpWRV/2gmgDAxn46RlA -mqKhQ0jUwgJkxvkK9kb2NWEfGvYZZ1ZHEuSbDXLu7zGufWW4nOK9lN3bhGlTWhTm -R2biS2SkPiMRuxiADI9BlMLgkHR1GcnDWqql157TBSe8pnH8j665F782x2RWF/j+ -l0Sl6yLkN4MXlAVdx4QfBnH3u1s/Y9T7OytzWwCApxMGNrsJx/+v12MV+s3M4vUg -bUE/mWd5j/xRixiAMrW492d++TItxz7yQe08tARRvtICwY5HL8WU1DzePTjLHPUa -1UNCrLNiVt2p4owygkYBseqgTfTguYtv72MHAoYMduoCNbKcoemuGj61I1BUiytn -wC8NMw/9H3OmTJ5IwDCSDqDcpjlJwpQI9/vZncf/fbodBEwxUTtDVFlX4RhaSrIy -FuFZnbcvpSdMwTxs8TjwEuJNQtzejaIH49DoGD8+qoR96ICD62b/Rqbbi7xi1DKs -tnG3au443YCFnPMEiuzDY0f2sFLOFEJZvLiW+vVi644My/ox6FQtgf9Jx79yCHZO -sq1VRfjteby2gO8jl2aMuw9ubDe8rxfoScU6bLcWSLNJ1KorNssoSg45r+NU0NOc -m2F8OXGu9zgwMMs35/oMrkLo64j7uA/5uPkxW43HeDxtx6K0XZRrP38HhVjKTnqO -O3+OQJXrkBtWOwE3Nn3bqxbQfTwtCTZBXQpmADhzwmBMKUL8tVy34gL7yqSClveE -2gxb4Vc+/pFs6bPAiBJr/7x77ya7sSYHBHzEBzUOlm9DMjTFrgMTi4bLMF7o5+hT -7votJYtIR7p4nowmBIeRBAJ+V6MM/LZ/v8DDUPgmsk7sEfOSEsDr4JDW8ChGeSr8 -uiXbaFnTBblrFSNQOElQsIzFG3cu9sD7PsxsUqfHCO6XuBFIcCnzyhcwX8o+Xcbw -Nqprgf3kbXErTcywM89Xg1RGa5Eu0wAqCqvEzsLm1dGsAQ/iTMuIitr9uJ+rell4 -/7TsLue9YFFcGXL3HcbV1RKGami14UXY+8t0BRYUnG49x3QTVXco0JKKtrhPT93s -eQ/jHDaZJXvVTjhiOR2bW6XkZ9KKlMXViwRRbJ7BlDUhbKltJXjIYJt+KbOmyGxP -ORE0EV9Le0hJBLXmgkXvr3AynL+twUEKLR9D91Ky/ZHcAyw61wmiuFq24U4aKWh0 ------END RSA PRIVATE KEY----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/OCSPValidatorTest/ocsp/keys/key1.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/OCSPValidatorTest/ocsp/keys/key1.pem deleted file mode 100644 index 9b62b4a33d..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/OCSPValidatorTest/ocsp/keys/key1.pem +++ /dev/null @@ -1,31 +0,0 @@ ------BEGIN ENCRYPTED PRIVATE KEY----- -MIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQ86aONneT2rZ4OxSP -Dm+4cAICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEAQIEEF9NVK7Q8njCcRuJ -rMR4K0EEggTQHHXOcf7/lWrCNH2itwUuqgz4V3M1mX6QiIjJuHFsf/03PJj08bbb -Ne1x+LQCZzG63vBZmYchDvjj7QVPSecmEIfLrmISv8+qu1iBlzNXWScLBTul33wT -TbSFEfDl/AoH8sX1S+f2yZqmQEssdfV5gg7yoFXFEo27mRkBW378OOQWXKgXUI0A -z7CBRjDlr/0nt4CHDSib75MtE2oNMbyihAVb+LMsro7y2pWXHadH/U4PTyNMjTvv -HsA8+lmJHDiPVmzTbR3Aur0wIMR8LqaNUJ8NgfHFRHDiE94Q4g8DLTnMDOtLifAT -cneGIIEBbPuLBh6IDzaR55b5QJ7ZAaoO2BMEuRTP5PJtTrheKF8X8PjAZ7LPPc8n -FLY0hYc9RWw/MfFuiPRpiD2vzY5R19tFrFOSyNZz9r2haqwJ5lNfFEI5IQn6q0Bm -B77USRn0q5OlGXb3mxB1EqaOAVnZyppbbw1NXITFttKps2rplYJXUtNsc273UNgB -Clyc2vsmW27H8aEa/zHr+KVDMyz+JTyLorxECaRfvRl3XlBIVdpeFCrd8viIWjV/ -wp3RYMKMXPS1VvcJk6A388IAi+b7vnVDxtX+emAkrOMtAa4IZJwQyIfuy0qBdx1K -OQYS8qFUg+ErIJwOcgXlu4YV/ebgC0ESabTjNCAeVpPQ20ypgqTerAaP6QZMDrLl -Q+50eOLWl7E5mcdxsL+2MCu+eX6yc9njrvidtKKz7H+Qt4gWspRpKCDJpk4YTKof -zRQLSBhgMYWHDGM1uGx9bMnZYnM8aB1dph+7BJuETUXzp7Q3tJgUL+mYNUtrLvkG -eflHjUcFNj+24RDnzoDsdxv9YWBj5nF1mM9pdGUfe2VGMgAQ/ZQxdNDYGWF2zkfJ -tba+ylRNjprtn0Bt3PaCUPKYLZ0JMPoup9uENJIMx+4BB3z8Q038Ejrdr5xDmkOV -2zMFXSqSH/NE78ovi3Sg+cBpjqrX+rZtyksQlo8gQqFjzruxHokM41NnTJwOTitU -VLzJjh8ljjhwqPW9AY9o/k3Zrg0i7NxfVr2PnEeZnuI8atn+J0/2tbS67TCAxra3 -ZdZ3u9tYBof9sNPq2WmVmLWnC2DpkVvKN7uIOEJbONlCKCxxYYV/UpM9HPvYWvRC -Fl2qfzn1T6FeCISn7zJiwxXUZZQIT8PVJUnRoT5tptp71OkpfH83AZ/lyQg3WzcN -KUPDO6z8zLiihq7tgFOJ38kMZA0fs9UahfsxVgjgweQjcX2x927uWccd7VAqkCri -yY1L2xwgfiHF8ZR7Q2XzI71EwXhcpRkdzJEYUpPaD2FVrZWLeEDv8WHeo9BtnX+f -Z0Jc5BUtMB05Nwf7MAusdj7PrZ2yCg20f03o8W0lFF2V67uKDfumjX7HAaUL6uNi -+h3i4HuvKUVeMcIj5DxvMHKfEDgwytCCZkVqmlllseLkKGjnbRleJwGfC4shQlyE -0a0baa4vlAczT9ZAdxWJOLqELixZH5QxzctS6587Q9MuY4YwVc6NNRjPVfOmOoZO -o6BWVN2lOeMME9YV5Im+jDMZ1MeN0FlOfkoy4K5lt/e59ibdzaTQQp7jYIMsjeQZ -Lacc5oY0cY0UKZefRFtg8Lisen6WG4195B5cErHT5mF9N6FOaI7Eox8= ------END ENCRYPTED PRIVATE KEY----- - diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/OCSPValidatorTest/ocsp/keys/key2.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/OCSPValidatorTest/ocsp/keys/key2.pem deleted file mode 100644 index 73dcde347c..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/OCSPValidatorTest/ocsp/keys/key2.pem +++ /dev/null @@ -1,30 +0,0 @@ ------BEGIN ENCRYPTED PRIVATE KEY----- -MIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQF0kKZGhuRjc0ReXs -rguJdwICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEAQIEEGF+EL8evTXnqMNG -Cxyic6wEggTQTM4EBzYhNo76Y+YPJC5ozvrp1Wl0/veYDj8kAkfUUEkL/CarBQ/N -lifnuusLtSU6lRj4H4rDmB209kk3XQ9Q1ca6s9kwpXBlTWk9ya5PGIpKAR2+OIzq -wb8JwhldgRD9p9cuSaVLcWvRMpEuBQCXSoIVGsB/erj1Ek7EjamAoPjStJ0y0QGG -iFrGCKzAIsVZxQ5dCaR8r6kZi60cLaFMt6dWhpfimJqOCpXyCW112ZVinjHNEYEd -ufHwXXIvzMnft/X21pkE/MLr3xZyzkbC5d+zX3pzW5HpKrIOlET13uvIstB0nWQI -9y1vTBwb+C6iZiZw7KP73OWu/vjZWOj/NF+yu6RhfsDV3xl23heKp+uF+JGlv79t -MqBXtxp3P1DdpE0iexALw1dpZTAfNn+qfwiYY2OPOhkc7ZASgaEduM0Zz+jKOhqI -ib5amuXs+T827kD9VKRWID0DDnfQWpANcKLCuwhLR4FhmaBGUr1s1qDZploc/QVu -B5k8wt/DanFsACx51Zsdj/c7x/mnI6Bv5md0HHy3t8XZYYICO9KKMDucoENtuxhq -XsyYppgznYRwU0uT49JFFx5die2QyE5RB8MjYPZlre21b0pVodOiTU0H9ZbS/5HY -OvlEed+OakvU/U10QU0chBRYF6B9wziK5lGSEtUbz+eoWg5UYvWEJtK7ZqROG94M -qHF7QYgzysX9/AtJCs/KR5Av7uRFyUme6Pajw8DQEoXzP6vwNnDVA317f+/nClrj -4rYb+UgqKFy9iTSJMpPrQUTPATbair6vWuRrmFGr1WAl7iydBMVUWWdEVJl9U/ql -PNqS+wAT2KXGKGkSZv2KfK1TQxHwsWVZOBybQwct3ydrFR0lN9hZDsFTBg3QyeNF -mNkn/J1YOnoZQQzidQCUz59vU0DNtQBRgdOejirbnhcUpfx5X5XOvZnHiWIpM5f0 -JLKocR7kGJ0ccCXv9p7cyic3Iu2osKL/h/0SmAn7WZWCeBW4s5akQJCzoEZLxZJH -Vgb0h3FO6g1HS/YUv6WnsFH+NDDdyyWI5LYtknSWSQQLtlpHuBhY5GSqUFGOCkG8 -b4waEUMDdOj85B4dSY3hhDOCLtpfUI5haJbAR9KNZ4nzbDwP6ItaVKL2JP7MaS3X -3nIDo7hu6T0xI25sAaZZhGOd2EJ9rMzQC4fMuSYVVZJRgFADAyySklJpqVmkv3sT -5uKcUOK/iQOmVnL9EWLwstcdiRYg1Q8FQcWObntmUY8O99gMkvYOhQgWx50KoKnr -YrGDn3LnA5wfotKniNquHWbE2NsFvmVvKPEjj0mNbxF0oZxv9nBeUN34l7rjyzfV -D9xBywazBXkIN4lgKUyicy8M8LoFbpwy8DBFLZhb1npTAI+HI/w0jpfQpi5YZxiH -9t2UfBUR3yhP1Jj53SBby+TWnmvxdL+WIQKAd3TC/z9ONdDMM+7A3pMnIJ5np7qa -8jKNY4jumgtR+0WVsYjTkhQZeVMoknb8gcq06FKI0/duM2YDtItEalU67m6GBKFF -jqDjLSANO9W43wkPJEfb3/0mU5Eq/MdQeIommE84TRjg7X0TD7/a+KyR5Yc2UU9v -cfHxPXI3FHBBHMnetOabyXC7jfvIaMCnOsyiQWghfkWawiCc1EgvRSI= ------END ENCRYPTED PRIVATE KEY----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/OCSPValidatorTest/ocsp/keys/key3.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/OCSPValidatorTest/ocsp/keys/key3.pem deleted file mode 100644 index 7e63e5fbc0..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/OCSPValidatorTest/ocsp/keys/key3.pem +++ /dev/null @@ -1,30 +0,0 @@ ------BEGIN ENCRYPTED PRIVATE KEY----- -MIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQAYAHt8zWxpTT+SPd -rIySKgICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEAQIEEKZoItUClr1nqMtK -fpMWOkIEggTQokjE2mbLL2lSdNZjzge6rK6AGppQetH1iILY9UqVmx8DbK8v4i1C -TsHuvJ0nlMtGSa2xfdwc96dZwn5gTm3SjhgClyIWtotbjWyG4a2qUGgTowGWmxuH -Dz/4D7hP8gIMzVg2nzhiHlTjs+IddQesZyCUIu7tf0QgXcHI9PoogjIi2djgOL4m -c22h6vYNKo0kDFoCjZvzDpK8wt5LsAwDEERNM73vUh73AXqSUDBYqvFEQN+QmVEf -pSuac0JXWmpXHGllkrT2DmcUHmde6HB1ZBPhWryuoQZfRpwLORXSPDQ0rQXuwWcP -uUd+iXHMMkzLEIsb9du41u2DlDEcRXnCrGR+oMSV4wyQdosc7nlOzVXVB4RCTBgY -AEVQag7IjH/1/3FXT9YS7vBTKaF1OqS2ibquGmw5ibxCUVPOowD08F5HhQgh5WjI -9x3uP83f8eKqRLsSQRUJzCqHU8pxpEhBEk6uOEGY6Z7Nvn9wKWNjJhqrndzsO0bS -iee7AvbgntoLWU91LnH7mc+Tg9MwbKEH2vtx45kbHFuhqeqToRWHZyxjx7x4DuDP -i/2h/Dp9gWDbQ+BscVTZlJcssKRcKEecXWfFHctgsI4IhzZGojcq0iKE4hRlRaX1 -ZH2xpQNBazIhlGt5kdLY2LCUlPSYbFzb5MmkRy+8uUUfZJOu/4BwgqgJJPh0jvIy -zU4vYr3gD+qKsXsJMkXBVjiPWQJNCRuDgC1ayGLgRNxXqkaAdjFkWotB9vIfWMb4 -Q2c0O/cqmRbNOxxu4Uoh3ia9k9mVShrl+VIEtDK7egfke0xK0NHu5mmgSYmZ2Wod -q5xTKw1xiw/X4TgtlK0JqBL8MkupOEsRkkHS+pUIfEQQ3Y7dx8WRl6nse53TE7bH -y8TTKC4lIJl61vYRtdXV8jqZQOzAHxXcwwATyD8j/ugnyKC6bgti0mJReM5gh4pZ -NxT3Up2WJvvD02eFrCacu3mS6ueOjHMXq2VJ5Yu8s9DxJfN+aIN1iCMO7hNKlX9S -bZ+ZXnJQ1SVwY5NqdxaxdJQ35X4KClb7hmF82SHEL9ybySwRs2epvSu15Rf5rN1p -AmvgPbIXv7GRgNoVuii79lKukDLqijB7GXPLAv6YjwryuuJ4fVusVphpOcUUj3Ih -dsp4DeArB/uT4ju4AAg6EhLG94k/nc/EXWFxc0pOF8smeyA1EzvJe3cecEuj/LjX -YqU5H1uOuU/lIv2lLEqF6HYnXW+TdxsWxLY86XFy8mM41GwGso5EChl9H4cSfdSR -qtv9zR6WVJQeVJXMoQQlPntO4JSLDgS+WpWH8LYa4duyahAAoVQJGkEcNKcMVdOL -XL8cvRyXsVo/tY8+BtepmXhxduReM501p0zn2IathorTgu5gN6Pi2PcCmYoCD5jI -Iv3XWKTBDgD36j/PG2mjH1PTDfjZvn99uvTT5KXl2oHki8NEybJt5Hv+BmMRfncu -clg3G9QmshEGRL2exps7u5zOV+wdYp17l5WMGCPy0qo72l4Z1DAoB1fle8VTmO5n -G3/V5oi5fZGN5InTe098ge99wYJNyKye/Q3Nt7YAodBQBBt1CJb6qMe9wtC9onkb -IV2DQw3+XE3hdwFCTzahQjxT5wJDMMxdtNWgnlAD0t0R/wztA/bZPqM= ------END ENCRYPTED PRIVATE KEY----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/certs/short_validity_sign_cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/certs/short_validity_sign_cert.pem deleted file mode 100644 index 2d90e06b74..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/certs/short_validity_sign_cert.pem +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDVTCCAj2gAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwQjELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MSMwIQYDVQQDDBppVGV4dFRlc3RTaG9ydFZhbGlkaXR5 -Um9vdDAeFw0yNDA2MDYwMDAwMDBaFw0yNDA2MDcwMDAwMDBaMEUxCzAJBgNVBAYT -AkJFMQ4wDAYDVQQKDAVpVGV4dDEmMCQGA1UEAwwdaVRleHRUZXN0U2hvcnRWYWxp -ZGl0eVNpZ25pbmcwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDBjVE5 -g+cvznWx1lVVpl9yg4dS3TCrB2kRO/meweFHcHSBhL+LEZDgA7m+k+fR+WHE/I1g -KbAFbX3/5dj8gcD8pQyOO9QuBkgvSi3uejpk/O2Zi/6hxItfiUu2O2SLvpGv72Zi -MVV0RgyS78i2s+uTno+vmbvooTKEbLyg1zQf4cfcQY+kX7q3JN192TfqEQQnNuK2 -STBERsk3MZ/lmXrfdn5SLQ6vEui4FKf/d2UWKXp+ZcLX9h47tRU0o1zBaZVvUf/d -/z1MNzo+jFMUrC9Zy6Jn2IOj3EoUg9xp/R77KoqQ/DbnoS/FiYTsyew9+pIptDSu -gLjTTxrFixkEkK4jAgMBAAGjUjBQMB0GA1UdDgQWBBSxHey9ksvff7hxUU3MLaSF -Nb++zTAfBgNVHSMEGDAWgBQPU6vHmmiV36QSlV44n86WrnzBHDAOBgNVHQ8BAf8E -BAMCBkAwDQYJKoZIhvcNAQELBQADggEBAHJNNuclJp1ZTRIGX0wAu8WfULnCHg7l -lUfY2BebGKpCnciwlgDTBDLV+2nLtjWmlxO9j0v/OOw+TV/SuQ2nWIDbfj1mEm5i -WzgNd5PvzI2EHb4kZ1DF4HVhxzjd5Syhk821fmLIyugel8Oe10D7PWlf/tQZiUoV -ca3xh64aoYE8khYzwREQGSSj9VRJkHddd+k73kp20kdk72YrAi72GzkPan/Fj8ar -6FH2EjGannaKdUDWf6EN9BLb/URqn49bCbLev9Xxj7wfQiu0KhYDq33wlZwBgVdT -3lEvqT9hvDMTurdrkrpcO9+qA4QQ3xObAZLhsXygm+tz9Mm109pLEjQ= ------END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/certs/ts_cert.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/certs/ts_cert.pem deleted file mode 100644 index c5ca173fa5..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorIntegrationTest/certs/ts_cert.pem +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDUDCCAjigAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPjELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MR8wHQYDVQQDDBZpVGV4dFRlc3RUaW1lc3RhbXBSb290 -MCAXDTAwMDEwMTAwMDAwMFoYDzI1MDAwMTAxMDAwMDAwWjA6MQswCQYDVQQGEwJC -RTEOMAwGA1UECgwFaVRleHQxGzAZBgNVBAMMEmlUZXh0VGVzdFRpbWVzdGFtcDCC -ASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALe0riefIAla5GYrx2DJ7tUC -coIBGKpuQdGT6/TQETmVgAJ+04f6A+xpviaABT6wanDEjxIwc4AY24Z03MoN9mTq -tMSL8p2/C7fEYM5QPMaKRLjvKQs4pdloe69bpe4qnaXrnhspafC40kh4opKHwAm8 -2xpEPnrcrIoldlNzUZ0wDlu9ScSdu9HnDc7l5ShScRhz5pEqTmpclOUCU4P4lvMP -o7ESpDGVK6dLb5psfQkPx06MDY7HiXq3kG4ZTf4l37TZTQq+MPoICh0Vcuk1Rwo8 -Iqkk0M6cBgI+xvQzGm+wr/xH7tiWeWGUuoxqgYxsBotOlX7WW7hMDC+woGRGKSkC -AwEAAaNaMFgwHQYDVR0OBBYEFLT7THY3zBbfAlt6XxIDWZ/y+PKKMB8GA1UdIwQY -MBaAFAjHQmCYQVscTRw/3JXqLE36LcsPMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMI -MA0GCSqGSIb3DQEBCwUAA4IBAQCYeEO0M7GTyEhaOHCH/vUTlxueSUnqAX5oMcGW -1IUXtQpG7bgBMA7GnW5FZztk2pX+GwyPCSXaWrPBpJDBQtH/4bsHSDtM9OSahlgr -9aYEqaoKzjJCgPKTb1iEluE9NL43tMS8frJkPYDioEv6zGaMwpcvXs5+s5JXTBS8 -1OwGKuVXi1KAM8Bw4BNDcH29iy4LhVuTL+J5iBXbzZc+YVTs+5drewJU2DjWB2Cj -mBOY52p8WE6pAuoHGogLk+ubqjv/v+rMCEFSQzciP2lB2IbDq7zKJ0ZTjyzHEKMf -DEQ3moy3EM6z9nhtkyt0/DCojEOB4uqO8MOvo27S1TV1kaid ------END CERTIFICATE----- diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/certs/trustedCerts.pem b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/certs/trustedCerts.pem deleted file mode 100644 index 91cf8349d9..0000000000 --- a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/certs/trustedCerts.pem +++ /dev/null @@ -1,43 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDSzCCAjOgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwNTELMAkGA1UEBhMCQkUx -DjAMBgNVBAoMBWlUZXh0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTAwMDEw -MTAwMDAwMFoYDzI1MDAwMTAxMDAwMDAwWjA1MQswCQYDVQQGEwJCRTEOMAwGA1UE -CgwFaVRleHQxFjAUBgNVBAMMDWlUZXh0VGVzdFJvb3QwggEiMA0GCSqGSIb3DQEB -AQUAA4IBDwAwggEKAoIBAQC0X3R+3mERB2TiXd+AbcFNqXQWdIMNY39fr/93QQgT -mqp/QCQ5YTBDS52DAMWXC1twQCYTLzq4hW4awcYFrxawVvSxR4qR93hr5f19vwIW -hDiKy+RGNQ3aTs6W8NE41ZXqxrbgFelMmJ3/UUcCcwXL8wmviSXFCOBEkIPNwuHZ -vkoPqM7lKDYF4OTRkfQ6B5/hEikiZ7JhHbr5uPEHKt6xvpGY8jh8rECGDfJwqPAo -YIjFUoALHDnRyc9avuYU5sdZxgdBpVvjYSbmZXECUy5YTiMyhKusArk0kR/QH51c -8mXzYrhrAGJD8x084D+KpniCKwj2v8lRDezCohzAkpgLAgMBAAGjYzBhMB0GA1Ud -DgQWBBQ3hv2LhpBxKeA4pviBxff1Jcja9DAfBgNVHSMEGDAWgBQ3hv2LhpBxKeA4 -pviBxff1Jcja9DAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIC5DANBgkq -hkiG9w0BAQsFAAOCAQEAc1W5CE+h5o9dTBUT6h8RAjyjYnUZgNlhTqFZBG5MyixQ -c0CpVulgmCuZ7edYO9/BqeWiTcMsckSoMQk5+33xUlCqOfogpM0CPqfDKWDFl8no -XS3bvfl+s5LOPV2ENNMUVlgZVPuSIzGrOeUAfVJrhhYtaayN6YR7Ky7XroTliX0W -dCcJVaJ/xvysWUIBA/IKGUn8MofR9p30ub7ig0vPMyIFcj5Swo0LsejfFU0Mb/E4 -N8Y/NRNmMZG31j+6Fjuevb9bUh5jz5jx+HD2lIioWaDvIu9cqKoL5muNecbnxL8u -mtMd2BcnDCWaH5CiYV50pLAfupP1tByUmNotNDmK1g== ------END CERTIFICATE----- ------BEGIN CERTIFICATE----- -MIID6jCCAtKgAwIBAgIEWOeR1jANBgkqhkiG9w0BAQsFADBUMQswCQYDVQQGEwJC -WTEOMAwGA1UEBwwFTWluc2sxDjAMBgNVBAoMBWlUZXh0MQ0wCwYDVQQLDAR0ZXN0 -MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290MCAXDTE3MDQwNzEzMjAwMVoYDzIxMTcw -NDA3MTMyMDAxWjBUMQswCQYDVQQGEwJCWTEOMAwGA1UEBwwFTWluc2sxDjAMBgNV -BAoMBWlUZXh0MQ0wCwYDVQQLDAR0ZXN0MRYwFAYDVQQDDA1pVGV4dFRlc3RSb290 -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz/fz7iq1wzhMMYcGfmMm -teCY/ZtdE26PB1OTTBuDSN86sVNmur5FV/mLPU9ZK2ofrs+wMrqn0agmFlRl4dTh -f5u5WSEQ/ARwXzYOn2uEkwR/0dwwZUL3VWhrPSD5SxX5MzFo8UXTNlXW2bClLC0F -QU2qLjIwwRFwwWDSQPR8r/Mv181RljVpEjPk6DfkDtHWWA4daGlQU0nXbuZszplv -iPafXmyKn+2w4G9Jw/8pHIK2VhWYstLI+bUZk662ZVldNvnpMyHn12FfB0Nbf/Z6 -V2WTGviEr8EEE2cA7I+H7ZGUDzug7umNCCJn3ilC6vAt9i9OLaZRDh6jPMOjMUiz -TwIDAQABo4HBMIG+MA8GA1UdEwEB/wQFMAMBAf8wfwYDVR0jBHgwdoAUXSpxda7d -2L5ZuiCxZpHJdjZTXO6hWKRWMFQxCzAJBgNVBAYTAkJZMQ4wDAYDVQQHDAVNaW5z -azEOMAwGA1UECgwFaVRleHQxDTALBgNVBAsMBHRlc3QxFjAUBgNVBAMMDWlUZXh0 -VGVzdFJvb3SCBFjnkdYwHQYDVR0OBBYEFF0qcXWu3di+WbogsWaRyXY2U1zuMAsG -A1UdDwQEAwIB9jANBgkqhkiG9w0BAQsFAAOCAQEAdhby6EaopoUF8j7oR44Mhe/N -3y9hzGb/zLmmgTavPd2plv6NlAPt9W+8rezKO6jQCsBRFw8JY+Lx6j3W0K6rWigB -pPGU/B/0bXLlOIv2a4uW8nBmq6jxAe5Xbtwm8HcKOOLMzxPIChHJIJy5NWw9ArD4 -Ul+FEt/VuEW1NfPZm1U5ixMOrBfn0C8pxIX4+VSHN9I8WoFjSfYX4Y3ldRLTeqxQ -rhZQlbhGNymp3Kcvtuq5At6vopskyB8Q1b7L4e+hRWK2prz/7p4Bdhu2TmkEfWZc -YKpgrkVFqa/Z1uZ0q4KVBOP3cyaQmqRXTV37SfpNyHAJdol5ueF68VVVNZFRXw== ------END CERTIFICATE----- \ No newline at end of file diff --git a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/helloWorldDoc.pdf b/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/helloWorldDoc.pdf deleted file mode 100644 index 7e6f851581..0000000000 Binary files a/itext.tests/itext.sign.tests/resources/itext/signatures/validation/v1/SignatureValidatorTest/helloWorldDoc.pdf and /dev/null differ diff --git a/itext.tests/itext.styledxmlparser.tests/Properties/AssemblyInfo.cs b/itext.tests/itext.styledxmlparser.tests/Properties/AssemblyInfo.cs index 4c638aac4e..4d98c18722 100644 --- a/itext.tests/itext.styledxmlparser.tests/Properties/AssemblyInfo.cs +++ b/itext.tests/itext.styledxmlparser.tests/Properties/AssemblyInfo.cs @@ -15,9 +15,9 @@ [assembly: Guid("409b5131-4d0c-4e4b-9c7b-2407a8356ca4")] -[assembly: AssemblyVersion("8.0.5.0")] -[assembly: AssemblyFileVersion("8.0.5.0")] -[assembly: AssemblyInformationalVersion("8.0.5")] +[assembly: AssemblyVersion("9.0.0.0")] +[assembly: AssemblyFileVersion("9.0.0.0")] +[assembly: AssemblyInformationalVersion("9.0.0")] #if !NETSTANDARD2_0 [assembly: NUnit.Framework.Timeout(300000)] diff --git a/itext.tests/itext.styledxmlparser.tests/itext/styledxmlparser/jsoup/nodes/ElementTest.cs b/itext.tests/itext.styledxmlparser.tests/itext/styledxmlparser/jsoup/nodes/ElementTest.cs index feb0aaaad1..3bd52adaf8 100644 --- a/itext.tests/itext.styledxmlparser.tests/itext/styledxmlparser/jsoup/nodes/ElementTest.cs +++ b/itext.tests/itext.styledxmlparser.tests/itext/styledxmlparser/jsoup/nodes/ElementTest.cs @@ -1659,13 +1659,13 @@ public virtual void TestTraverse() { iText.StyledXmlParser.Jsoup.Nodes.Element div = doc.SelectFirst("div"); AtomicLong counter = new AtomicLong(0); iText.StyledXmlParser.Jsoup.Nodes.Element div2 = (iText.StyledXmlParser.Jsoup.Nodes.Element)div.Traverse(new - _NodeVisitor_1765(counter)); + _NodeVisitor_1763(counter)); NUnit.Framework.Assert.AreEqual(7, counter.Get()); NUnit.Framework.Assert.AreEqual(div2, div); } - private sealed class _NodeVisitor_1765 : NodeVisitor { - public _NodeVisitor_1765(AtomicLong counter) { + private sealed class _NodeVisitor_1763 : NodeVisitor { + public _NodeVisitor_1763(AtomicLong counter) { this.counter = counter; } @@ -1685,12 +1685,12 @@ public virtual void VoidTestFilterCallReturnsElement() { Document doc = iText.StyledXmlParser.Jsoup.Jsoup.Parse("

    One

    Two

    Three"); iText.StyledXmlParser.Jsoup.Nodes.Element div = doc.SelectFirst("div"); iText.StyledXmlParser.Jsoup.Nodes.Element div2 = (iText.StyledXmlParser.Jsoup.Nodes.Element)div.Filter(new - _NodeFilter_1787()); + _NodeFilter_1785()); NUnit.Framework.Assert.AreSame(div, div2); } - private sealed class _NodeFilter_1787 : NodeFilter { - public _NodeFilter_1787() { + private sealed class _NodeFilter_1785 : NodeFilter { + public _NodeFilter_1785() { } public override NodeFilter.FilterResult Head(iText.StyledXmlParser.Jsoup.Nodes.Node node, int depth) { diff --git a/itext.tests/itext.styledxmlparser.tests/itext/styledxmlparser/jsoup/nodes/LeafNodeTest.cs b/itext.tests/itext.styledxmlparser.tests/itext/styledxmlparser/jsoup/nodes/LeafNodeTest.cs index ddca021891..64c808e61f 100644 --- a/itext.tests/itext.styledxmlparser.tests/itext/styledxmlparser/jsoup/nodes/LeafNodeTest.cs +++ b/itext.tests/itext.styledxmlparser.tests/itext/styledxmlparser/jsoup/nodes/LeafNodeTest.cs @@ -62,12 +62,12 @@ public virtual void DoesNotGetAttributesTooEasily() { private bool HasAnyAttributes(iText.StyledXmlParser.Jsoup.Nodes.Node node) { bool[] found = new bool[1]; - node.Filter(new _NodeFilter_78(found)); + node.Filter(new _NodeFilter_77(found)); return found[0]; } - private sealed class _NodeFilter_78 : NodeFilter { - public _NodeFilter_78(bool[] found) { + private sealed class _NodeFilter_77 : NodeFilter { + public _NodeFilter_77(bool[] found) { this.found = found; } diff --git a/itext.tests/itext.styledxmlparser.tests/itext/styledxmlparser/jsoup/nodes/NodeTest.cs b/itext.tests/itext.styledxmlparser.tests/itext/styledxmlparser/jsoup/nodes/NodeTest.cs index 42169b439f..1f59f05764 100644 --- a/itext.tests/itext.styledxmlparser.tests/itext/styledxmlparser/jsoup/nodes/NodeTest.cs +++ b/itext.tests/itext.styledxmlparser.tests/itext/styledxmlparser/jsoup/nodes/NodeTest.cs @@ -248,12 +248,12 @@ public virtual void UnwrapNoChildren() { public virtual void Traverse() { Document doc = iText.StyledXmlParser.Jsoup.Jsoup.Parse("

    Hello

    There
    "); StringBuilder accum = new StringBuilder(); - doc.Select("div").First().Traverse(new _NodeVisitor_289(accum)); + doc.Select("div").First().Traverse(new _NodeVisitor_287(accum)); NUnit.Framework.Assert.AreEqual("

    <#text>

    ", accum.ToString()); } - private sealed class _NodeVisitor_289 : NodeVisitor { - public _NodeVisitor_289(StringBuilder accum) { + private sealed class _NodeVisitor_287 : NodeVisitor { + public _NodeVisitor_287(StringBuilder accum) { this.accum = accum; } diff --git a/itext.tests/itext.styledxmlparser.tests/itext/styledxmlparser/jsoup/parser/HtmlParserTest.cs b/itext.tests/itext.styledxmlparser.tests/itext/styledxmlparser/jsoup/parser/HtmlParserTest.cs index 5aeb519abc..daf0d5b927 100644 --- a/itext.tests/itext.styledxmlparser.tests/itext/styledxmlparser/jsoup/parser/HtmlParserTest.cs +++ b/itext.tests/itext.styledxmlparser.tests/itext/styledxmlparser/jsoup/parser/HtmlParserTest.cs @@ -87,7 +87,7 @@ public virtual void ParsesQuiteRoughAttributes() { // this (used to; now gets cleaner) gets a

    with attr '=a' and an OneSomething

    \nElse", doc.body().html()); + // Assertions.assertEquals("

    OneSomething

    \nElse", doc.body().html()); NUnit.Framework.Assert.AreEqual("

    One

    Something

    Else", TextUtil.StripNewlines (doc.Body().Html())); doc = iText.StyledXmlParser.Jsoup.Jsoup.Parse("

    "); diff --git a/itext.tests/itext.styledxmlparser.tests/itext/styledxmlparser/jsoup/parser/MultiLocaleTest.cs b/itext.tests/itext.styledxmlparser.tests/itext/styledxmlparser/jsoup/parser/MultiLocaleTest.cs index 8faace7ec4..5df0332d8e 100644 --- a/itext.tests/itext.styledxmlparser.tests/itext/styledxmlparser/jsoup/parser/MultiLocaleTest.cs +++ b/itext.tests/itext.styledxmlparser.tests/itext/styledxmlparser/jsoup/parser/MultiLocaleTest.cs @@ -23,14 +23,12 @@ You should have received a copy of the GNU Affero General Public License using System; using System.Collections.Generic; using System.Globalization; -using System.Linq; using iText.Commons.Utils; using iText.StyledXmlParser.Jsoup.Nodes; using iText.Test; namespace iText.StyledXmlParser.Jsoup.Parser { [NUnit.Framework.Category("UnitTest")] - [NUnit.Framework.TestFixtureSource("LocalesTestFixtureData")] public class MultiLocaleTest : ExtendedITextTest { private readonly CultureInfo defaultLocale = System.Threading.Thread.CurrentThread.CurrentUICulture; @@ -39,27 +37,13 @@ public static ICollection Locales() { )); } - public static ICollection LocalesTestFixtureData() { - return Locales().Select(array => new NUnit.Framework.TestFixtureData(array)).ToList(); - } - [NUnit.Framework.TearDown] public virtual void SetDefaultLocale() { System.Threading.Thread.CurrentThread.CurrentUICulture = defaultLocale; } - private CultureInfo locale; - - public MultiLocaleTest(CultureInfo locale) { - this.locale = locale; - } - - public MultiLocaleTest(CultureInfo[] array) - : this(array[0]) { - } - - [NUnit.Framework.Test] - public virtual void CaseSupport() { + [NUnit.Framework.TestCaseSource("Locales")] + public virtual void CaseSupport(CultureInfo locale) { System.Threading.Thread.CurrentThread.CurrentUICulture = locale; ParseSettings bothOn = new ParseSettings(true, true); ParseSettings bothOff = new ParseSettings(false, false); @@ -75,16 +59,16 @@ public virtual void CaseSupport() { NUnit.Framework.Assert.AreEqual("ID", attrOn.NormalizeAttribute("ID")); } - [NUnit.Framework.Test] - public virtual void AttributeCaseNormalization() { + [NUnit.Framework.TestCaseSource("Locales")] + public virtual void AttributeCaseNormalization(CultureInfo locale) { System.Threading.Thread.CurrentThread.CurrentUICulture = locale; ParseSettings parseSettings = new ParseSettings(false, false); String normalizedAttribute = parseSettings.NormalizeAttribute("HIDDEN"); NUnit.Framework.Assert.AreEqual("hidden", normalizedAttribute); } - [NUnit.Framework.Test] - public virtual void AttributesCaseNormalization() { + [NUnit.Framework.TestCaseSource("Locales")] + public virtual void AttributesCaseNormalization(CultureInfo locale) { System.Threading.Thread.CurrentThread.CurrentUICulture = locale; ParseSettings parseSettings = new ParseSettings(false, false); Attributes attributes = new Attributes(); @@ -93,8 +77,8 @@ public virtual void AttributesCaseNormalization() { NUnit.Framework.Assert.AreEqual("item", normalizedAttributes.AsList()[0].Key); } - [NUnit.Framework.Test] - public virtual void CanBeInsensitive() { + [NUnit.Framework.TestCaseSource("Locales")] + public virtual void CanBeInsensitive(CultureInfo locale) { System.Threading.Thread.CurrentThread.CurrentUICulture = locale; iText.StyledXmlParser.Jsoup.Parser.Tag script1 = iText.StyledXmlParser.Jsoup.Parser.Tag.ValueOf("script", ParseSettings.htmlDefault); diff --git a/itext.tests/itext.styledxmlparser.tests/itext/styledxmlparser/jsoup/select/MultiLocaleTest.cs b/itext.tests/itext.styledxmlparser.tests/itext/styledxmlparser/jsoup/select/MultiLocaleTest.cs index 2dbd3f8181..ed964bb508 100644 --- a/itext.tests/itext.styledxmlparser.tests/itext/styledxmlparser/jsoup/select/MultiLocaleTest.cs +++ b/itext.tests/itext.styledxmlparser.tests/itext/styledxmlparser/jsoup/select/MultiLocaleTest.cs @@ -23,14 +23,12 @@ You should have received a copy of the GNU Affero General Public License using System; using System.Collections.Generic; using System.Globalization; -using System.Linq; using iText.Commons.Utils; using iText.StyledXmlParser.Jsoup.Nodes; using iText.Test; namespace iText.StyledXmlParser.Jsoup.Select { [NUnit.Framework.Category("UnitTest")] - [NUnit.Framework.TestFixtureSource("LocalesTestFixtureData")] public class MultiLocaleTest : ExtendedITextTest { private readonly CultureInfo defaultLocale = System.Threading.Thread.CurrentThread.CurrentUICulture; @@ -39,27 +37,13 @@ public static ICollection Locales() { )); } - public static ICollection LocalesTestFixtureData() { - return Locales().Select(array => new NUnit.Framework.TestFixtureData(array)).ToList(); - } - [NUnit.Framework.TearDown] public virtual void SetDefaultLocale() { System.Threading.Thread.CurrentThread.CurrentUICulture = defaultLocale; } - private CultureInfo locale; - - public MultiLocaleTest(CultureInfo locale) { - this.locale = locale; - } - - public MultiLocaleTest(CultureInfo[] array) - : this(array[0]) { - } - - [NUnit.Framework.Test] - public virtual void TestByAttribute() { + [NUnit.Framework.TestCaseSource("Locales")] + public virtual void TestByAttribute(CultureInfo locale) { System.Threading.Thread.CurrentThread.CurrentUICulture = locale; String h = "

    " + "
    "; Document doc = iText.StyledXmlParser.Jsoup.Jsoup.Parse(h); @@ -91,8 +75,8 @@ public virtual void TestByAttribute() { NUnit.Framework.Assert.AreEqual("SLIM", contains.Last().Attr("title")); } - [NUnit.Framework.Test] - public virtual void TestPseudoContains() { + [NUnit.Framework.TestCaseSource("Locales")] + public virtual void TestPseudoContains(CultureInfo locale) { System.Threading.Thread.CurrentThread.CurrentUICulture = locale; Document doc = iText.StyledXmlParser.Jsoup.Jsoup.Parse("

    The Rain.

    The RAIN.

    Rain, the.

    " ); @@ -115,8 +99,8 @@ public virtual void TestPseudoContains() { NUnit.Framework.Assert.AreEqual(8, ps6.Count); } - [NUnit.Framework.Test] - public virtual void ContainsOwn() { + [NUnit.Framework.TestCaseSource("Locales")] + public virtual void ContainsOwn(CultureInfo locale) { System.Threading.Thread.CurrentThread.CurrentUICulture = locale; Document doc = iText.StyledXmlParser.Jsoup.Jsoup.Parse("

    Hello there igor

    "); Elements ps = doc.Select("p:containsOwn(Hello IGOR)"); @@ -127,8 +111,8 @@ public virtual void ContainsOwn() { NUnit.Framework.Assert.AreEqual(1, doc2.Select("p:containsOwn(igor)").Count); } - [NUnit.Framework.Test] - public virtual void ContainsData() { + [NUnit.Framework.TestCaseSource("Locales")] + public virtual void ContainsData(CultureInfo locale) { System.Threading.Thread.CurrentThread.CurrentUICulture = locale; String html = "

    function

    "; Document doc = iText.StyledXmlParser.Jsoup.Jsoup.Parse(html); @@ -152,8 +136,8 @@ public virtual void ContainsData() { NUnit.Framework.Assert.AreEqual(1, dataEls5.Count); } - [NUnit.Framework.Test] - public virtual void TestByAttributeStarting() { + [NUnit.Framework.TestCaseSource("Locales")] + public virtual void TestByAttributeStarting(CultureInfo locale) { System.Threading.Thread.CurrentThread.CurrentUICulture = locale; Document doc = iText.StyledXmlParser.Jsoup.Jsoup.Parse("
    Hello

    There

    No

    " ); diff --git a/itext.tests/itext.styledxmlparser.tests/itext/styledxmlparser/jsoup/select/TraversorTest.cs b/itext.tests/itext.styledxmlparser.tests/itext/styledxmlparser/jsoup/select/TraversorTest.cs index 479ffaaf46..2b121d39dd 100644 --- a/itext.tests/itext.styledxmlparser.tests/itext/styledxmlparser/jsoup/select/TraversorTest.cs +++ b/itext.tests/itext.styledxmlparser.tests/itext/styledxmlparser/jsoup/select/TraversorTest.cs @@ -34,13 +34,13 @@ public class TraversorTest : ExtendedITextTest { public virtual void FilterVisit() { Document doc = iText.StyledXmlParser.Jsoup.Jsoup.Parse("

    Hello

    There
    "); StringBuilder accum = new StringBuilder(); - NodeTraversor.Filter(new _NodeFilter_44(accum), doc.Select("div")); + NodeTraversor.Filter(new _NodeFilter_43(accum), doc.Select("div")); NUnit.Framework.Assert.AreEqual("

    <#text>

    <#text>
    ", accum.ToString ()); } - private sealed class _NodeFilter_44 : NodeFilter { - public _NodeFilter_44(StringBuilder accum) { + private sealed class _NodeFilter_43 : NodeFilter { + public _NodeFilter_43(StringBuilder accum) { this.accum = accum; } @@ -61,14 +61,14 @@ public override NodeFilter.FilterResult Tail(iText.StyledXmlParser.Jsoup.Nodes.N public virtual void FilterSkipChildren() { Document doc = iText.StyledXmlParser.Jsoup.Jsoup.Parse("

    Hello

    There
    "); StringBuilder accum = new StringBuilder(); - NodeTraversor.Filter(new _NodeFilter_64(accum), + NodeTraversor.Filter(new _NodeFilter_63(accum), // OMIT contents of p: doc.Select("div")); NUnit.Framework.Assert.AreEqual("

    <#text>
    ", accum.ToString()); } - private sealed class _NodeFilter_64 : NodeFilter { - public _NodeFilter_64(StringBuilder accum) { + private sealed class _NodeFilter_63 : NodeFilter { + public _NodeFilter_63(StringBuilder accum) { this.accum = accum; } @@ -89,14 +89,14 @@ public override NodeFilter.FilterResult Tail(iText.StyledXmlParser.Jsoup.Nodes.N public virtual void FilterSkipEntirely() { Document doc = iText.StyledXmlParser.Jsoup.Jsoup.Parse("

    Hello

    There
    "); StringBuilder accum = new StringBuilder(); - NodeTraversor.Filter(new _NodeFilter_85(accum), + NodeTraversor.Filter(new _NodeFilter_84(accum), // OMIT p: doc.Select("div")); NUnit.Framework.Assert.AreEqual("
    <#text>
    ", accum.ToString()); } - private sealed class _NodeFilter_85 : NodeFilter { - public _NodeFilter_85(StringBuilder accum) { + private sealed class _NodeFilter_84 : NodeFilter { + public _NodeFilter_84(StringBuilder accum) { this.accum = accum; } @@ -120,7 +120,7 @@ public override NodeFilter.FilterResult Tail(iText.StyledXmlParser.Jsoup.Nodes.N public virtual void FilterRemove() { Document doc = iText.StyledXmlParser.Jsoup.Jsoup.Parse("

    Hello

    There be bold
    " ); - NodeTraversor.Filter(new _NodeFilter_107(), + NodeTraversor.Filter(new _NodeFilter_106(), // Delete "p" in head: // Delete "b" in tail: @@ -128,8 +128,8 @@ public virtual void FilterRemove() { NUnit.Framework.Assert.AreEqual("
    \n
    \n There be \n
    ", doc.Select("body").Html()); } - private sealed class _NodeFilter_107 : NodeFilter { - public _NodeFilter_107() { + private sealed class _NodeFilter_106 : NodeFilter { + public _NodeFilter_106() { } public override NodeFilter.FilterResult Head(iText.StyledXmlParser.Jsoup.Nodes.Node node, int depth) { @@ -145,14 +145,14 @@ public override NodeFilter.FilterResult Tail(iText.StyledXmlParser.Jsoup.Nodes.N public virtual void FilterStop() { Document doc = iText.StyledXmlParser.Jsoup.Jsoup.Parse("

    Hello

    There
    "); StringBuilder accum = new StringBuilder(); - NodeTraversor.Filter(new _NodeFilter_127(accum), + NodeTraversor.Filter(new _NodeFilter_126(accum), // Stop after p. doc.Select("div")); NUnit.Framework.Assert.AreEqual("

    <#text>

    ", accum.ToString()); } - private sealed class _NodeFilter_127 : NodeFilter { - public _NodeFilter_127(StringBuilder accum) { + private sealed class _NodeFilter_126 : NodeFilter { + public _NodeFilter_126(StringBuilder accum) { this.accum = accum; } @@ -175,14 +175,14 @@ public virtual void ReplaceElement() { // test we can replace an element during traversal String html = "

    One two three four.

    "; Document doc = iText.StyledXmlParser.Jsoup.Jsoup.Parse(html); - NodeTraversor.Traverse(new _NodeVisitor_150(), doc); + NodeTraversor.Traverse(new _NodeVisitor_149(), doc); iText.StyledXmlParser.Jsoup.Nodes.Element p = doc.SelectFirst("p"); NUnit.Framework.Assert.IsNotNull(p); NUnit.Framework.Assert.AreEqual("

    One two three four.

    ", p.OuterHtml()); } - private sealed class _NodeVisitor_150 : NodeVisitor { - public _NodeVisitor_150() { + private sealed class _NodeVisitor_149 : NodeVisitor { + public _NodeVisitor_149() { } public void Head(iText.StyledXmlParser.Jsoup.Nodes.Node node, int depth) { @@ -203,13 +203,13 @@ public void Tail(iText.StyledXmlParser.Jsoup.Nodes.Node node, int depth) { [NUnit.Framework.Test] public virtual void CanAddChildren() { Document doc = iText.StyledXmlParser.Jsoup.Jsoup.Parse("

    "); - NodeTraversor.Traverse(new _NodeVisitor_174(), doc); + NodeTraversor.Traverse(new _NodeVisitor_173(), doc); NUnit.Framework.Assert.AreEqual("
    \n" + "

    01

    \n" + "

    23

    \n" + "
    ", doc.Body().Html()); } - private sealed class _NodeVisitor_174 : NodeVisitor { - public _NodeVisitor_174() { + private sealed class _NodeVisitor_173 : NodeVisitor { + public _NodeVisitor_173() { this.i = 0; } diff --git a/itext.tests/itext.svg.tests/Properties/AssemblyInfo.cs b/itext.tests/itext.svg.tests/Properties/AssemblyInfo.cs index 0b3da6e1cf..ff23a8f2f4 100644 --- a/itext.tests/itext.svg.tests/Properties/AssemblyInfo.cs +++ b/itext.tests/itext.svg.tests/Properties/AssemblyInfo.cs @@ -15,9 +15,9 @@ [assembly: Guid("ae4e5743-0665-4705-9a33-07ea57cdd269")] -[assembly: AssemblyVersion("8.0.5.0")] -[assembly: AssemblyFileVersion("8.0.5.0")] -[assembly: AssemblyInformationalVersion("8.0.5")] +[assembly: AssemblyVersion("9.0.0.0")] +[assembly: AssemblyFileVersion("9.0.0.0")] +[assembly: AssemblyInformationalVersion("9.0.0")] #if !NETSTANDARD2_0 [assembly: NUnit.Framework.Timeout(300000)] diff --git a/itext.tests/itext.svg.tests/itext/svg/renderers/SvgDrawContextTest.cs b/itext.tests/itext.svg.tests/itext/svg/renderers/SvgDrawContextTest.cs index 175f3bd76f..15d41e48e1 100644 --- a/itext.tests/itext.svg.tests/itext/svg/renderers/SvgDrawContextTest.cs +++ b/itext.tests/itext.svg.tests/itext/svg/renderers/SvgDrawContextTest.cs @@ -23,6 +23,8 @@ You should have received a copy of the GNU Affero General Public License using System; using System.Collections.Generic; using System.IO; +using iText.IO.Util; +using iText.Kernel.Geom; using iText.Kernel.Pdf; using iText.Kernel.Pdf.Canvas; using iText.Svg.Dummy.Renderers.Impl; @@ -192,5 +194,14 @@ public virtual void AddNamedObjectAndTryToAddDuplicate() { Object actual = context.GetNamedObject(dummyName); NUnit.Framework.Assert.AreEqual(expectedOne, actual); } + + [NUnit.Framework.Test] + public virtual void RootTransformText() { + AffineTransform at = new AffineTransform(); + NUnit.Framework.Assert.AreEqual(at, context.GetRootTransform()); + at.SetToRotation(MathUtil.ToRadians(45)); + context.SetRootTransform(at); + NUnit.Framework.Assert.AreEqual(at, context.GetRootTransform()); + } } } diff --git a/itext.tests/itext.svg.tests/itext/svg/renderers/TransformationApplicationTest.cs b/itext.tests/itext.svg.tests/itext/svg/renderers/TransformationApplicationTest.cs index f9279957dc..2e58c47659 100644 --- a/itext.tests/itext.svg.tests/itext/svg/renderers/TransformationApplicationTest.cs +++ b/itext.tests/itext.svg.tests/itext/svg/renderers/TransformationApplicationTest.cs @@ -36,7 +36,7 @@ public class TransformationApplicationTest : ExtendedITextTest { [NUnit.Framework.Test] public virtual void NormalDrawTest() { byte[] expected = "1 0 0 1 7.5 0 cm\n0 0 0 rg\nf\n".GetBytes(System.Text.Encoding.UTF8); - ISvgNodeRenderer nodeRenderer = new _AbstractSvgNodeRenderer_51(); + ISvgNodeRenderer nodeRenderer = new _AbstractSvgNodeRenderer_50(); // do nothing IDictionary attributeMap = new Dictionary(); attributeMap.Put(SvgConstants.Attributes.TRANSFORM, "translate(10)"); @@ -50,8 +50,8 @@ public virtual void NormalDrawTest() { NUnit.Framework.Assert.AreEqual(expected, actual); } - private sealed class _AbstractSvgNodeRenderer_51 : AbstractSvgNodeRenderer { - public _AbstractSvgNodeRenderer_51() { + private sealed class _AbstractSvgNodeRenderer_50 : AbstractSvgNodeRenderer { + public _AbstractSvgNodeRenderer_50() { } public override ISvgNodeRenderer CreateDeepCopy() { diff --git a/itext.tests/itext.svg.tests/itext/svg/renderers/impl/LinearGradientSvgNodeRendererTest.cs b/itext.tests/itext.svg.tests/itext/svg/renderers/impl/LinearGradientSvgNodeRendererTest.cs index 242a2979d0..ea10cd61c9 100644 --- a/itext.tests/itext.svg.tests/itext/svg/renderers/impl/LinearGradientSvgNodeRendererTest.cs +++ b/itext.tests/itext.svg.tests/itext/svg/renderers/impl/LinearGradientSvgNodeRendererTest.cs @@ -353,7 +353,6 @@ public virtual void TextXYOffset() { [NUnit.Framework.Test] public virtual void TextXOffset() { - // TODO DEVSIX-4143 change cmp file after fixing ConvertAndCompare(sourceFolder, destinationFolder, "textXOffset"); } @@ -529,7 +528,6 @@ public virtual void TranslateTransformInGradientWithObjectBoundingBoxUnitsTest() [NUnit.Framework.Test] public virtual void MatrixTransformInGradientWithObjectBoundingBoxUnitsTest() { - //TODO change cmp after DEVSIX-4143 is fixed (bug with only one absolute coordinate in tspan) ConvertAndCompare(sourceFolder, destinationFolder, "matrixTransformInGradientWithObjectBoundingBoxUnits"); } diff --git a/itext.tests/itext.svg.tests/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest.cs b/itext.tests/itext.svg.tests/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest.cs index 8a8898ba48..c9c9102230 100644 --- a/itext.tests/itext.svg.tests/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest.cs +++ b/itext.tests/itext.svg.tests/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest.cs @@ -210,5 +210,20 @@ public virtual void TspanNestedRelativeOffsets() { public virtual void SimpleNestedTspanTest() { ConvertAndCompareSinglePage(SOURCE_FOLDER, DESTINATION_FOLDER, "simpleNestedTspan"); } + + [NUnit.Framework.Test] + public virtual void XWithoutYTest() { + ConvertAndCompareSinglePage(SOURCE_FOLDER, DESTINATION_FOLDER, "xWithoutY"); + } + + [NUnit.Framework.Test] + public virtual void NoXNoYTest() { + ConvertAndCompareSinglePage(SOURCE_FOLDER, DESTINATION_FOLDER, "noXNoY"); + } + + [NUnit.Framework.Test] + public virtual void YWithoutXTest() { + ConvertAndCompareSinglePage(SOURCE_FOLDER, DESTINATION_FOLDER, "yWithoutX"); + } } } diff --git a/itext.tests/itext.svg.tests/itext/svg/renderers/impl/TextSvgBranchRendererIntegrationTest.cs b/itext.tests/itext.svg.tests/itext/svg/renderers/impl/TextSvgBranchRendererIntegrationTest.cs index fbfcd5900c..0f42fb4d8a 100644 --- a/itext.tests/itext.svg.tests/itext/svg/renderers/impl/TextSvgBranchRendererIntegrationTest.cs +++ b/itext.tests/itext.svg.tests/itext/svg/renderers/impl/TextSvgBranchRendererIntegrationTest.cs @@ -216,7 +216,6 @@ public virtual void TextFontSizeExUnitsTest() { [NUnit.Framework.Test] public virtual void TspanWithOneAbsoluteCoordinateTest() { - // TODO change cmp after DEVSIX-4143 is fixed ConvertAndCompareSinglePage(SOURCE_FOLDER, DESTINATION_FOLDER, "tspanWithOneAbsoluteCoordinateTest"); } } diff --git a/itext.tests/itext.svg.tests/itext/svg/renderers/path/impl/EllipseArcTest.cs b/itext.tests/itext.svg.tests/itext/svg/renderers/path/impl/EllipseArcTest.cs index 5236a59c6e..fb3055ae54 100644 --- a/itext.tests/itext.svg.tests/itext/svg/renderers/path/impl/EllipseArcTest.cs +++ b/itext.tests/itext.svg.tests/itext/svg/renderers/path/impl/EllipseArcTest.cs @@ -29,8 +29,8 @@ public class EllipseArcTest : ExtendedITextTest { private const double DELTA = 0.00001; private void AssertPointEqual(Point expected, Point actual) { - NUnit.Framework.Assert.AreEqual(expected.x, actual.x, DELTA); - NUnit.Framework.Assert.AreEqual(expected.y, actual.y, DELTA); + NUnit.Framework.Assert.AreEqual(expected.GetX(), actual.GetX(), DELTA); + NUnit.Framework.Assert.AreEqual(expected.GetY(), actual.GetY(), DELTA); } [NUnit.Framework.Test] diff --git a/itext.tests/itext.svg.tests/itext/svg/renderers/path/impl/EllipticalPathOperatorTest.cs b/itext.tests/itext.svg.tests/itext/svg/renderers/path/impl/EllipticalPathOperatorTest.cs index 886bddb630..252d9a21de 100644 --- a/itext.tests/itext.svg.tests/itext/svg/renderers/path/impl/EllipticalPathOperatorTest.cs +++ b/itext.tests/itext.svg.tests/itext/svg/renderers/path/impl/EllipticalPathOperatorTest.cs @@ -103,8 +103,8 @@ private void AssertPointArrayArrayEquals(Point[][] expected, Point[][] actual) { private void AssertPointArrayEquals(Point[] expected, Point[] actual) { NUnit.Framework.Assert.AreEqual(expected.Length, actual.Length); for (int i = 0; i < expected.Length; i++) { - NUnit.Framework.Assert.AreEqual(expected[i].x, actual[i].x, 0.00001); - NUnit.Framework.Assert.AreEqual(expected[i].y, actual[i].y, 0.00001); + NUnit.Framework.Assert.AreEqual(expected[i].GetX(), actual[i].GetX(), 0.00001); + NUnit.Framework.Assert.AreEqual(expected[i].GetY(), actual[i].GetY(), 0.00001); } } diff --git a/itext.tests/itext.svg.tests/itext/svg/utils/TransformUtilsTest.cs b/itext.tests/itext.svg.tests/itext/svg/utils/TransformUtilsTest.cs index 0cb7527916..f355307397 100644 --- a/itext.tests/itext.svg.tests/itext/svg/utils/TransformUtilsTest.cs +++ b/itext.tests/itext.svg.tests/itext/svg/utils/TransformUtilsTest.cs @@ -118,6 +118,13 @@ public virtual void CombinedReverseTransformTest() { NUnit.Framework.Assert.AreEqual(actual, expected); } + [NUnit.Framework.Test] + public virtual void CombinedReverseTransformWithCommaTest() { + AffineTransform actual = TransformUtils.ParseTransform("scale(3),translate(40,20)"); + AffineTransform expected = new AffineTransform(3d, 0d, 0d, 3d, 90d, 45d); + NUnit.Framework.Assert.AreEqual(actual, expected); + } + [NUnit.Framework.Test] public virtual void DoubleTransformationTest() { AffineTransform expected = new AffineTransform(9d, 0d, 0d, 9d, 0d, 0d); diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/converter/SvgConverterTest/cmp_CTI_eclipse_StreamDocument.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/converter/SvgConverterTest/cmp_CTI_eclipse_StreamDocument.pdf deleted file mode 100644 index 61838b64df..0000000000 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/converter/SvgConverterTest/cmp_CTI_eclipse_StreamDocument.pdf and /dev/null differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/converter/SvgConverterTest/cmp_CTI_eclipse_StreamDocumentProps.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/converter/SvgConverterTest/cmp_CTI_eclipse_StreamDocumentProps.pdf deleted file mode 100644 index 78744674ef..0000000000 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/converter/SvgConverterTest/cmp_CTI_eclipse_StreamDocumentProps.pdf and /dev/null differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/converter/SvgConverterTest/cmp_CTI_eclipse_StreamDocument_props.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/converter/SvgConverterTest/cmp_CTI_eclipse_StreamDocument_props.pdf deleted file mode 100644 index ea0d5a8b63..0000000000 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/converter/SvgConverterTest/cmp_CTI_eclipse_StreamDocument_props.pdf and /dev/null differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/css/DefaultInheritance/useGroupInheritance.svg b/itext.tests/itext.svg.tests/resources/itext/svg/css/DefaultInheritance/useGroupInheritance.svg deleted file mode 100644 index 65a3764d67..0000000000 --- a/itext.tests/itext.svg.tests/resources/itext/svg/css/DefaultInheritance/useGroupInheritance.svg +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/css/SvgStyleResolver/web-fonts/NotoSansCJK-Regular.woff2 b/itext.tests/itext.svg.tests/resources/itext/svg/css/SvgStyleResolver/web-fonts/NotoSansCJK-Regular.woff2 deleted file mode 100644 index 77e3b2613c..0000000000 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/css/SvgStyleResolver/web-fonts/NotoSansCJK-Regular.woff2 and /dev/null differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/css/SvgStyleResolver/web-fonts/open-sans-v15-latin-regular.ttf b/itext.tests/itext.svg.tests/resources/itext/svg/css/SvgStyleResolver/web-fonts/open-sans-v15-latin-regular.ttf deleted file mode 100644 index 9d4e8e526d..0000000000 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/css/SvgStyleResolver/web-fonts/open-sans-v15-latin-regular.ttf and /dev/null differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/processors/impl/font/FontFaceTest/w3c-test-fonts/cmp_droidSerifLocalWithMediaFontTest.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/processors/impl/font/FontFaceTest/w3c-test-fonts/cmp_droidSerifLocalWithMediaFontTest.pdf deleted file mode 100644 index bb5fb7d088..0000000000 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/processors/impl/font/FontFaceTest/w3c-test-fonts/cmp_droidSerifLocalWithMediaFontTest.pdf and /dev/null differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/DeepCopyTest/deepCopyExample.svg b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/DeepCopyTest/deepCopyExample.svg deleted file mode 100644 index d40c7b4266..0000000000 --- a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/DeepCopyTest/deepCopyExample.svg +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/EllipseSvgNodeRendererIntegrationTest/Ellipse.svg b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/EllipseSvgNodeRendererIntegrationTest/Ellipse.svg deleted file mode 100644 index eb61d28293..0000000000 --- a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/EllipseSvgNodeRendererIntegrationTest/Ellipse.svg +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/FillTest/cmp_eofillUnsuportedAtributeTest.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/FillTest/cmp_eofillUnsuportedAtributeTest.pdf deleted file mode 100644 index 732e4b8bb1..0000000000 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/FillTest/cmp_eofillUnsuportedAtributeTest.pdf and /dev/null differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/GroupRendererTest/doubleOccurrenceNestedGroup.svg b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/GroupRendererTest/doubleOccurrenceNestedGroup.svg deleted file mode 100644 index 493e106266..0000000000 --- a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/GroupRendererTest/doubleOccurrenceNestedGroup.svg +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/GroupRendererTest/simpleG.svg b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/GroupRendererTest/simpleG.svg deleted file mode 100644 index db983ce5f0..0000000000 --- a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/GroupRendererTest/simpleG.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/ImageSvgNodeRendererTest/random.svg b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/ImageSvgNodeRendererTest/random.svg deleted file mode 100644 index cffd6aab1b..0000000000 --- a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/ImageSvgNodeRendererTest/random.svg +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/LineSvgNodeRendererTest/cmp_invalidAttributes02.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/LineSvgNodeRendererTest/cmp_invalidAttributes02.pdf deleted file mode 100644 index 513347240b..0000000000 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/LineSvgNodeRendererTest/cmp_invalidAttributes02.pdf and /dev/null differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/LineSvgNodeRendererTest/lineBlue.svg b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/LineSvgNodeRendererTest/lineBlue.svg deleted file mode 100644 index badf0a0258..0000000000 --- a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/LineSvgNodeRendererTest/lineBlue.svg +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/LineSvgNodeRendererTest/lineRendererTest.svg b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/LineSvgNodeRendererTest/lineRendererTest.svg deleted file mode 100644 index cd4aae1888..0000000000 --- a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/LineSvgNodeRendererTest/lineRendererTest.svg +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/LinearGradientSvgNodeRendererTest/cmp_text.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/LinearGradientSvgNodeRendererTest/cmp_text.pdf index 18388ac11d..2bd40bef4e 100644 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/LinearGradientSvgNodeRendererTest/cmp_text.pdf and b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/LinearGradientSvgNodeRendererTest/cmp_text.pdf differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/LinearGradientSvgNodeRendererTest/cmp_textXOffset.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/LinearGradientSvgNodeRendererTest/cmp_textXOffset.pdf index 8b180cdf7d..0002429049 100644 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/LinearGradientSvgNodeRendererTest/cmp_textXOffset.pdf and b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/LinearGradientSvgNodeRendererTest/cmp_textXOffset.pdf differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/MarkerSvgNodeRendererIntegrationTest/markerSimple.svg b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/MarkerSvgNodeRendererIntegrationTest/markerSimple.svg deleted file mode 100644 index 672ed2dad6..0000000000 --- a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/MarkerSvgNodeRendererIntegrationTest/markerSimple.svg +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/MarkerSvgNodeRendererIntegrationTest/oneShapePath.svg b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/MarkerSvgNodeRendererIntegrationTest/oneShapePath.svg deleted file mode 100644 index 013e9f8421..0000000000 --- a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/MarkerSvgNodeRendererIntegrationTest/oneShapePath.svg +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/OpacityTest/testStrokeOpacityWithComma.svg b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/OpacityTest/testStrokeOpacityWithComma.svg deleted file mode 100644 index 42a3f17867..0000000000 --- a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/OpacityTest/testStrokeOpacityWithComma.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/PathSvgNodeRendererTest/CurveToTest1.svg b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/PathSvgNodeRendererTest/CurveToTest1.svg deleted file mode 100644 index 2484cbd5af..0000000000 --- a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/PathSvgNodeRendererTest/CurveToTest1.svg +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/PathSvgNodeRendererTest/cmp_eofillUnsuportedPathTest.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/PathSvgNodeRendererTest/cmp_eofillUnsuportedPathTest.pdf deleted file mode 100644 index d3339fd3d1..0000000000 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/PathSvgNodeRendererTest/cmp_eofillUnsuportedPathTest.pdf and /dev/null differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/PathSvgNodeRendererTest/cmp_pathZOperatorTest01.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/PathSvgNodeRendererTest/cmp_pathZOperatorTest01.pdf deleted file mode 100644 index af2ba45dd1..0000000000 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/PathSvgNodeRendererTest/cmp_pathZOperatorTest01.pdf and /dev/null differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/PathSvgNodeRendererTest/cmp_pathZOperatorTest03.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/PathSvgNodeRendererTest/cmp_pathZOperatorTest03.pdf deleted file mode 100644 index f1ae897843..0000000000 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/PathSvgNodeRendererTest/cmp_pathZOperatorTest03.pdf and /dev/null differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/PathSvgNodeRendererTest/pathMultipleSuccessiveVOperatorsTest.svg b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/PathSvgNodeRendererTest/pathMultipleSuccessiveVOperatorsTest.svg deleted file mode 100644 index 6f1d28404f..0000000000 --- a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/PathSvgNodeRendererTest/pathMultipleSuccessiveVOperatorsTest.svg +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/PathSvgNodeRendererTest/simple.svg b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/PathSvgNodeRendererTest/simple.svg deleted file mode 100644 index 74dea5734d..0000000000 --- a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/PathSvgNodeRendererTest/simple.svg +++ /dev/null @@ -1,5 +0,0 @@ - - \ No newline at end of file diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/PatternTest/cmp_patternInsideOtherOne.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/PatternTest/cmp_patternInsideOtherOne.pdf deleted file mode 100644 index 9e0c350fdb..0000000000 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/PatternTest/cmp_patternInsideOtherOne.pdf and /dev/null differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/PatternTest/cmp_widthHeighXYNoMeasureUnit.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/PatternTest/cmp_widthHeighXYNoMeasureUnit.pdf deleted file mode 100644 index f90bd2052c..0000000000 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/PatternTest/cmp_widthHeighXYNoMeasureUnit.pdf and /dev/null differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/PreserveAspectRatioSvgNodeRendererIntegrationTest/ITSC-Logo-Horizontal-PMS-72dpi-compressor.png b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/PreserveAspectRatioSvgNodeRendererIntegrationTest/ITSC-Logo-Horizontal-PMS-72dpi-compressor.png deleted file mode 100644 index 8dd982690b..0000000000 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/PreserveAspectRatioSvgNodeRendererIntegrationTest/ITSC-Logo-Horizontal-PMS-72dpi-compressor.png and /dev/null differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/RectangleSvgNodeRendererTest/rectangleTesting.svg b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/RectangleSvgNodeRendererTest/rectangleTesting.svg deleted file mode 100644 index 0217924bd6..0000000000 --- a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/RectangleSvgNodeRendererTest/rectangleTesting.svg +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/RootSvgNodeRendererTest/cmp_viewbox_scaling_DoNotPreserveAspectRatio_all.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/RootSvgNodeRendererTest/cmp_viewbox_scaling_DoNotPreserveAspectRatio_all.pdf deleted file mode 100644 index 55fa76ab34..0000000000 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/RootSvgNodeRendererTest/cmp_viewbox_scaling_DoNotPreserveAspectRatio_all.pdf and /dev/null differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/RootSvgNodeRendererTest/svg/absentEverything.svg b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/RootSvgNodeRendererTest/svg/absentEverything.svg deleted file mode 100644 index 3735aec84c..0000000000 --- a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/RootSvgNodeRendererTest/svg/absentEverything.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/RootSvgNodeRendererTest/svg/absentXY.svg b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/RootSvgNodeRendererTest/svg/absentXY.svg deleted file mode 100644 index 1be98d94a4..0000000000 --- a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/RootSvgNodeRendererTest/svg/absentXY.svg +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/RootSvgNodeRendererTest/svg/cmp_absentEverything.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/RootSvgNodeRendererTest/svg/cmp_absentEverything.pdf deleted file mode 100644 index 8e2476480c..0000000000 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/RootSvgNodeRendererTest/svg/cmp_absentEverything.pdf and /dev/null differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/RootSvgNodeRendererTest/svg/cmp_invalidWidth.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/RootSvgNodeRendererTest/svg/cmp_invalidWidth.pdf deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/RootSvgNodeRendererTest/viewbox/cmp_viewbox_100.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/RootSvgNodeRendererTest/viewbox/cmp_viewbox_100.pdf deleted file mode 100644 index ba49522be1..0000000000 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/RootSvgNodeRendererTest/viewbox/cmp_viewbox_100.pdf and /dev/null differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/RootSvgNodeRendererTest/viewbox/cmp_viewbox_400.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/RootSvgNodeRendererTest/viewbox/cmp_viewbox_400.pdf deleted file mode 100644 index 35df52551d..0000000000 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/RootSvgNodeRendererTest/viewbox/cmp_viewbox_400.pdf and /dev/null differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/RootSvgNodeRendererTest/viewbox/cmp_viewbox_50.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/RootSvgNodeRendererTest/viewbox/cmp_viewbox_50.pdf deleted file mode 100644 index 0b5383ef4c..0000000000 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/RootSvgNodeRendererTest/viewbox/cmp_viewbox_50.pdf and /dev/null differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/SymbolTest/cmp_interactionOfCoordinatesUsingSymbolTag.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/SymbolTest/cmp_interactionOfCoordinatesUsingSymbolTag.pdf deleted file mode 100644 index 1ac038f72a..0000000000 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/SymbolTest/cmp_interactionOfCoordinatesUsingSymbolTag.pdf and /dev/null differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/SymbolTest/cmp_widthHeightAttrTest.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/SymbolTest/cmp_widthHeightAttrTest.pdf deleted file mode 100644 index 569c39c84e..0000000000 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/SymbolTest/cmp_widthHeightAttrTest.pdf and /dev/null differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/SymbolTest/cmp_xYInUseTest.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/SymbolTest/cmp_xYInUseTest.pdf deleted file mode 100644 index 38bdfcaba0..0000000000 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/SymbolTest/cmp_xYInUseTest.pdf and /dev/null differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_noXNoY.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_noXNoY.pdf new file mode 100644 index 0000000000..43cd7c134b Binary files /dev/null and b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_noXNoY.pdf differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_simpleNestedTspan.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_simpleNestedTspan.pdf index 728e35402c..372c8e819e 100644 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_simpleNestedTspan.pdf and b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_simpleNestedTspan.pdf differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-relativeMove-XandY.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-relativeMove-XandY.pdf index cf55eb70d0..0b86e313b5 100644 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-relativeMove-XandY.pdf and b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-relativeMove-XandY.pdf differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-relativeMove-negativeX.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-relativeMove-negativeX.pdf index 3fa336afc9..63e3ecb6bc 100644 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-relativeMove-negativeX.pdf and b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-relativeMove-negativeX.pdf differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-relativeMove-negativeY.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-relativeMove-negativeY.pdf index c5110239d9..31cff5ad72 100644 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-relativeMove-negativeY.pdf and b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-relativeMove-negativeY.pdf differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-relativeMove-positiveX.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-relativeMove-positiveX.pdf index 6e57b6a0a5..599032a8d6 100644 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-relativeMove-positiveX.pdf and b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-relativeMove-positiveX.pdf differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-relativeMove-positiveY.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-relativeMove-positiveY.pdf index 966ae9041b..5464920f8e 100644 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-relativeMove-positiveY.pdf and b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-relativeMove-positiveY.pdf differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-relativeMove-zeroX.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-relativeMove-zeroX.pdf index f42fec5336..c625e22eb8 100644 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-relativeMove-zeroX.pdf and b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-relativeMove-zeroX.pdf differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-relativeMove-zeroY.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-relativeMove-zeroY.pdf index dafc4b209e..aafdf7a75e 100644 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-relativeMove-zeroY.pdf and b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-relativeMove-zeroY.pdf differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-whitespace.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-whitespace.pdf index 2a0e17ab75..b84fec838b 100644 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-whitespace.pdf and b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_textspan-whitespace.pdf differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_tspanBasicExample.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_tspanBasicExample.pdf index 316e85de0d..d52f7006f8 100644 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_tspanBasicExample.pdf and b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_tspanBasicExample.pdf differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_tspanNestedExample.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_tspanNestedExample.pdf index 2c4de10513..5f5ae59a31 100644 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_tspanNestedExample.pdf and b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_tspanNestedExample.pdf differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_tspanNestedRelativeOffsets.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_tspanNestedRelativeOffsets.pdf index 1c197f79fa..2688f55896 100644 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_tspanNestedRelativeOffsets.pdf and b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_tspanNestedRelativeOffsets.pdf differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_xWithoutY.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_xWithoutY.pdf new file mode 100644 index 0000000000..32a01f48bf Binary files /dev/null and b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_xWithoutY.pdf differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_yWithoutX.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_yWithoutX.pdf new file mode 100644 index 0000000000..39e3ef8c19 Binary files /dev/null and b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/cmp_yWithoutX.pdf differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/noXNoY.svg b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/noXNoY.svg new file mode 100644 index 0000000000..edf2d126d2 --- /dev/null +++ b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/noXNoY.svg @@ -0,0 +1,7 @@ + + + + Line1 + Line2 + + diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/xWithoutY.svg b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/xWithoutY.svg new file mode 100644 index 0000000000..d7d851f750 --- /dev/null +++ b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/xWithoutY.svg @@ -0,0 +1,11 @@ + + + + Line1 + Line2 + + + Line1 + Line2 + + diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/yWithoutX.svg b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/yWithoutX.svg new file mode 100644 index 0000000000..3e196d15a0 --- /dev/null +++ b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TSpanNodeRendererIntegrationTest/yWithoutX.svg @@ -0,0 +1,7 @@ + + + + Line1 + Line2 + + diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TextSvgBranchRendererIntegrationTest/cmp_tspanWithOneAbsoluteCoordinateTest.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TextSvgBranchRendererIntegrationTest/cmp_tspanWithOneAbsoluteCoordinateTest.pdf index bdd3417fee..bbf927bea2 100644 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TextSvgBranchRendererIntegrationTest/cmp_tspanWithOneAbsoluteCoordinateTest.pdf and b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/TextSvgBranchRendererIntegrationTest/cmp_tspanWithOneAbsoluteCoordinateTest.pdf differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/cmp_test_001.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/cmp_test_001.pdf deleted file mode 100644 index 331c69e31f..0000000000 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/cmp_test_001.pdf and /dev/null differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/cmp_test_002.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/cmp_test_002.pdf deleted file mode 100644 index 473d2bc561..0000000000 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/cmp_test_002.pdf and /dev/null differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/cmp_test_003.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/cmp_test_003.pdf deleted file mode 100644 index ecec412586..0000000000 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/cmp_test_003.pdf and /dev/null differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/cmp_test_004.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/cmp_test_004.pdf deleted file mode 100644 index e60da6f349..0000000000 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/cmp_test_004.pdf and /dev/null differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/cmp_test_005.pdf b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/cmp_test_005.pdf deleted file mode 100644 index 50f4f04a7c..0000000000 Binary files a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/cmp_test_005.pdf and /dev/null differ diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/test_001.svg b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/test_001.svg deleted file mode 100644 index 4d1a3c20a8..0000000000 --- a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/test_001.svg +++ /dev/null @@ -1,1026 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/test_002.svg b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/test_002.svg deleted file mode 100644 index 9f84bffb62..0000000000 --- a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/test_002.svg +++ /dev/null @@ -1,1027 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/test_003.svg b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/test_003.svg deleted file mode 100644 index f5e35481ef..0000000000 --- a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/test_003.svg +++ /dev/null @@ -1,1027 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/test_004.svg b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/test_004.svg deleted file mode 100644 index 6a96621cfc..0000000000 --- a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/test_004.svg +++ /dev/null @@ -1,1027 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/test_005.svg b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/test_005.svg deleted file mode 100644 index 6becae3b43..0000000000 --- a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/test_005.svg +++ /dev/null @@ -1,1027 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/test_006.svg b/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/test_006.svg deleted file mode 100644 index 3abe147056..0000000000 --- a/itext.tests/itext.svg.tests/resources/itext/svg/renderers/impl/gunit/test_006.svg +++ /dev/null @@ -1,1328 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/itext/itext.barcodes/Properties/AssemblyInfo.cs b/itext/itext.barcodes/Properties/AssemblyInfo.cs index 07c15afb49..a4bad7ea9d 100644 --- a/itext/itext.barcodes/Properties/AssemblyInfo.cs +++ b/itext/itext.barcodes/Properties/AssemblyInfo.cs @@ -21,6 +21,6 @@ [assembly: Guid("8694665a-5749-40c6-9e9c-53c686a77ad1")] -[assembly: AssemblyVersion("8.0.5.0")] -[assembly: AssemblyFileVersion("8.0.5.0")] -[assembly: AssemblyInformationalVersion("8.0.5")] +[assembly: AssemblyVersion("9.0.0.0")] +[assembly: AssemblyFileVersion("9.0.0.0")] +[assembly: AssemblyInformationalVersion("9.0.0")] diff --git a/itext/itext.barcodes/itext/barcodes/BarcodeDataMatrix.cs b/itext/itext.barcodes/itext/barcodes/BarcodeDataMatrix.cs index 589b021387..52047696db 100644 --- a/itext/itext.barcodes/itext/barcodes/BarcodeDataMatrix.cs +++ b/itext/itext.barcodes/itext/barcodes/BarcodeDataMatrix.cs @@ -296,24 +296,24 @@ public virtual int SetCode(byte[] text, int textOffset, int textSize) { ], new int[textSize - extOut], new int[textSize - extOut], new int[textSize - extOut] }; if (height == 0 || width == 0) { last = dmSizes[dmSizes.Length - 1]; - e = GetEncodation(text, textOffset + extOut, textSize - extOut, data, extCount, last.dataSize - extCount, - options, false); + e = GetEncodation(text, textOffset + extOut, textSize - extOut, data, extCount, last.GetDataSize() - extCount + , options, false); if (e < 0) { return DM_ERROR_TEXT_TOO_BIG; } e += extCount; for (k = 0; k < dmSizes.Length; ++k) { - if (dmSizes[k].dataSize >= e) { + if (dmSizes[k].GetDataSize() >= e) { break; } } dm = dmSizes[k]; - height = dm.height; - width = dm.width; + height = dm.GetHeight(); + width = dm.GetWidth(); } else { for (k = 0; k < dmSizes.Length; ++k) { - if (height == dmSizes[k].height && width == dmSizes[k].width) { + if (height == dmSizes[k].GetHeight() && width == dmSizes[k].GetWidth()) { break; } } @@ -321,8 +321,8 @@ public virtual int SetCode(byte[] text, int textOffset, int textSize) { return DM_ERROR_INVALID_SQUARE; } dm = dmSizes[k]; - e = GetEncodation(text, textOffset + extOut, textSize - extOut, data, extCount, dm.dataSize - extCount, options - , true); + e = GetEncodation(text, textOffset + extOut, textSize - extOut, data, extCount, dm.GetDataSize() - extCount + , options, true); if (e < 0) { return DM_ERROR_TEXT_TOO_BIG; } @@ -331,12 +331,12 @@ public virtual int SetCode(byte[] text, int textOffset, int textSize) { if ((options & DM_TEST) != 0) { return DM_NO_ERROR; } - image = new byte[(dm.width + 2 * ws + 7) / 8 * (dm.height + 2 * ws)]; - MakePadding(data, e, dm.dataSize - e); - place = Placement.DoPlacement(dm.height - dm.height / dm.heightSection * 2, dm.width - dm.width / dm.widthSection - * 2); - full = dm.dataSize + (dm.dataSize + 2) / dm.dataBlock * dm.errorBlock; - ReedSolomon.GenerateECC(data, dm.dataSize, dm.dataBlock, dm.errorBlock); + image = new byte[(dm.GetWidth() + 2 * ws + 7) / 8 * (dm.GetHeight() + 2 * ws)]; + MakePadding(data, e, dm.GetDataSize() - e); + place = Placement.DoPlacement(dm.GetHeight() - dm.GetHeight() / dm.GetHeightSection() * 2, dm.GetWidth() - + dm.GetWidth() / dm.GetWidthSection() * 2); + full = dm.GetDataSize() + (dm.GetDataSize() + 2) / dm.GetDataBlock() * dm.GetErrorBlock(); + ReedSolomon.GenerateECC(data, dm.GetDataSize(), dm.GetDataBlock(), dm.GetErrorBlock()); Draw(data, full, dm); return DM_NO_ERROR; } @@ -831,8 +831,8 @@ private int EdifactEncodation(byte[] text, int textOffset, int textLength, byte[ if (!sizeFixed && (symbolIndex == text.Length - 1 || symbolIndex < 0) && textLength % 4 < 3) { dataSize = int.MaxValue; for (int i = 0; i < dmSizes.Length; ++i) { - if (dmSizes[i].dataSize >= dataRequired + textLength % 4) { - dataSize = dmSizes[i].dataSize; + if (dmSizes[i].GetDataSize() >= dataRequired + textLength % 4) { + dataSize = dmSizes[i].GetDataSize(); break; } } @@ -1000,8 +1000,8 @@ private int EdifactEncodation(byte[] text, int textOffset, int textLength, byte[ if (!sizeFixed && (symbolIndex == text.Length - 1 || symbolIndex < 0)) { dataSize = int.MaxValue; for (int i = 0; i < dmSizes.Length; ++i) { - if (dmSizes[i].dataSize >= dataOffset + ptrOut + (3 - pedi / 6)) { - dataSize = dmSizes[i].dataSize; + if (dmSizes[i].GetDataSize() >= dataOffset + ptrOut + (3 - pedi / 6)) { + dataSize = dmSizes[i].GetDataSize(); break; } } @@ -1247,38 +1247,38 @@ private void Draw(byte[] data, int dataSize, DmParams dm) { int xs; int ys; int z; - int xByte = (dm.width + ws * 2 + 7) / 8; + int xByte = (dm.GetWidth() + ws * 2 + 7) / 8; JavaUtil.Fill(image, (byte)0); //alignment patterns //dotted horizontal line - for (i = ws; i < dm.height + ws; i += dm.heightSection) { - for (j = ws; j < dm.width + ws; j += 2) { + for (i = ws; i < dm.GetHeight() + ws; i += dm.GetHeightSection()) { + for (j = ws; j < dm.GetWidth() + ws; j += 2) { SetBit(j, i, xByte); } } //solid horizontal line - for (i = dm.heightSection - 1 + ws; i < dm.height + ws; i += dm.heightSection) { - for (j = ws; j < dm.width + ws; ++j) { + for (i = dm.GetHeightSection() - 1 + ws; i < dm.GetHeight() + ws; i += dm.GetHeightSection()) { + for (j = ws; j < dm.GetWidth() + ws; ++j) { SetBit(j, i, xByte); } } //solid vertical line - for (i = ws; i < dm.width + ws; i += dm.widthSection) { - for (j = ws; j < dm.height + ws; ++j) { + for (i = ws; i < dm.GetWidth() + ws; i += dm.GetWidthSection()) { + for (j = ws; j < dm.GetHeight() + ws; ++j) { SetBit(i, j, xByte); } } //dotted vertical line - for (i = dm.widthSection - 1 + ws; i < dm.width + ws; i += dm.widthSection) { - for (j = 1 + ws; j < dm.height + ws; j += 2) { + for (i = dm.GetWidthSection() - 1 + ws; i < dm.GetWidth() + ws; i += dm.GetWidthSection()) { + for (j = 1 + ws; j < dm.GetHeight() + ws; j += 2) { SetBit(i, j, xByte); } } p = 0; - for (ys = 0; ys < dm.height; ys += dm.heightSection) { - for (y = 1; y < dm.heightSection - 1; ++y) { - for (xs = 0; xs < dm.width; xs += dm.widthSection) { - for (x = 1; x < dm.widthSection - 1; ++x) { + for (ys = 0; ys < dm.GetHeight(); ys += dm.GetHeightSection()) { + for (y = 1; y < dm.GetHeightSection() - 1; ++y) { + for (xs = 0; xs < dm.GetWidth(); xs += dm.GetWidthSection()) { + for (x = 1; x < dm.GetWidthSection() - 1; ++x) { z = place[p++]; if (z == 1 || z > 1 && (data[z / 8 - 1] & 0xff & 128 >> z % 8) != 0) { SetBit(x + xs + ws, y + ys + ws, xByte); diff --git a/itext/itext.barcodes/itext/barcodes/BarcodePDF417.cs b/itext/itext.barcodes/itext/barcodes/BarcodePDF417.cs index f899bdff38..450c945d1b 100644 --- a/itext/itext.barcodes/itext/barcodes/BarcodePDF417.cs +++ b/itext/itext.barcodes/itext/barcodes/BarcodePDF417.cs @@ -1085,7 +1085,7 @@ protected internal virtual bool CheckSegmentType(BarcodePDF417.Segment segment, if (segment == null) { return false; } - return segment.type == type; + return segment.GetType() == type; } /// Calculates the length of the given segment @@ -1095,7 +1095,7 @@ protected internal virtual int GetSegmentLength(BarcodePDF417.Segment segment) { if (segment == null) { return 0; } - return segment.end - segment.start; + return segment.GetEnd() - segment.GetStart(); } /// Compacts the code words. @@ -1142,24 +1142,24 @@ protected internal virtual void Assemble() { cwPtr = 1; for (k = 0; k < segmentList.Size(); ++k) { BarcodePDF417.Segment v = segmentList.Get(k); - switch (v.type) { + switch (v.GetType()) { case 'T': { if (k != 0) { codewords[cwPtr++] = TEXT_MODE; } - TextCompaction(v.start, GetSegmentLength(v)); + TextCompaction(v.GetStart(), GetSegmentLength(v)); break; } case 'N': { codewords[cwPtr++] = NUMERIC_MODE; - NumberCompaction(v.start, GetSegmentLength(v)); + NumberCompaction(v.GetStart(), GetSegmentLength(v)); break; } case 'B': { codewords[cwPtr++] = GetSegmentLength(v) % 6 != 0 ? BYTE_MODE : BYTE_MODE_6; - ByteCompaction(v.start, GetSegmentLength(v)); + ByteCompaction(v.GetStart(), GetSegmentLength(v)); break; } } @@ -1195,13 +1195,13 @@ protected internal virtual void DumpList() { int len = GetSegmentLength(v); char[] c = new char[len]; for (int j = 0; j < len; ++j) { - c[j] = (char)(code[v.start + j] & 0xff); + c[j] = (char)(code[v.GetStart() + j] & 0xff); if (c[j] == '\r') { c[j] = '\n'; } } StringBuilder sb = new StringBuilder(); - sb.Append(v.type); + sb.Append(v.GetType()); sb.Append(c); System.Console.Out.WriteLine(sb.ToString()); } @@ -1324,7 +1324,7 @@ internal virtual void BreakString() { if (CheckSegmentType(v, 'B') && GetSegmentLength(v) == 1) { if (CheckSegmentType(vp, 'T') && CheckSegmentType(vn, 'T') && GetSegmentLength(vp) + GetSegmentLength(vn) >= 3) { - vp.end = vn.end; + vp.SetEnd(vn.GetEnd()); segmentList.Remove(k); segmentList.Remove(k); k = -1; @@ -1341,13 +1341,13 @@ internal virtual void BreakString() { bool redo = false; if (CheckSegmentType(vp, 'B') && GetSegmentLength(vp) == 1 || CheckSegmentType(vp, 'T')) { redo = true; - v.start = vp.start; + v.SetStart(vp.GetStart()); segmentList.Remove(k - 1); --k; } if (CheckSegmentType(vn, 'B') && GetSegmentLength(vn) == 1 || CheckSegmentType(vn, 'T')) { redo = true; - v.end = vn.end; + v.SetEnd(vn.GetEnd()); segmentList.Remove(k + 1); } if (redo) { @@ -1365,13 +1365,13 @@ internal virtual void BreakString() { bool redo = false; if (CheckSegmentType(vp, 'T') && GetSegmentLength(vp) < 5 || CheckSegmentType(vp, 'B')) { redo = true; - v.start = vp.start; + v.SetStart(vp.GetStart()); segmentList.Remove(k - 1); --k; } if (CheckSegmentType(vn, 'T') && GetSegmentLength(vn) < 5 || CheckSegmentType(vn, 'B')) { redo = true; - v.end = vn.end; + v.SetEnd(vn.GetEnd()); segmentList.Remove(k + 1); } if (redo) { @@ -1381,15 +1381,15 @@ internal virtual void BreakString() { } } // check if all numbers - if (segmentList.Size() == 1 && (v = segmentList.Get(0)).type == 'T' && GetSegmentLength(v) >= 8) { - for (k = v.start; k < v.end; ++k) { + if (segmentList.Size() == 1 && (v = segmentList.Get(0)).GetType() == 'T' && GetSegmentLength(v) >= 8) { + for (k = v.GetStart(); k < v.GetEnd(); ++k) { c = (char)(code[k] & 0xff); if (c < '0' || c > '9') { break; } } - if (k == v.end) { - v.type = 'N'; + if (k == v.GetEnd()) { + v.SetType('N'); } } } @@ -1655,11 +1655,11 @@ private void TextCompaction(byte[] input, int start, int length) { /// A container that encapsulates all data needed for a segment. protected internal class Segment { - public char type; + private char type; - public int start; + private int start; - public int end; + private int end; /// /// Creates a new @@ -1674,6 +1674,42 @@ public Segment(char type, int start, int end) { this.start = start; this.end = end; } + + /// Retrieves the type of the segment. + /// segment type + public virtual char GetType() { + return type; + } + + /// Sets the type of the segment. + /// segment type + public virtual void SetType(char type) { + this.type = type; + } + + /// Retrieves the start of the segment. + /// segment start + public virtual int GetStart() { + return start; + } + + /// Sets the start of the segment. + /// segment start + public virtual void SetStart(int start) { + this.start = start; + } + + /// Retrieves the end of the segment. + /// segment end + public virtual int GetEnd() { + return end; + } + + /// Sets the end of the segment. + /// segment end + public virtual void SetEnd(int end) { + this.end = end; + } } /// An utility class that encapsulates a list of segments. diff --git a/itext/itext.barcodes/itext/barcodes/BarcodePostnet.cs b/itext/itext.barcodes/itext/barcodes/BarcodePostnet.cs index c4534b6c9d..e0633cb790 100644 --- a/itext/itext.barcodes/itext/barcodes/BarcodePostnet.cs +++ b/itext/itext.barcodes/itext/barcodes/BarcodePostnet.cs @@ -37,9 +37,9 @@ namespace iText.Barcodes { /// point is added, usually being the last two digits of the address or PO box number. /// public class BarcodePostnet : Barcode1D { - public static int TYPE_POSTNET = 1; + public const int TYPE_POSTNET = 1; - public static int TYPE_PLANET = 2; + public const int TYPE_PLANET = 2; /// The bars for each character. private static readonly byte[][] BARS = new byte[][] { new byte[] { 1, 1, 0, 0, 0 }, new byte[] { 0, 0, 0, diff --git a/itext/itext.barcodes/itext/barcodes/dmcode/DmParams.cs b/itext/itext.barcodes/itext/barcodes/dmcode/DmParams.cs index d2b142b067..6b39bfb555 100644 --- a/itext/itext.barcodes/itext/barcodes/dmcode/DmParams.cs +++ b/itext/itext.barcodes/itext/barcodes/dmcode/DmParams.cs @@ -46,18 +46,60 @@ public DmParams(int height, int width, int heightSection, int widthSection, int this.errorBlock = errorBlock; } - public int height; + private readonly int height; - public int width; + private readonly int width; - public int heightSection; + private readonly int heightSection; - public int widthSection; + private readonly int widthSection; - public int dataSize; + private readonly int dataSize; - public int dataBlock; + private readonly int dataBlock; - public int errorBlock; + private readonly int errorBlock; + + /// Retrieves the height of DmParams object. + /// total height value + public virtual int GetHeight() { + return height; + } + + /// Retrieves the width of DmParams object. + /// total width value + public virtual int GetWidth() { + return width; + } + + /// Retrieves the height of a single section. + /// total height value + public virtual int GetHeightSection() { + return heightSection; + } + + /// Retrieves the width of a single section. + /// total width value + public virtual int GetWidthSection() { + return widthSection; + } + + /// Retrieves the size of the data. + /// data size value + public virtual int GetDataSize() { + return dataSize; + } + + /// Retrieves the size of the data block. + /// data block size value + public virtual int GetDataBlock() { + return dataBlock; + } + + /// Retrieves the size of the error block. + /// error block size value + public virtual int GetErrorBlock() { + return errorBlock; + } } } diff --git a/itext/itext.bouncy-castle-adapter/Properties/AssemblyInfo.cs b/itext/itext.bouncy-castle-adapter/Properties/AssemblyInfo.cs index 3c289f0969..3b31c7f707 100644 --- a/itext/itext.bouncy-castle-adapter/Properties/AssemblyInfo.cs +++ b/itext/itext.bouncy-castle-adapter/Properties/AssemblyInfo.cs @@ -15,6 +15,6 @@ [assembly: Guid("3c83a192-e64a-4134-ade9-38f65c8e9fca")] -[assembly: AssemblyVersion("8.0.5.0")] -[assembly: AssemblyFileVersion("8.0.5.0")] -[assembly: AssemblyInformationalVersion("8.0.5")] \ No newline at end of file +[assembly: AssemblyVersion("9.0.0.0")] +[assembly: AssemblyFileVersion("9.0.0.0")] +[assembly: AssemblyInformationalVersion("9.0.0")] \ No newline at end of file diff --git a/itext/itext.bouncy-castle-adapter/itext-bouncy-castle-adapter.nuspec b/itext/itext.bouncy-castle-adapter/itext-bouncy-castle-adapter.nuspec index b9f053f987..714505b3be 100644 --- a/itext/itext.bouncy-castle-adapter/itext-bouncy-castle-adapter.nuspec +++ b/itext/itext.bouncy-castle-adapter/itext-bouncy-castle-adapter.nuspec @@ -2,7 +2,7 @@ itext.bouncy-castle-adapter - 8.0.5 + 9.0.0 iText bouncy-castle adapter module Apryse Software Apryse Software @@ -18,12 +18,12 @@ itext itext7 itextsharp c# .net csharp - - + + - - + + diff --git a/itext/itext.bouncy-castle-adapter/itext.bouncy-castle-adapter.csproj b/itext/itext.bouncy-castle-adapter/itext.bouncy-castle-adapter.csproj index e1ef51af7b..19181a141e 100644 --- a/itext/itext.bouncy-castle-adapter/itext.bouncy-castle-adapter.csproj +++ b/itext/itext.bouncy-castle-adapter/itext.bouncy-castle-adapter.csproj @@ -30,6 +30,6 @@ - + \ No newline at end of file diff --git a/itext/itext.bouncy-castle-adapter/itext/bouncycastle/BouncyCastleFactory.cs b/itext/itext.bouncy-castle-adapter/itext/bouncycastle/BouncyCastleFactory.cs index d764e0c83b..ffccd18ef9 100644 --- a/itext/itext.bouncy-castle-adapter/itext/bouncycastle/BouncyCastleFactory.cs +++ b/itext/itext.bouncy-castle-adapter/itext/bouncycastle/BouncyCastleFactory.cs @@ -24,6 +24,7 @@ You should have received a copy of the GNU Affero General Public License using System.Collections; using System.Collections.Generic; using System.IO; +using System.Security.Cryptography; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.Esf; using Org.BouncyCastle.Asn1.Ess; @@ -49,6 +50,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Bouncycastle.Cms; using iText.Bouncycastle.Crypto; using iText.Bouncycastle.Crypto.Generators; +using iText.Bouncycastle.Crypto.Modes; using iText.Bouncycastle.Math; using iText.Bouncycastle.Openssl; using iText.Bouncycastle.Operator; @@ -71,6 +73,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Cms; using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Bouncycastle.Crypto.Generators; +using iText.Commons.Bouncycastle.Crypto.Modes; using iText.Commons.Bouncycastle.Math; using iText.Commons.Bouncycastle.Openssl; using iText.Commons.Bouncycastle.Operator; @@ -79,7 +82,13 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.X509; using Org.BouncyCastle.Asn1.Pkcs; using Org.BouncyCastle.Asn1.Tsp; +using Org.BouncyCastle.Crypto.Digests; +using Org.BouncyCastle.Crypto.Engines; +using Org.BouncyCastle.Crypto.Generators; +using Org.BouncyCastle.Crypto.Engines; +using Org.BouncyCastle.Crypto.Modes; using Org.BouncyCastle.Crypto.Operators; +using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.OpenSsl; using Org.BouncyCastle.Security; using Org.BouncyCastle.Security.Certificates; @@ -847,7 +856,8 @@ public virtual ITimeStampRequest CreateTimeStampRequest(byte[] bytes) { /// public ITimeStampTokenGenerator CreateTimeStampTokenGenerator(IPrivateKey pk, IX509Certificate certificate, string allowedDigest, string policyOid) { - return new TimeStampTokenGeneratorBC(pk, certificate, allowedDigest, policyOid); + String digestOid = GetDigestAlgorithmOid(allowedDigest.ToUpperInvariant()); + return new TimeStampTokenGeneratorBC(pk, certificate, digestOid, policyOid); } /// @@ -865,6 +875,11 @@ public virtual IX500Name CreateX500Name(String s) { return new X509NameBC(new X509Name(s)); } + public IX500Name CreateX500Name(IAsn1Sequence s) + { + return new X509NameBC(X509Name.GetInstance(((Asn1SequenceBC) s).GetAsn1Sequence())); + } + /// public virtual IRespID CreateRespID(IX500Name x500Name) { return new RespIDBC(x500Name); @@ -1127,6 +1142,11 @@ public bool IsNullExtension(IX509Extension ext) { public bool IsNull(IAsn1Encodable encodable) { return ((Asn1EncodableBC)encodable).GetEncodable() == null; } + + /// + public RNGCryptoServiceProvider GetSecureRandom() { + return new RNGCryptoServiceProvider(); + } /// public IX509Extension CreateExtension(bool b, IDerOctetString octetString) { @@ -1170,6 +1190,42 @@ public string CreateEndDate(IX509Certificate certificate) { return certificate.GetEndDateTime(); } + /// + public byte[] GenerateHKDF(byte[] inputKey, byte[] salt, byte[] info) { + HkdfBytesGenerator hkdfBytesGenerator = new HkdfBytesGenerator(new Sha256Digest()); + HkdfParameters hkdfParameters = new HkdfParameters(inputKey, salt, info); + hkdfBytesGenerator.Init(hkdfParameters); + byte[] hkdf = new byte[32]; + hkdfBytesGenerator.GenerateBytes(hkdf, 0, 32); + + return hkdf; + } + + /// + public byte[] GenerateHMACSHA256Token(byte[] key, byte[] data) { + HMACSHA256 mac = new HMACSHA256(key); + return mac.ComputeHash(data); + } + + /// + public byte[] GenerateEncryptedKeyWithAES256NoPad(byte[] key, byte[] kek) { + IWrapper wrapper = new AesWrapEngine(); + wrapper.Init(true, new KeyParameter(kek)); + return wrapper.Wrap(key, 0, key.Length); + } + + /// + public byte[] GenerateDecryptedKeyWithAES256NoPad(byte[] key, byte[] kek) { + IWrapper wrapper = new AesWrapEngine(); + wrapper.Init(false, new KeyParameter(kek)); + return wrapper.Unwrap(key, 0, key.Length); + } + + public IGCMBlockCipher CreateGCMBlockCipher() { + GcmBlockCipher cipher = new GcmBlockCipher(new AesEngine()); + return new GCMBlockCipherBC(cipher); + } + //\cond DO_NOT_DOCUMENT internal class BouncyCastlePasswordFinder : IPasswordFinder { private readonly char[] password; diff --git a/itext/itext.bouncy-castle-adapter/itext/bouncycastle/asn1/Asn1EncodableVectorBC.cs b/itext/itext.bouncy-castle-adapter/itext/bouncycastle/asn1/Asn1EncodableVectorBC.cs index 44507dbe6f..089dc19ef7 100644 --- a/itext/itext.bouncy-castle-adapter/itext/bouncycastle/asn1/Asn1EncodableVectorBC.cs +++ b/itext/itext.bouncy-castle-adapter/itext/bouncycastle/asn1/Asn1EncodableVectorBC.cs @@ -107,6 +107,11 @@ public virtual void AddOptional(IAlgorithmIdentifier element) { } } + /// + public virtual int Size() { + return encodableVector.Count; + } + /// Indicates whether some other object is "equal to" this one. /// Indicates whether some other object is "equal to" this one. Compares wrapped objects. public override bool Equals(Object o) { diff --git a/itext/itext.bouncy-castle-adapter/itext/bouncycastle/asn1/ocsp/BasicOcspResponseBC.cs b/itext/itext.bouncy-castle-adapter/itext/bouncycastle/asn1/ocsp/BasicOcspResponseBC.cs index 78f8c1ddf4..7edd145ca7 100644 --- a/itext/itext.bouncy-castle-adapter/itext/bouncycastle/asn1/ocsp/BasicOcspResponseBC.cs +++ b/itext/itext.bouncy-castle-adapter/itext/bouncycastle/asn1/ocsp/BasicOcspResponseBC.cs @@ -22,6 +22,7 @@ You should have received a copy of the GNU Affero General Public License */ using System; using System.Collections.Generic; +using iText.Bouncycastle.Asn1.X509; using Org.BouncyCastle.Asn1.Ocsp; using iText.Bouncycastle.Cert.Ocsp; using iText.Bouncycastle.Crypto; @@ -127,5 +128,10 @@ public IAsn1Encodable GetExtensionParsedValue(IDerObjectIdentifier objectIdentif return new Asn1EncodableBC(GetBasicOcspResponse().TbsResponseData.ResponseExtensions .GetExtensionParsedValue(((DerObjectIdentifierBC)objectIdentifier).GetDerObjectIdentifier())); } + + public IRespID GetResponderId() + { + return new RespIDBC(new X509NameBC(GetBasicOcspResponse().TbsResponseData.ResponderID.Name)); + } } } diff --git a/itext/itext.bouncy-castle-adapter/itext/bouncycastle/asn1/x509/X509NameBC.cs b/itext/itext.bouncy-castle-adapter/itext/bouncycastle/asn1/x509/X509NameBC.cs index 52bf9c4b58..14410a20e3 100644 --- a/itext/itext.bouncy-castle-adapter/itext/bouncycastle/asn1/x509/X509NameBC.cs +++ b/itext/itext.bouncy-castle-adapter/itext/bouncycastle/asn1/x509/X509NameBC.cs @@ -51,5 +51,10 @@ public X509NameBC(X509Name x500Name) public virtual X509Name GetX509Name() { return (X509Name)GetEncodable(); } + + public string GetName() + { + return GetX509Name().ToString(); + } } } diff --git a/itext/itext.bouncy-castle-adapter/itext/bouncycastle/cert/ocsp/RespIDBC.cs b/itext/itext.bouncy-castle-adapter/itext/bouncycastle/cert/ocsp/RespIDBC.cs index b21175562f..9cfc196fb2 100644 --- a/itext/itext.bouncy-castle-adapter/itext/bouncycastle/cert/ocsp/RespIDBC.cs +++ b/itext/itext.bouncy-castle-adapter/itext/bouncycastle/cert/ocsp/RespIDBC.cs @@ -69,6 +69,11 @@ public virtual RespID GetRespID() { return respID; } + /// + public virtual IResponderID ToASN1Primitive() { + return new ResponderIDBC(respID.ToAsn1Object()); + } + /// Indicates whether some other object is "equal to" this one. /// Indicates whether some other object is "equal to" this one. Compares wrapped objects. public override bool Equals(Object o) { diff --git a/itext/itext.bouncy-castle-adapter/itext/bouncycastle/cert/ocsp/ResponderIDBC.cs b/itext/itext.bouncy-castle-adapter/itext/bouncycastle/cert/ocsp/ResponderIDBC.cs new file mode 100644 index 0000000000..770b8cd9ce --- /dev/null +++ b/itext/itext.bouncy-castle-adapter/itext/bouncycastle/cert/ocsp/ResponderIDBC.cs @@ -0,0 +1,63 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using Org.BouncyCastle.Asn1.Ocsp; +using iText.Bouncycastle.Asn1.X509; +using iText.Commons.Bouncycastle.Asn1.X500; +using iText.Commons.Bouncycastle.Cert.Ocsp; + +namespace iText.Bouncycastle.Cert.Ocsp { + /// + /// Wrapper class for + /// . + /// + public class ResponderIDBC : IResponderID { + private readonly ResponderID responderID; + + /// + /// Creates new wrapper instance for + /// . + /// + /// + /// + /// + /// to be wrapped + /// + public ResponderIDBC(ResponderID responderID) { + this.responderID = responderID; + } + + /// + public virtual IX500Name GetName() { + return new X509NameBC(responderID.Name); + } + + /// Gets actual org.bouncycastle object being wrapped. + /// + /// wrapped + /// . + /// + public virtual ResponderID GetResponderID() { + return responderID; + } + } +} diff --git a/itext/itext.bouncy-castle-adapter/itext/bouncycastle/crypto/InvalidCipherTextExceptionBC.cs b/itext/itext.bouncy-castle-adapter/itext/bouncycastle/crypto/InvalidCipherTextExceptionBC.cs new file mode 100644 index 0000000000..3676a7e906 --- /dev/null +++ b/itext/itext.bouncy-castle-adapter/itext/bouncycastle/crypto/InvalidCipherTextExceptionBC.cs @@ -0,0 +1,34 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using Org.BouncyCastle.Crypto; +using iText.Commons.Bouncycastle.Crypto; + +namespace iText.Bouncycastle.Crypto { + public class InvalidCipherTextExceptionBC : AbstractInvalidCipherTextException { + private readonly InvalidCipherTextException exception; + + public InvalidCipherTextExceptionBC(InvalidCipherTextException exception) { + this.exception = exception; + } + } +} diff --git a/itext/itext.bouncy-castle-adapter/itext/bouncycastle/crypto/modes/GCMBlockCipherBC.cs b/itext/itext.bouncy-castle-adapter/itext/bouncycastle/crypto/modes/GCMBlockCipherBC.cs new file mode 100644 index 0000000000..54aab5ab0b --- /dev/null +++ b/itext/itext.bouncy-castle-adapter/itext/bouncycastle/crypto/modes/GCMBlockCipherBC.cs @@ -0,0 +1,112 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using Org.BouncyCastle.Crypto; +using Org.BouncyCastle.Crypto.Modes; +using Org.BouncyCastle.Crypto.Parameters; +using iText.Commons.Bouncycastle.Crypto.Modes; +using iText.Commons.Utils; + +namespace iText.Bouncycastle.Crypto.Modes { + /// + /// This class provides the functionality of a cryptographic cipher of aes-gcm for encryption and decryption via + /// wrapping the corresponding + /// GCMBlockCipher + /// class from bouncy-castle. + /// + public class GCMBlockCipherBC : IGCMBlockCipher { + private readonly GcmBlockCipher cipher; + + /// + /// Creates new wrapper for + /// + /// aes-gcm block cipher class. + /// + /// bouncy-castle class to wrap + public GCMBlockCipherBC(GcmBlockCipher cipher) { + this.cipher = cipher; + } + + /// Gets actual org.bouncycastle object being wrapped. + /// + /// wrapped + /// + /// + public virtual GcmBlockCipher GetCipher() { + return cipher; + } + + /// + public virtual void Init(bool forEncryption, byte[] key, int macSizeBits, byte[] iv) { + cipher.Init(forEncryption, new AeadParameters(new KeyParameter(key), macSizeBits, iv)); + } + + /// + public virtual int GetUpdateOutputSize(int len) { + return cipher.GetUpdateOutputSize(len); + } + + /// + public virtual void ProcessBytes(byte[] input, int inputOffset, int len, byte[] output, int outOffset) { + cipher.ProcessBytes(input, inputOffset, len, output, outOffset); + } + + /// + public virtual int GetOutputSize(int len) { + return cipher.GetOutputSize(len); + } + + /// + public virtual void DoFinal(byte[] plainText, int i) { + try { + cipher.DoFinal(plainText, i); + } + catch (InvalidCipherTextException e) { + throw new ArgumentException(e.Message, e); + } + } + + /// + public override bool Equals(Object o) { + if (this == o) { + return true; + } + if (o == null || GetType() != o.GetType()) { + return false; + } + iText.Bouncycastle.Crypto.Modes.GCMBlockCipherBC that = (iText.Bouncycastle.Crypto.Modes.GCMBlockCipherBC) + o; + return Object.Equals(cipher, that.cipher); + } + + /// + public override int GetHashCode() { + return JavaUtil.ArraysHashCode(cipher); + } + + /// + public override String ToString() { + return cipher.ToString(); + } + } +} diff --git a/itext/itext.bouncy-castle-connector/Properties/AssemblyInfo.cs b/itext/itext.bouncy-castle-connector/Properties/AssemblyInfo.cs index d16a59d4b4..206dea88c3 100644 --- a/itext/itext.bouncy-castle-connector/Properties/AssemblyInfo.cs +++ b/itext/itext.bouncy-castle-connector/Properties/AssemblyInfo.cs @@ -15,6 +15,6 @@ [assembly: Guid("56eaf103-2032-43eb-a7dd-fbeea5c5cb9c")] -[assembly: AssemblyVersion("8.0.5.0")] -[assembly: AssemblyFileVersion("8.0.5.0")] -[assembly: AssemblyInformationalVersion("8.0.5")] \ No newline at end of file +[assembly: AssemblyVersion("9.0.0.0")] +[assembly: AssemblyFileVersion("9.0.0.0")] +[assembly: AssemblyInformationalVersion("9.0.0")] \ No newline at end of file diff --git a/itext/itext.bouncy-castle-connector/itext.bouncy-castle-connector.csproj b/itext/itext.bouncy-castle-connector/itext.bouncy-castle-connector.csproj index 45e5f3381e..f9e7e19d4b 100644 --- a/itext/itext.bouncy-castle-connector/itext.bouncy-castle-connector.csproj +++ b/itext/itext.bouncy-castle-connector/itext.bouncy-castle-connector.csproj @@ -32,6 +32,7 @@ + \ No newline at end of file diff --git a/itext/itext.bouncy-castle-connector/itext/bouncycastleconnector/BouncyCastleDefaultFactory.cs b/itext/itext.bouncy-castle-connector/itext/bouncycastleconnector/BouncyCastleDefaultFactory.cs index 0496ff7230..5951924310 100644 --- a/itext/itext.bouncy-castle-connector/itext/bouncycastleconnector/BouncyCastleDefaultFactory.cs +++ b/itext/itext.bouncy-castle-connector/itext/bouncycastleconnector/BouncyCastleDefaultFactory.cs @@ -24,6 +24,7 @@ You should have received a copy of the GNU Affero General Public License using System.Collections; using System.Collections.Generic; using System.IO; +using System.Security.Cryptography; using iText.Bouncycastleconnector.Logs; using iText.Commons.Bouncycastle; using iText.Commons.Bouncycastle.Asn1; @@ -41,6 +42,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Cms; using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Bouncycastle.Crypto.Generators; +using iText.Commons.Bouncycastle.Crypto.Modes; using iText.Commons.Bouncycastle.Math; using iText.Commons.Bouncycastle.Openssl; using iText.Commons.Bouncycastle.Operator; @@ -520,6 +522,11 @@ public IX500Name CreateX500Name(string s) { throw new NotSupportedException(BouncyCastleLogMessageConstant.BOUNCY_CASTLE_DEPENDENCY_MUST_PRESENT); } + public IX500Name CreateX500Name(IAsn1Sequence s) + { + throw new NotSupportedException(BouncyCastleLogMessageConstant.BOUNCY_CASTLE_DEPENDENCY_MUST_PRESENT); + } + public IRespID CreateRespID(IX500Name x500Name) { throw new NotSupportedException(BouncyCastleLogMessageConstant.BOUNCY_CASTLE_DEPENDENCY_MUST_PRESENT); } @@ -702,6 +709,10 @@ public bool IsNull(IAsn1Encodable encodable) { throw new NotSupportedException(BouncyCastleLogMessageConstant.BOUNCY_CASTLE_DEPENDENCY_MUST_PRESENT); } + public RNGCryptoServiceProvider GetSecureRandom() { + throw new NotSupportedException(BouncyCastleLogMessageConstant.BOUNCY_CASTLE_DEPENDENCY_MUST_PRESENT); + } + public byte[] CreateCipherBytes(IX509Certificate x509Certificate, byte[] abyte0, IAlgorithmIdentifier algorithmidentifier) { throw new NotSupportedException(BouncyCastleLogMessageConstant.BOUNCY_CASTLE_DEPENDENCY_MUST_PRESENT); } @@ -721,5 +732,25 @@ public IBouncyCastleUtil GetBouncyCastleUtil() { public string CreateEndDate(IX509Certificate certificate) { throw new NotSupportedException(BouncyCastleLogMessageConstant.BOUNCY_CASTLE_DEPENDENCY_MUST_PRESENT); } + + public byte[] GenerateHKDF(byte[] inputKey, byte[] salt, byte[] info) { + throw new NotSupportedException(BouncyCastleLogMessageConstant.BOUNCY_CASTLE_DEPENDENCY_MUST_PRESENT); + } + + public byte[] GenerateHMACSHA256Token(byte[] key, byte[] data) { + throw new NotSupportedException(BouncyCastleLogMessageConstant.BOUNCY_CASTLE_DEPENDENCY_MUST_PRESENT); + } + + public byte[] GenerateEncryptedKeyWithAES256NoPad(byte[] key, byte[] kek) { + throw new NotSupportedException(BouncyCastleLogMessageConstant.BOUNCY_CASTLE_DEPENDENCY_MUST_PRESENT); + } + + public byte[] GenerateDecryptedKeyWithAES256NoPad(byte[] key, byte[] kek) { + throw new NotSupportedException(BouncyCastleLogMessageConstant.BOUNCY_CASTLE_DEPENDENCY_MUST_PRESENT); + } + + public IGCMBlockCipher CreateGCMBlockCipher() { + throw new NotSupportedException(BouncyCastleLogMessageConstant.BOUNCY_CASTLE_DEPENDENCY_MUST_PRESENT); + } } } diff --git a/itext/itext.bouncy-castle-connector/itext/bouncycastleconnector/BouncyCastleFactoryCreator.cs b/itext/itext.bouncy-castle-connector/itext/bouncycastleconnector/BouncyCastleFactoryCreator.cs index 674ad6ceae..44716a5d0e 100644 --- a/itext/itext.bouncy-castle-connector/itext/bouncycastleconnector/BouncyCastleFactoryCreator.cs +++ b/itext/itext.bouncy-castle-connector/itext/bouncycastleconnector/BouncyCastleFactoryCreator.cs @@ -48,8 +48,8 @@ namespace iText.Bouncycastleconnector { public sealed class BouncyCastleFactoryCreator { private static IBouncyCastleFactory factory; - private static IDictionary> factories = new LinkedDictionary>(); + private static readonly IDictionary> FACTORIES = new LinkedDictionary>(); private const String FACTORY_ENVIRONMENT_VARIABLE_NAME = "ITEXT_BOUNCY_CASTLE_FACTORY_NAME"; @@ -59,11 +59,11 @@ public sealed class BouncyCastleFactoryCreator { static BouncyCastleFactoryCreator() { PopulateFactoriesMap(); String factoryName = SystemUtil.GetEnvironmentVariable(FACTORY_ENVIRONMENT_VARIABLE_NAME); - Func systemVariableFactoryCreator = factories.Get(factoryName); + Func systemVariableFactoryCreator = FACTORIES.Get(factoryName); if (systemVariableFactoryCreator != null) { TryCreateFactory(systemVariableFactoryCreator); } - foreach (Func factorySupplier in factories.Values) { + foreach (Func factorySupplier in FACTORIES.Values) { if (factory != null) { break; } @@ -121,8 +121,8 @@ private static void CreateFactory(Func factoryCreator) { } private static void PopulateFactoriesMap() { - factories.Put("bouncy-castle", () => new BouncyCastleFactory()); - factories.Put("bouncy-castle-fips", () => new BouncyCastleFipsFactory()); + FACTORIES.Put("bouncy-castle", () => new BouncyCastleFactory()); + FACTORIES.Put("bouncy-castle-fips", () => new BouncyCastleFipsFactory()); } // Android-Conversion-Skip-Line (BC FIPS isn't supported on Android) } diff --git a/itext/itext.bouncy-castle-fips-adapter/Properties/AssemblyInfo.cs b/itext/itext.bouncy-castle-fips-adapter/Properties/AssemblyInfo.cs index c0aac4fc15..2e933eca08 100644 --- a/itext/itext.bouncy-castle-fips-adapter/Properties/AssemblyInfo.cs +++ b/itext/itext.bouncy-castle-fips-adapter/Properties/AssemblyInfo.cs @@ -15,6 +15,6 @@ [assembly: Guid("4e9a859e-f268-49cc-ac3c-c5b9632b3290")] -[assembly: AssemblyVersion("8.0.5.0")] -[assembly: AssemblyFileVersion("8.0.5.0")] -[assembly: AssemblyInformationalVersion("8.0.5")] \ No newline at end of file +[assembly: AssemblyVersion("9.0.0.0")] +[assembly: AssemblyFileVersion("9.0.0.0")] +[assembly: AssemblyInformationalVersion("9.0.0")] \ No newline at end of file diff --git a/itext/itext.bouncy-castle-fips-adapter/itext-bouncy-castle-fips-adapter.nuspec b/itext/itext.bouncy-castle-fips-adapter/itext-bouncy-castle-fips-adapter.nuspec index 0e960c3439..5ff7345495 100644 --- a/itext/itext.bouncy-castle-fips-adapter/itext-bouncy-castle-fips-adapter.nuspec +++ b/itext/itext.bouncy-castle-fips-adapter/itext-bouncy-castle-fips-adapter.nuspec @@ -2,7 +2,7 @@ itext.bouncy-castle-fips-adapter - 8.0.5 + 9.0.0 iText bouncy-castle FIPS adapter module Apryse Software Apryse Software @@ -18,7 +18,7 @@ itext itext7 itextsharp c# .net csharp - + diff --git a/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/BouncyCastleFipsFactory.cs b/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/BouncyCastleFipsFactory.cs index dcd6dae0ea..aa7018c4e2 100644 --- a/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/BouncyCastleFipsFactory.cs +++ b/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/BouncyCastleFipsFactory.cs @@ -24,6 +24,7 @@ You should have received a copy of the GNU Affero General Public License using System.Collections; using System.Collections.Generic; using System.IO; +using System.Security.Cryptography; using iText.Bouncycastle.Security; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.Esf; @@ -47,6 +48,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Bouncycastlefips.Cms; using iText.Bouncycastlefips.Crypto; using iText.Bouncycastlefips.Crypto.Generators; +using iText.Bouncycastlefips.Crypto.Modes; using iText.Bouncycastlefips.Math; using iText.Bouncycastlefips.Openssl; using iText.Bouncycastlefips.Operator; @@ -69,6 +71,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Cms; using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Bouncycastle.Crypto.Generators; +using iText.Commons.Bouncycastle.Crypto.Modes; using iText.Commons.Bouncycastle.Math; using iText.Commons.Bouncycastle.Openssl; using iText.Commons.Bouncycastle.Operator; @@ -874,6 +877,11 @@ public virtual IX500Name CreateX500Name(String s) { return new X500NameBCFips(new X500Name(s)); } + public IX500Name CreateX500Name(IAsn1Sequence s) + { + return new X500NameBCFips(X500Name.GetInstance(((Asn1SequenceBCFips) s).GetAsn1Sequence())); + } + /// public virtual IRespID CreateRespID(IX500Name x500Name) { return new RespIDBCFips(x500Name); @@ -1187,6 +1195,11 @@ public bool IsNullExtension(IX509Extension ext) { public bool IsNull(IAsn1Encodable encodable) { return ((Asn1EncodableBCFips)encodable).GetEncodable() == null; } + + /// + public RNGCryptoServiceProvider GetSecureRandom() { + return new RNGCryptoServiceProvider(); + } /// public IX509Extension CreateExtension(bool b, IDerOctetString octetString) { @@ -1216,17 +1229,6 @@ public void IsEncryptionFeatureSupported(int encryptionType, bool withCertificat } } - /// - public SecureRandom GetSecureRandom() { - byte[] personalizationString = Strings.ToUtf8ByteArray("some personalization string"); - SecureRandom entropySource = new SecureRandom(); - return CryptoServicesRegistrar.CreateService(FipsDrbg.Sha512) - .FromEntropySource(entropySource,true) - .SetPersonalizationString(personalizationString).Build( - entropySource.GenerateSeed(256 / (2 * 8)), true, - Strings.ToByteArray("number only used once")); - } - /// public IBouncyCastleUtil GetBouncyCastleUtil() { return BOUNCY_CASTLE_UTIL; @@ -1236,6 +1238,39 @@ public IBouncyCastleUtil GetBouncyCastleUtil() { public string CreateEndDate(IX509Certificate certificate) { return certificate.GetEndDateTime(); } + + /// + public byte[] GenerateHKDF(byte[] inputKey, byte[] salt, byte[] info) { + FipsKdf.HKdfKey key = FipsKdf.HKdfKeyBldr.WithSalt(salt).WithPrf(FipsPrfAlgorithm.Sha256HMac).Build(inputKey).WithIV(info); + IKdfCalculator service = CryptoServicesRegistrar.CreateService(key); + return service.GetResult(inputKey.Length).Collect(); + } + + /// + public byte[] GenerateHMACSHA256Token(byte[] key, byte[] data) { + HMACSHA256 mac = new HMACSHA256(key); + return mac.ComputeHash(data); + } + + /// + public byte[] GenerateEncryptedKeyWithAES256NoPad(byte[] key, byte[] kek) { + FipsAes.Key aesKey = new FipsAes.Key(kek); + IBlockCipherService provider = CryptoServicesRegistrar.CreateService((ICryptoServiceType) aesKey); + IKeyWrapper keyWrapper = provider.CreateKeyWrapper(FipsAes.KW); + return keyWrapper.Wrap(key).Collect(); + } + + /// + public byte[] GenerateDecryptedKeyWithAES256NoPad(byte[] key, byte[] kek) { + FipsAes.Key aesKey = new FipsAes.Key(kek); + IBlockCipherService provider = CryptoServicesRegistrar.CreateService((ICryptoServiceType) aesKey); + IKeyUnwrapper keyWrapper = provider.CreateKeyUnwrapper(FipsAes.KW); + return keyWrapper.Unwrap(key, 0, key.Length).Collect(); + } + + public IGCMBlockCipher CreateGCMBlockCipher() { + return new GCMBlockCipherBCFips(); + } private IX509Certificate ReadPemCertificate(PushbackStream pushbackStream) { using (TextReader file = new StreamReader(pushbackStream)) { diff --git a/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/BouncyCastleFipsUtil.cs b/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/BouncyCastleFipsUtil.cs index 5703c6784f..e6b3ecda15 100644 --- a/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/BouncyCastleFipsUtil.cs +++ b/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/BouncyCastleFipsUtil.cs @@ -20,7 +20,7 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ -using System.Collections.Generic; +using System.Collections.Generic; using System.IO; using iText.Bouncycastlefips.Cert; using iText.Commons.Bouncycastle; diff --git a/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/UnsupportedEncryptionFeatureException.cs b/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/UnsupportedEncryptionFeatureException.cs index 3403efd532..75e5a57720 100644 --- a/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/UnsupportedEncryptionFeatureException.cs +++ b/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/UnsupportedEncryptionFeatureException.cs @@ -20,18 +20,16 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ -using System; +using System; using iText.Commons.Exceptions; namespace iText.Bouncycastlefips { - public class UnsupportedEncryptionFeatureException : ITextException - { + public class UnsupportedEncryptionFeatureException : ITextException { public const String ENCRYPTION_WITH_CERTIFICATE_ISNT_SUPPORTED_IN_FIPS = "Encryption with certificated is currently not supported in Bouncy Castle FIPS mode."; - public UnsupportedEncryptionFeatureException(string msg): base(msg) - { + public UnsupportedEncryptionFeatureException(string msg): base(msg) { } } } diff --git a/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/asn1/Asn1EncodableVectorBCFips.cs b/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/asn1/Asn1EncodableVectorBCFips.cs index 16eda0990d..7199072a6c 100644 --- a/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/asn1/Asn1EncodableVectorBCFips.cs +++ b/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/asn1/Asn1EncodableVectorBCFips.cs @@ -107,6 +107,11 @@ public virtual void AddOptional(IAlgorithmIdentifier element) { } } + /// + public virtual int Size() { + return encodableVector.Count; + } + /// Indicates whether some other object is "equal to" this one. /// Indicates whether some other object is "equal to" this one. Compares wrapped objects. public override bool Equals(Object o) { diff --git a/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/asn1/ocsp/BasicOcspResponseBCFips.cs b/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/asn1/ocsp/BasicOcspResponseBCFips.cs index d66cb978fb..c462dbac3c 100644 --- a/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/asn1/ocsp/BasicOcspResponseBCFips.cs +++ b/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/asn1/ocsp/BasicOcspResponseBCFips.cs @@ -129,5 +129,10 @@ public IAsn1Encodable GetExtensionParsedValue(IDerObjectIdentifier objectIdentif return new Asn1EncodableBCFips(GetBasicOcspResponse().TbsResponseData.ResponseExtensions.GetExtension( ((DerObjectIdentifierBCFips)objectIdentifier).GetDerObjectIdentifier())?.GetParsedValue()); } + + public IRespID GetResponderId() + { + return new RespIDBCFips(GetBasicOcspResponse().TbsResponseData.ResponderID); + } } } diff --git a/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/asn1/x500/X500NameBCFips.cs b/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/asn1/x500/X500NameBCFips.cs index f7c1e96604..f68380a71a 100644 --- a/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/asn1/x500/X500NameBCFips.cs +++ b/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/asn1/x500/X500NameBCFips.cs @@ -51,5 +51,10 @@ public X500NameBCFips(X500Name x500Name) public virtual X500Name GetX500Name() { return (X500Name)GetEncodable(); } + + public string GetName() + { + return GetX500Name().ToString(); + } } } diff --git a/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/cert/ocsp/RespIDBCFips.cs b/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/cert/ocsp/RespIDBCFips.cs index 2a17c0e146..fcc64f6999 100644 --- a/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/cert/ocsp/RespIDBCFips.cs +++ b/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/cert/ocsp/RespIDBCFips.cs @@ -95,5 +95,10 @@ public override int GetHashCode() { public override String ToString() { return respID.ToString(); } + + public IResponderID ToASN1Primitive() + { + return new ResponderIDBCFips(respID); + } } } diff --git a/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/cert/ocsp/ResponderIDBCFips.cs b/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/cert/ocsp/ResponderIDBCFips.cs new file mode 100644 index 0000000000..75b6bd9e6d --- /dev/null +++ b/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/cert/ocsp/ResponderIDBCFips.cs @@ -0,0 +1,63 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using Org.BouncyCastle.Asn1.Ocsp; +using iText.Bouncycastlefips.Asn1.X500; +using iText.Commons.Bouncycastle.Asn1.X500; +using iText.Commons.Bouncycastle.Cert.Ocsp; + +namespace iText.Bouncycastlefips.Cert.Ocsp { + /// + /// Wrapper class for + /// . + /// + public class ResponderIDBCFips : IResponderID { + private readonly ResponderID responderID; + + /// + /// Creates new wrapper instance for + /// . + /// + /// + /// + /// + /// to be wrapped + /// + public ResponderIDBCFips(ResponderID responderID) { + this.responderID = responderID; + } + + /// + public virtual IX500Name GetName() { + return new X500NameBCFips(responderID.Name); + } + + /// Gets actual org.bouncycastle object being wrapped. + /// + /// wrapped + /// . + /// + public virtual ResponderID GetResponderID() { + return responderID; + } + } +} diff --git a/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/crypto/CipherCBCnoPadBCFips.cs b/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/crypto/CipherCBCnoPadBCFips.cs index 0584ce416a..18affc5ff3 100644 --- a/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/crypto/CipherCBCnoPadBCFips.cs +++ b/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/crypto/CipherCBCnoPadBCFips.cs @@ -21,6 +21,7 @@ You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ using System; +using System.IO; using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Utils; using Org.BouncyCastle.Crypto; @@ -63,14 +64,15 @@ public class CipherCBCnoPadBCFips : ICipherCBCnoPad { /// public CipherCBCnoPadBCFips(bool forEncryption, byte[] key, byte[] initVector) { FipsAes.Key aesKey = new FipsAes.Key(key); - IBlockCipherService provider = CryptoServicesRegistrar.CreateService(aesKey); + IBlockCipherService provider = CryptoServicesRegistrar.CreateService( + (ICryptoServiceType) aesKey); IBlockCipherBuilder> cipherBuilder = null; if (forEncryption) { - cipherBuilder = provider.CreateBlockEncryptorBuilder(FipsAes.Cbc.WithIV(initVector)); + cipherBuilder = provider.CreateBlockEncryptorBuilder(FipsAes.Cbc.WithIV(initVector)); } else { - cipherBuilder = provider.CreateBlockDecryptorBuilder(FipsAes.Cbc.WithIV(initVector)); + cipherBuilder = provider.CreateBlockDecryptorBuilder(FipsAes.Cbc.WithIV(initVector)); } blockCipher = cipherBuilder.BuildBlockCipher(memoryStream); @@ -81,14 +83,14 @@ public virtual byte[] ProcessBlock(byte[] inp, int inpOff, int inpLen) { if (inpLen % blockCipher.BlockSize != 0) { throw new ArgumentException("Not multiple of block: " + inpLen); } - try { - blockCipher.Stream.Write(inp, inpOff, inpLen); - blockCipher.Stream.Flush(); - return memoryStream.ToArray(); + if (memoryStream.Length != 0) { + throw new ArgumentException("Cipher memory stream is not empty!"); } - finally { - memoryStream.SetLength(0); + + using (Stream stream = blockCipher.Stream) { + stream.Write(inp, inpOff, inpLen); } + return memoryStream.ToArray(); } /// Indicates whether some other object is "equal to" this one. Compares wrapped objects. diff --git a/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/crypto/SignerBCFips.cs b/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/crypto/SignerBCFips.cs index d86eed0e91..d76212e60b 100644 --- a/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/crypto/SignerBCFips.cs +++ b/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/crypto/SignerBCFips.cs @@ -37,6 +37,8 @@ public class SignerBCFips : ISigner { private string lastHashAlgorithm; private string lastEncryptionAlgorithm; + private string digestAlgoName; + private int saltLen; private IStreamCalculator digest; @@ -71,8 +73,8 @@ public void InitSign(IPrivateKey key) { /// public void InitRsaPssSigner(string digestAlgoName, int saltLen, int trailerField) { - // Not supported yet - // Leave empty, we will throw in another place + this.digestAlgoName = digestAlgoName; + this.saltLen = saltLen; } /// @@ -159,8 +161,16 @@ private void InitSign(IPrivateKey key, string hashAlgorithm, string encrAlgorith private void InitSignature(IAsymmetricKey key, string hashAlgorithm, string encAlgorithm) { ISignatureFactoryService signatureFactoryProvider = CryptoServicesRegistrar.CreateService((ICryptoServiceType)key, new SecureRandom()); - FipsShs.Parameters parameters = DigestBCFips.GetMessageDigestParams(hashAlgorithm); + FipsShs.Parameters parameters = digestAlgoName == null + ? DigestBCFips.GetMessageDigestParams(hashAlgorithm) + : DigestBCFips.GetMessageDigestParams(digestAlgoName); switch (encAlgorithm) { + case "RSASSA-PSS": { + ISignatureFactory rsaSig = signatureFactoryProvider.CreateSignatureFactory( + FipsRsa.Pss.WithDigest(parameters).WithSaltLength(saltLen)); + digest = rsaSig.CreateCalculator(); + break; + } case "RSA": { ISignatureFactory rsaSig = signatureFactoryProvider.CreateSignatureFactory( @@ -188,9 +198,17 @@ private void InitSignature(IAsymmetricKey key, string hashAlgorithm, string encA private void InitVerifySignature(IAsymmetricKey key, String hashAlgorithm, String encrAlgorithm) { IVerifierFactoryService verifierFactoryProvider = CryptoServicesRegistrar.CreateService((ICryptoServiceType)key); - FipsShs.Parameters parameters = DigestBCFips.GetMessageDigestParams(hashAlgorithm); + FipsShs.Parameters parameters = digestAlgoName == null + ? DigestBCFips.GetMessageDigestParams(hashAlgorithm) + : DigestBCFips.GetMessageDigestParams(digestAlgoName); switch (encrAlgorithm) { + case "RSASSA-PSS": { + IVerifierFactory rsaSig = + verifierFactoryProvider.CreateVerifierFactory(FipsRsa.Pss.WithDigest(parameters).WithSaltLength(saltLen)); + iSigner = rsaSig.CreateCalculator(); + break; + } case "RSA": { IVerifierFactory rsaSig = verifierFactoryProvider.CreateVerifierFactory(FipsRsa.Pkcs1v15.WithDigest(parameters)); diff --git a/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/crypto/generators/RsaKeyPairGeneratorBCFips.cs b/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/crypto/generators/RsaKeyPairGeneratorBCFips.cs index fe98135985..e7588debc0 100644 --- a/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/crypto/generators/RsaKeyPairGeneratorBCFips.cs +++ b/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/crypto/generators/RsaKeyPairGeneratorBCFips.cs @@ -27,6 +27,8 @@ You should have received a copy of the GNU Affero General Public License using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Fips; using Org.BouncyCastle.Math; +using Org.BouncyCastle.Security; +using Org.BouncyCastle.Utilities; namespace iText.Bouncycastlefips.Crypto.Generators { /// @@ -40,9 +42,16 @@ public class RsaKeyPairGeneratorBCFips : IRsaKeyPairGenerator { /// . /// public RsaKeyPairGeneratorBCFips() { + byte[] personalizationString = Strings.ToUtf8ByteArray("some personalization string"); + SecureRandom entropySource = new SecureRandom(); + SecureRandom secureRandomForGenerator = CryptoServicesRegistrar.CreateService(FipsDrbg.Sha512) + .FromEntropySource(entropySource,true) + .SetPersonalizationString(personalizationString).Build( + entropySource.GenerateSeed(256 / (2 * 8)), true, + Strings.ToByteArray("number only used once")); this.generator = CryptoServicesRegistrar.CreateGenerator( new FipsRsa.KeyGenerationParameters(BigInteger.ValueOf(0x10001), 2048), - new BouncyCastleFipsFactory().GetSecureRandom()); + secureRandomForGenerator); } /// diff --git a/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/crypto/modes/GCMBlockCipherBCFips.cs b/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/crypto/modes/GCMBlockCipherBCFips.cs new file mode 100644 index 0000000000..d0849ebc40 --- /dev/null +++ b/itext/itext.bouncy-castle-fips-adapter/itext/bouncycastlefips/crypto/modes/GCMBlockCipherBCFips.cs @@ -0,0 +1,125 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using System.IO; +using iText.Commons.Bouncycastle.Crypto.Modes; +using iText.Commons.Utils; +using Org.BouncyCastle.Crypto; +using Org.BouncyCastle.Crypto.Fips; +using Org.BouncyCastle.Utilities.IO; + +namespace iText.Bouncycastlefips.Crypto.Modes { + /// + /// Wrapper class for IAeadCipher. + /// + public class GCMBlockCipherBCFips : IGCMBlockCipher { + private IAeadCipher cipher; + private MemoryOutputStream memoryStream = new MemoryOutputStream(); + private long lastPos = 0; + + /// + /// Creates new wrapper instance for + /// . + /// + public GCMBlockCipherBCFips() { + } + + /// Gets actual org.bouncycastle object being wrapped. + /// Wrapped IAeadCipher. + public virtual IAeadCipher GetCipher() { + return cipher; + } + + /// + public virtual void Init(bool forEncryption, byte[] key, int macSizeBits, byte[] iv) { + FipsAes.Key aesKey = new FipsAes.Key(key); + IAeadCipherService provider = CryptoServicesRegistrar.CreateService(aesKey); + + IAeadCipherBuilder> aeadEncryptorBldr = forEncryption ? + provider.CreateAeadEncryptorBuilder(FipsAes.Gcm.WithIV(iv).WithMacSize(macSizeBits)) : + provider.CreateAeadDecryptorBuilder(FipsAes.Gcm.WithIV(iv).WithMacSize(macSizeBits)); + + cipher = (IAeadCipher)aeadEncryptorBldr.BuildCipher(memoryStream); + } + + /// + public virtual int GetUpdateOutputSize(int len) { + return cipher.GetUpdateOutputSize(len); + } + + /// + public virtual void ProcessBytes(byte[] inputBuff, int inOff, int len, byte[] outBuff, int outOff) { + cipher.Stream.Write(inputBuff, inOff, len); + byte[] output = GetBytes(); + Array.Copy(output, 0, outBuff, outOff, output.Length); + } + + /// + public virtual int GetOutputSize(int i) { + return cipher.GetMaxOutputSize(i); + } + + /// + public virtual void DoFinal(byte[] plainText, int i) { + cipher.Stream.Close(); + byte[] encMac = GetBytes(); + Array.Copy(encMac, 0, plainText, i, encMac.Length); + } + + /// Indicates whether some other object is "equal to" this one. Compares wrapped objects. + public override bool Equals(Object o) { + if (this == o) { + return true; + } + if (o == null || GetType() != o.GetType()) { + return false; + } + iText.Bouncycastlefips.Crypto.Modes.GCMBlockCipherBCFips that = (iText.Bouncycastlefips.Crypto.Modes.GCMBlockCipherBCFips + )o; + return Object.Equals(cipher, that.cipher); + } + + /// Returns a hash code value based on the wrapped object. + public override int GetHashCode() { + return JavaUtil.ArraysHashCode(cipher); + } + + /// + /// Delegates + /// toString + /// method call to the wrapped object. + /// + public override String ToString() { + return cipher.ToString(); + } + + private byte[] GetBytes() { + byte[] bytes = memoryStream.ToArray(); + long len = bytes.Length - lastPos; + byte[] res = new byte[len]; + Array.Copy(bytes, lastPos, res, 0, len); + lastPos = bytes.Length; + return res; + } + } +} diff --git a/itext/itext.commons/Properties/AssemblyInfo.cs b/itext/itext.commons/Properties/AssemblyInfo.cs index f88162cb7f..5b8327f135 100644 --- a/itext/itext.commons/Properties/AssemblyInfo.cs +++ b/itext/itext.commons/Properties/AssemblyInfo.cs @@ -39,6 +39,6 @@ [assembly: Guid("339569d2-3ba2-41cc-972c-70b05e4c4fcd")] -[assembly: AssemblyVersion("8.0.5.0")] -[assembly: AssemblyFileVersion("8.0.5.0")] -[assembly: AssemblyInformationalVersion("8.0.5")] +[assembly: AssemblyVersion("9.0.0.0")] +[assembly: AssemblyFileVersion("9.0.0.0")] +[assembly: AssemblyInformationalVersion("9.0.0")] diff --git a/itext/itext.commons/itext-commons.nuspec b/itext/itext.commons/itext-commons.nuspec index a7a69eaf43..32855fa07f 100644 --- a/itext/itext.commons/itext-commons.nuspec +++ b/itext/itext.commons/itext-commons.nuspec @@ -2,7 +2,7 @@ itext.commons - 8.0.5 + 9.0.0 iText commons module Apryse Software Apryse Software @@ -19,10 +19,12 @@ + + diff --git a/itext/itext.commons/itext.commons.csproj b/itext/itext.commons/itext.commons.csproj index 8665daf8fa..a3c6d33b3a 100644 --- a/itext/itext.commons/itext.commons.csproj +++ b/itext/itext.commons/itext.commons.csproj @@ -31,6 +31,7 @@ + diff --git a/itext/itext.commons/itext/commons/actions/EventManager.cs b/itext/itext.commons/itext/commons/actions/EventManager.cs index 2cd292e245..c5af788e8a 100644 --- a/itext/itext.commons/itext/commons/actions/EventManager.cs +++ b/itext/itext.commons/itext/commons/actions/EventManager.cs @@ -43,7 +43,7 @@ private EventManager() { handlers.Add(ProductEventHandler.INSTANCE); } - /// Allows an access to the instance of EventManager. + /// Allows access to the instance of EventManager. /// the instance of the class public static iText.Commons.Actions.EventManager GetInstance() { return INSTANCE; diff --git a/itext/itext.commons/itext/commons/actions/data/CommonsProductData.cs b/itext/itext.commons/itext/commons/actions/data/CommonsProductData.cs index fdd9566757..601dd0a1a5 100644 --- a/itext/itext.commons/itext/commons/actions/data/CommonsProductData.cs +++ b/itext/itext.commons/itext/commons/actions/data/CommonsProductData.cs @@ -38,7 +38,7 @@ public sealed class CommonsProductData { //\endcond //\cond DO_NOT_DOCUMENT - internal const String COMMONS_VERSION = "8.0.5"; + internal const String COMMONS_VERSION = "9.0.0"; //\endcond //\cond DO_NOT_DOCUMENT diff --git a/itext/itext.commons/itext/commons/bouncycastle/IBouncyCastleFactory.cs b/itext/itext.commons/itext/commons/bouncycastle/IBouncyCastleFactory.cs index b150fc90b3..5eac94997c 100644 --- a/itext/itext.commons/itext/commons/bouncycastle/IBouncyCastleFactory.cs +++ b/itext/itext.commons/itext/commons/bouncycastle/IBouncyCastleFactory.cs @@ -24,6 +24,7 @@ You should have received a copy of the GNU Affero General Public License using System.Collections; using System.Collections.Generic; using System.IO; +using System.Security.Cryptography; using iText.Commons.Bouncycastle.Asn1; using iText.Commons.Bouncycastle.Asn1.Cms; using iText.Commons.Bouncycastle.Asn1.Esf; @@ -39,6 +40,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Cms; using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Bouncycastle.Crypto.Generators; +using iText.Commons.Bouncycastle.Crypto.Modes; using iText.Commons.Bouncycastle.Math; using iText.Commons.Bouncycastle.Openssl; using iText.Commons.Bouncycastle.Operator; @@ -1052,6 +1054,19 @@ ITimeStampTokenGenerator CreateTimeStampTokenGenerator(IPrivateKey pk, IX509Cert /// /// created X500 Name wrapper IX500Name CreateX500Name(String s); + + + /// + /// Create X500 Name wrapper from + /// . + /// + /// + /// + /// + /// to create X500 Name wrapper from + /// + /// created X500 Name wrapper + IX500Name CreateX500Name(IAsn1Sequence s); /// Create resp ID wrapper from X500 Name wrapper. /// X500 Name wrapper to create resp ID wrapper from @@ -1580,7 +1595,18 @@ IX509V3CertificateGenerator CreateJcaX509v3CertificateBuilder(IX509Certificate s /// bool IsNullExtension(IX509Extension extNonce); + /// + /// Check if provided encodable wrapper wraps null. + /// + /// encodable wrapper to be checked + /// true if provided encodable wrapper wraps null, false otherwise bool IsNull(IAsn1Encodable encodable); + + /// + /// Get SecureRandom implementation from the factory. + /// + /// SecureRandom implementation + RNGCryptoServiceProvider GetSecureRandom(); /// /// Create @@ -1635,5 +1661,40 @@ IX509V3CertificateGenerator CreateJcaX509v3CertificateBuilder(IX509Certificate s /// certificate to get end date /// The end date of the certificate string CreateEndDate(IX509Certificate certificate); + + /// + /// Generates byte array based on extract-and-expand key derivation function, using provided parameters. + /// + /// byte[] input key material + /// byte[] salt + /// byte[] info + /// byte[] key derivation function result. + byte[] GenerateHKDF(byte[] inputKey, byte[] salt, byte[] info); + + /// + /// Generates byte array based MAC token according to HMACSHA256 algorithm. + /// + /// MAC key + /// data to be encrypted + /// byte array based MAC token. + byte[] GenerateHMACSHA256Token(byte[] key, byte[] data); + + /// + /// Generates encrypted key based on AES256 without padding wrapping algorithm. + /// + /// key to be encrypted + /// key encryption key to be used + /// encrypted key. + byte[] GenerateEncryptedKeyWithAES256NoPad(byte[] key, byte[] kek); + + /// + /// Generates decrypted key based on AES256 without padding unwrapping algorithm. + /// + /// key to be decrypted + /// key encryption key to be used + /// decrypted key. + byte[] GenerateDecryptedKeyWithAES256NoPad(byte[] key, byte[] kek); + + IGCMBlockCipher CreateGCMBlockCipher(); } } diff --git a/itext/itext.commons/itext/commons/bouncycastle/IBouncyCastleUtil.cs b/itext/itext.commons/itext/commons/bouncycastle/IBouncyCastleUtil.cs index 5d02c283dd..9de39f85e6 100644 --- a/itext/itext.commons/itext/commons/bouncycastle/IBouncyCastleUtil.cs +++ b/itext/itext.commons/itext/commons/bouncycastle/IBouncyCastleUtil.cs @@ -20,7 +20,7 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ -using System.Collections.Generic; +using System.Collections.Generic; using System.IO; using iText.Commons.Bouncycastle.Cert; diff --git a/itext/itext.commons/itext/commons/bouncycastle/asn1/IAsn1EncodableVector.cs b/itext/itext.commons/itext/commons/bouncycastle/asn1/IAsn1EncodableVector.cs index 4e262a4fc5..401bcfe650 100644 --- a/itext/itext.commons/itext/commons/bouncycastle/asn1/IAsn1EncodableVector.cs +++ b/itext/itext.commons/itext/commons/bouncycastle/asn1/IAsn1EncodableVector.cs @@ -76,5 +76,17 @@ public interface IAsn1EncodableVector { /// /// AlgorithmIdentifier wrapper. void AddOptional(IAlgorithmIdentifier element); + + /// + /// Calls actual + /// size + /// method for the wrapped ASN1EncodableVector object. + /// + /// + /// + /// int + /// representing current vector size + /// + int Size(); } } diff --git a/itext/itext.commons/itext/commons/bouncycastle/asn1/ocsp/IBasicOcspResponse.cs b/itext/itext.commons/itext/commons/bouncycastle/asn1/ocsp/IBasicOcspResponse.cs index 6d6251afc5..e33fffa079 100644 --- a/itext/itext.commons/itext/commons/bouncycastle/asn1/ocsp/IBasicOcspResponse.cs +++ b/itext/itext.commons/itext/commons/bouncycastle/asn1/ocsp/IBasicOcspResponse.cs @@ -93,5 +93,7 @@ public interface IBasicOcspResponse : IAsn1Encodable { /// /// Parsed extension value. IAsn1Encodable GetExtensionParsedValue(IDerObjectIdentifier getIdPkixOcspArchiveCutoff); + + IRespID GetResponderId(); } } diff --git a/itext/itext.commons/itext/commons/bouncycastle/asn1/x500/IX500Name.cs b/itext/itext.commons/itext/commons/bouncycastle/asn1/x500/IX500Name.cs index 5268d45cbb..d57d4d7fec 100644 --- a/itext/itext.commons/itext/commons/bouncycastle/asn1/x500/IX500Name.cs +++ b/itext/itext.commons/itext/commons/bouncycastle/asn1/x500/IX500Name.cs @@ -20,6 +20,7 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ +using System; using iText.Commons.Bouncycastle.Asn1; namespace iText.Commons.Bouncycastle.Asn1.X500 { @@ -28,5 +29,8 @@ namespace iText.Commons.Bouncycastle.Asn1.X500 { /// to switch between bouncy-castle and bouncy-castle FIPS implementations. /// public interface IX500Name : IAsn1Encodable { + /// Gets the RFC2253 name. + /// the RFC2253 name + String GetName(); } } diff --git a/itext/itext.commons/itext/commons/bouncycastle/cert/ocsp/IRespID.cs b/itext/itext.commons/itext/commons/bouncycastle/cert/ocsp/IRespID.cs index bab491d4ee..1b8062bb6a 100644 --- a/itext/itext.commons/itext/commons/bouncycastle/cert/ocsp/IRespID.cs +++ b/itext/itext.commons/itext/commons/bouncycastle/cert/ocsp/IRespID.cs @@ -26,5 +26,12 @@ namespace iText.Commons.Bouncycastle.Cert.Ocsp { /// to switch between bouncy-castle and bouncy-castle FIPS implementations. ///
    public interface IRespID { + /// + /// Calls actual + /// toASN1Primitive + /// method for the wrapped BasicOCSPResp object. + /// + /// Responder ID as a ASN1 primitive. + IResponderID ToASN1Primitive(); } } diff --git a/itext/itext.commons/itext/commons/bouncycastle/cert/ocsp/IResponderID.cs b/itext/itext.commons/itext/commons/bouncycastle/cert/ocsp/IResponderID.cs new file mode 100644 index 0000000000..7199184abc --- /dev/null +++ b/itext/itext.commons/itext/commons/bouncycastle/cert/ocsp/IResponderID.cs @@ -0,0 +1,39 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Commons.Bouncycastle.Asn1.X500; + +namespace iText.Commons.Bouncycastle.Cert.Ocsp { + /// + /// This interface represents the wrapper for ResponderID that provides the ability + /// to switch between bouncy-castle and bouncy-castle FIPS implementations. + /// + public interface IResponderID { + /// + /// Calls actual + /// getName + /// method for the wrapped BasicOCSPResp object. + /// + /// wrapped X500NAme. + IX500Name GetName(); + } +} diff --git a/itext/itext.kernel/itext/kernel/events/Event.cs b/itext/itext.commons/itext/commons/bouncycastle/crypto/AbstractInvalidCipherTextException.cs similarity index 61% rename from itext/itext.kernel/itext/kernel/events/Event.cs rename to itext/itext.commons/itext/commons/bouncycastle/crypto/AbstractInvalidCipherTextException.cs index 033040c93d..67f4650e5b 100644 --- a/itext/itext.kernel/itext/kernel/events/Event.cs +++ b/itext/itext.commons/itext/commons/bouncycastle/crypto/AbstractInvalidCipherTextException.cs @@ -22,22 +22,7 @@ You should have received a copy of the GNU Affero General Public License */ using System; -namespace iText.Kernel.Events { - /// Describes abstract event. - public class Event { - /// A type of event. - protected internal String type; - - /// Creates an event of the specified type. - /// type of event - public Event(String type) { - this.type = type; - } - - /// Returns the type of this event. - /// type of this event - public virtual String GetEventType() { - return type; - } +namespace iText.Commons.Bouncycastle.Crypto { + public class AbstractInvalidCipherTextException : Exception { } } diff --git a/itext/itext.commons/itext/commons/bouncycastle/crypto/IDigest.cs b/itext/itext.commons/itext/commons/bouncycastle/crypto/IDigest.cs index 16eeff2629..2bdb63bac6 100644 --- a/itext/itext.commons/itext/commons/bouncycastle/crypto/IDigest.cs +++ b/itext/itext.commons/itext/commons/bouncycastle/crypto/IDigest.cs @@ -29,65 +29,5 @@ namespace iText.Commons.Bouncycastle.Crypto { /// to switch between bouncy-castle and bouncy-castle FIPS implementations. /// public interface IDigest : IMessageDigest { - /// - /// Calls actual - /// Digest - /// method for the wrapped IDigest object. - /// - /// byte array - /// - /// byte array. - /// - byte[] Digest(byte[] enc2); - - /// - /// Calls actual - /// Digest - /// method for the wrapped IDigest object. - /// Leaves the digest reset. - /// - /// - /// byte array. - /// - byte[] Digest(); - - /// - /// Gets byte length of wrapped digest algorithm. - /// - /// digest length - int GetDigestLength(); - - /// - /// Calls actual - /// Update - /// method for the wrapped IDigest object. - /// - /// byte array buffer - /// offset - /// buffer length - void Update(byte[] buf, int off, int len); - - /// - /// Calls actual - /// Update - /// method for the wrapped IDigest object. - /// - /// byte array buffer - void Update(byte[] buf); - - /// - /// Calls actual - /// Reset - /// method for the wrapped IDigest object. - /// - void Reset(); - - /// - /// Gets actual - /// AlgorithmName - /// for the wrapped IDigest object. - /// - /// algorithm name. - string GetAlgorithmName(); } } diff --git a/itext/itext.commons/itext/commons/bouncycastle/crypto/modes/IGCMBlockCipher.cs b/itext/itext.commons/itext/commons/bouncycastle/crypto/modes/IGCMBlockCipher.cs new file mode 100644 index 0000000000..e2af324a97 --- /dev/null +++ b/itext/itext.commons/itext/commons/bouncycastle/crypto/modes/IGCMBlockCipher.cs @@ -0,0 +1,71 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +namespace iText.Commons.Bouncycastle.Crypto.Modes { + /// Interface for aes-gcm cryptographic ciphers. + public interface IGCMBlockCipher { + /// Initialize this cipher with a key and a set of algorithm parameters. + /// true to use encrypt mode, false to use decrypt mode + /// the encryption key + /// MAC size, MAC sizes from 32 bits to 128 bits (must be a multiple of 8) + /// the IV source buffer + void Init(bool forEncryption, byte[] key, int macSizeBits, byte[] iv); + + /// + /// Returns the length in bytes that an output buffer would need to be in order to hold the result of + /// the next update operation, given the input length (in bytes). + /// + /// input length (in bytes) + /// output length in bytes + int GetUpdateOutputSize(int len); + + /// + /// Perform a multiple-part encryption or decryption operation (depending on how this cipher was initialized), + /// processing another data part. + /// + /// the input buffer + /// the offset in input where the input starts + /// the input length + /// the buffer for the result + /// the offset in output where the result is stored + void ProcessBytes(byte[] input, int inputOffset, int len, byte[] output, int outOffset); + + /// + /// Returns the length in bytes that an output buffer would need to be in order to hold the result of + /// the next doFinal operation, given the input length (in bytes). + /// + /// input length (in bytes) + /// output length in bytes + int GetOutputSize(int len); + + /// Finishes a multiple-part encryption or decryption operation, depending on how this cipher was initialized. + /// + /// + /// Finishes a multiple-part encryption or decryption operation, depending on how this cipher was initialized. + /// Input data that may have been buffered during a previous update operation is processed, also + /// the authentication tag is appended in the case of encryption, or verified in the case of decryption. + /// + /// the buffer for the result + /// the offset in output where the result is stored + void DoFinal(byte[] plainText, int i); + } +} diff --git a/itext/itext.commons/itext/commons/datastructures/ISimpleList.cs b/itext/itext.commons/itext/commons/datastructures/ISimpleList.cs new file mode 100644 index 0000000000..fafb2b2d65 --- /dev/null +++ b/itext/itext.commons/itext/commons/datastructures/ISimpleList.cs @@ -0,0 +1,90 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; + +namespace iText.Commons.Datastructures { + /// Interface for a simple list abstraction. + /// + /// Interface for a simple list abstraction. + /// + /// This interface is a subset of the + /// + /// interface. + /// It is intended to be used in cases where the full + /// + /// interface is not needed. + /// + /// The type of elements in this list. + public interface ISimpleList { + /// Adds an element to the end of the list. + /// the element to add + void Add(T element); + + /// Adds an element to the list at the specified index. + /// the index at which to add the element + /// the element to add + void Add(int index, T element); + + /// Returns the element at the specified index. + /// the index of the element to return + /// the element at the specified index + T Get(int index); + + /// Replaces the element at the specified index with the specified element. + /// the index of the element to replace + /// the element to be stored at the specified index + /// the element previously at the specified index + T Set(int index, T element); + + /// + /// Returns the index of the first occurrence of the specified element in the list, + /// or -1 if the list does not contain the element. + /// + /// the element to search for + /// + /// the index of the first occurrence of the specified element in the list, + /// or -1 if the list does not contain the element + /// + int IndexOf(Object element); + + /// Removes the element at the specified index. + /// the index of the element to be removed + void Remove(int index); + + /// Returns the number of elements in the list. + /// the number of elements in the list + int Size(); + + /// + /// Returns + /// + /// if the list contains no elements, false otherwise. + /// + /// + /// + /// + /// if the list contains no elements, false otherwise + /// + bool IsEmpty(); + } +} diff --git a/itext/itext.commons/itext/commons/datastructures/NullUnlimitedList.cs b/itext/itext.commons/itext/commons/datastructures/NullUnlimitedList.cs new file mode 100644 index 0000000000..ccb64db187 --- /dev/null +++ b/itext/itext.commons/itext/commons/datastructures/NullUnlimitedList.cs @@ -0,0 +1,160 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using System.Collections.Generic; + +namespace iText.Commons.Datastructures { + /// + /// The class represents a list which allows null elements, but doesn't allocate a memory for them, in the rest of + /// cases it behaves like usual + /// + /// and should have the same complexity (because keys are unique + /// integers, so collisions are impossible). + /// + /// elements of the list + public sealed class NullUnlimitedList : ISimpleList { + private readonly IDictionary map = new Dictionary(); + + private int size = 0; + + /// + /// Creates a new instance of + /// . + /// + public NullUnlimitedList() { + } + + // Empty constructor + /// + public void Add(T element) { + if (element == null) { + size++; + } + else { + int position = size++; + map.Put(position, element); + } + } + + /// + /// + /// In worth scenario O(n^2) but it is mostly impossible because keys shouldn't have + /// collisions at all (they are integers). + /// + /// + /// + /// In worth scenario O(n^2) but it is mostly impossible because keys shouldn't have + /// collisions at all (they are integers). So in average should be O(n). + /// + public void Add(int index, T element) { + if (index < 0 || index > size) { + return; + } + size++; + // Shifts the element currently at that position (if any) and any + // subsequent elements to the right (adds one to their indices). + T previous = map.Get(index); + for (int i = index + 1; i < size; i++) { + T currentToAdd = previous; + previous = map.Get(i); + this.Set(i, currentToAdd); + } + this.Set(index, element); + } + + /// + /// + /// average O(1), worth O(n) (mostly impossible in case when keys are integers) + /// + public T Get(int index) { + return map.Get(index); + } + + /// + /// + /// average O(1), worth O(n) (mostly impossible in case when keys are integers) + /// + public T Set(int index, T element) { + if (element == null) { + map.JRemove(index); + } + else { + map.Put(index, element); + } + return element; + } + + /// + public int IndexOf(Object element) { + if (element == null) { + for (int i = 0; i < size; i++) { + if (!map.ContainsKey(i)) { + return i; + } + } + return -1; + } + foreach (KeyValuePair entry in map) { + if (element.Equals(entry.Value)) { + return entry.Key; + } + } + return -1; + } + + /// + /// In worth scenario O(n^2) but it is mostly impossible because keys shouldn't have + /// collisions at all (they are integers). + /// + /// + /// In worth scenario O(n^2) but it is mostly impossible because keys shouldn't have + /// collisions at all (they are integers). So in average should be O(n). + /// + /// the index of the element to be removed + public void Remove(int index) { + if (index < 0 || index >= size) { + return; + } + map.JRemove(index); + // Shifts any subsequent elements to the left (subtracts one from their indices). + T previous = map.Get(size - 1); + int offset = 2; + for (int i = size - offset; i >= index; i--) { + T current = previous; + previous = map.Get(i); + this.Set(i, current); + } + map.JRemove(--size); + } + + /// the size of the list + public int Size() { + return size; + } + + /// true if the list is empty, false otherwise + public bool IsEmpty() { + return size == 0; + } + } +} diff --git a/itext/itext.commons/itext/commons/datastructures/SimpleArrayList.cs b/itext/itext.commons/itext/commons/datastructures/SimpleArrayList.cs new file mode 100644 index 0000000000..b158f3a0a3 --- /dev/null +++ b/itext/itext.commons/itext/commons/datastructures/SimpleArrayList.cs @@ -0,0 +1,95 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using System.Collections.Generic; + +namespace iText.Commons.Datastructures { + /// + /// Portable implementation of + /// . + /// + /// the type of elements in this list + public class SimpleArrayList : ISimpleList { + private readonly List list; + + /// + /// Creates a new instance of + /// . + /// + public SimpleArrayList() { + this.list = new List(); + } + + /// + /// Creates a new instance of + /// + /// with the specified initial capacity. + /// + /// the initial capacity of the list + public SimpleArrayList(int initialCapacity) { + this.list = new List(initialCapacity); + } + + /// + public virtual void Add(T element) { + list.Add(element); + } + + /// + public virtual void Add(int index, T element) { + list.Add(index, element); + } + + /// + public virtual T Get(int index) { + return list[index]; + } + + /// + public virtual T Set(int index, T element) { + T value = list[index]; + list[index] = element; + return value; + } + + /// + public virtual int IndexOf(Object element) { + return list.IndexOf((T)element); + } + + /// + public virtual void Remove(int index) { + list.JRemoveAt(index); + } + + /// + public virtual int Size() { + return list.Count; + } + + /// + public virtual bool IsEmpty() { + return list.IsEmpty(); + } + } +} diff --git a/itext/itext.commons/itext/commons/utils/Collections/MapExtensions.cs b/itext/itext.commons/itext/commons/utils/Collections/MapExtensions.cs index df1ad21f57..f44e899d6b 100644 --- a/itext/itext.commons/itext/commons/utils/Collections/MapExtensions.cs +++ b/itext/itext.commons/itext/commons/utils/Collections/MapExtensions.cs @@ -38,5 +38,14 @@ public static V ComputeIfAbsent(this IDictionary dict, K key, Func(this IDictionary dict, K key, V defaultValue) + { + if (!dict.ContainsKey(key)) + { + return defaultValue; + } + return dict[key]; + } } } \ No newline at end of file diff --git a/itext/itext.commons/itext/commons/utils/DIContainerConfigurations.cs b/itext/itext.commons/itext/commons/utils/DIContainerConfigurations.cs index f920f1c6fc..edb2f1b7da 100644 --- a/itext/itext.commons/itext/commons/utils/DIContainerConfigurations.cs +++ b/itext/itext.commons/itext/commons/utils/DIContainerConfigurations.cs @@ -26,9 +26,10 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Commons.Utils { public class DIContainerConfigurations { - - private static readonly Dictionary DEFAULT_CONFIGURATIONS = new Dictionary() { - { "iText.Forms", "iText.Forms.Util.RegisterDefaultDiContainer" } + private static readonly Dictionary DEFAULT_CONFIGURATIONS = new Dictionary() + { + { "iText.Forms", "iText.Forms.Util.RegisterDefaultDiContainer" }, + { "iText.Kernel","iText.Kernel.Utils.RegisterDefaultDiContainer" } }; public static void LoadDefaultConfigurations() { diff --git a/itext/itext.font-asian/Properties/AssemblyInfo.cs b/itext/itext.font-asian/Properties/AssemblyInfo.cs index ea181ec1d4..0a52276d04 100644 --- a/itext/itext.font-asian/Properties/AssemblyInfo.cs +++ b/itext/itext.font-asian/Properties/AssemblyInfo.cs @@ -15,6 +15,6 @@ [assembly: Guid("0f10190c-7611-4378-a157-03bf2ed78e30")] -[assembly: AssemblyVersion("8.0.5.0")] -[assembly: AssemblyFileVersion("8.0.5.0")] -[assembly: AssemblyInformationalVersion("8.0.5")] +[assembly: AssemblyVersion("9.0.0.0")] +[assembly: AssemblyFileVersion("9.0.0.0")] +[assembly: AssemblyInformationalVersion("9.0.0")] diff --git a/itext/itext.font-asian/iText Asian Font.nuspec b/itext/itext.font-asian/iText Asian Font.nuspec index a9ff0e7497..2c5c895dc0 100644 --- a/itext/itext.font-asian/iText Asian Font.nuspec +++ b/itext/itext.font-asian/iText Asian Font.nuspec @@ -2,7 +2,7 @@ itext.font-asian - 8.0.5 + 9.0.0 iText Asian Font Apryse Software Apryse Software diff --git a/itext/itext.font-asian/itext.font-asian.csproj b/itext/itext.font-asian/itext.font-asian.csproj index 6277f5e15d..ea967aa90c 100644 --- a/itext/itext.font-asian/itext.font-asian.csproj +++ b/itext/itext.font-asian/itext.font-asian.csproj @@ -46,6 +46,7 @@ + @@ -59,9 +60,20 @@ + + + + + + + + + + + @@ -75,6 +87,8 @@ + + @@ -145,6 +159,9 @@ + + + diff --git a/itext/itext.forms/Properties/AssemblyInfo.cs b/itext/itext.forms/Properties/AssemblyInfo.cs index fb6196c341..78b96b0165 100644 --- a/itext/itext.forms/Properties/AssemblyInfo.cs +++ b/itext/itext.forms/Properties/AssemblyInfo.cs @@ -20,6 +20,6 @@ [assembly: Guid("2257d7e6-2873-4cfb-ac3c-b24765a4b3b1")] -[assembly: AssemblyVersion("8.0.5.0")] -[assembly: AssemblyFileVersion("8.0.5.0")] -[assembly: AssemblyInformationalVersion("8.0.5")] +[assembly: AssemblyVersion("9.0.0.0")] +[assembly: AssemblyFileVersion("9.0.0.0")] +[assembly: AssemblyInformationalVersion("9.0.0")] diff --git a/itext/itext.forms/itext/forms/PdfAcroForm.cs b/itext/itext.forms/itext/forms/PdfAcroForm.cs index f854280e8f..846d7418c3 100644 --- a/itext/itext.forms/itext/forms/PdfAcroForm.cs +++ b/itext/itext.forms/itext/forms/PdfAcroForm.cs @@ -1382,10 +1382,10 @@ private AffineTransform CalcFieldAppTransformToAnnotRect(PdfFormXObject xObject, float[] transformedRectArr = new float[] { float.MaxValue, float.MaxValue, -float.MaxValue, -float.MaxValue }; foreach (Point p in transformedAppBoxPoints) { - transformedRectArr[0] = (float)Math.Min(transformedRectArr[0], p.x); - transformedRectArr[1] = (float)Math.Min(transformedRectArr[1], p.y); - transformedRectArr[2] = (float)Math.Max(transformedRectArr[2], p.x); - transformedRectArr[3] = (float)Math.Max(transformedRectArr[3], p.y); + transformedRectArr[0] = (float)Math.Min(transformedRectArr[0], p.GetX()); + transformedRectArr[1] = (float)Math.Min(transformedRectArr[1], p.GetY()); + transformedRectArr[2] = (float)Math.Max(transformedRectArr[2], p.GetX()); + transformedRectArr[3] = (float)Math.Max(transformedRectArr[3], p.GetY()); } transformedRect = new Rectangle(transformedRectArr[0], transformedRectArr[1], transformedRectArr[2] - transformedRectArr [0], transformedRectArr[3] - transformedRectArr[1]); diff --git a/itext/itext.forms/itext/forms/fields/AbstractPdfFormField.cs b/itext/itext.forms/itext/forms/fields/AbstractPdfFormField.cs index ca1bbf0c82..b87f8b8e8c 100644 --- a/itext/itext.forms/itext/forms/fields/AbstractPdfFormField.cs +++ b/itext/itext.forms/itext/forms/fields/AbstractPdfFormField.cs @@ -68,10 +68,7 @@ public abstract class AbstractPdfFormField : PdfObjectWrapper { protected internal Color color; - [System.ObsoleteAttribute(@"since 8.0.4, this is not used anymore! Use pdfConformanceLevel instead")] - protected internal PdfAConformanceLevel pdfAConformanceLevel; - - protected internal IConformanceLevel pdfConformanceLevel; + protected internal PdfConformance pdfConformance; /// Parent form field. protected internal PdfFormField parent; @@ -203,35 +200,13 @@ public virtual Color GetColor() { return color == null && parent != null ? parent.GetColor() : color; } - /// Gets the declared conformance level. - /// - /// Gets the declared conformance level. - /// Deprecated use - /// - /// getPdfConformanceLevel - /// - /// - /// the - /// - /// - [Obsolete] - public virtual PdfAConformanceLevel GetPdfAConformanceLevel() { - if (pdfConformanceLevel == null && parent != null) { - return parent.GetPdfAConformanceLevel(); - } - if (pdfConformanceLevel is PdfAConformanceLevel) { - return (PdfAConformanceLevel)pdfConformanceLevel; - } - return null; - } - - /// Gets the declared conformance level. + /// Gets the declared conformance. /// /// the - /// + /// /// - public virtual IConformanceLevel GetPdfConformanceLevel() { - return pdfConformanceLevel == null && parent != null ? parent.GetPdfConformanceLevel() : pdfConformanceLevel; + public virtual PdfConformance GetPdfConformance() { + return pdfConformance == null && parent != null ? parent.GetPdfConformance() : pdfConformance; } /// This method regenerates appearance stream of the field. diff --git a/itext/itext.forms/itext/forms/fields/CheckBoxFormFieldBuilder.cs b/itext/itext.forms/itext/forms/fields/CheckBoxFormFieldBuilder.cs index 10dac67021..eeb0b7d005 100644 --- a/itext/itext.forms/itext/forms/fields/CheckBoxFormFieldBuilder.cs +++ b/itext/itext.forms/itext/forms/fields/CheckBoxFormFieldBuilder.cs @@ -74,13 +74,13 @@ public virtual PdfButtonFormField CreateCheckBox() { else { PdfWidgetAnnotation annotation = new PdfWidgetAnnotation(GetWidgetRectangle()); annotation.SetAppearanceState(new PdfName(PdfFormAnnotation.OFF_STATE_VALUE)); - if (GetGenericConformanceLevel() != null) { + if (GetConformance() != null && GetConformance().IsPdfAOrUa()) { annotation.SetFlag(PdfAnnotation.PRINT); } check = PdfFormCreator.CreateButtonFormField(annotation, GetDocument()); } check.DisableFieldRegeneration(); - check.pdfConformanceLevel = GetGenericConformanceLevel(); + check.pdfConformance = GetConformance(); check.SetCheckType(checkType); check.SetFieldName(GetFormFieldName()); // the default behavior is to automatically calculate the fontsize diff --git a/itext/itext.forms/itext/forms/fields/ChoiceFormFieldBuilder.cs b/itext/itext.forms/itext/forms/fields/ChoiceFormFieldBuilder.cs index 347f3980c3..04ac51947d 100644 --- a/itext/itext.forms/itext/forms/fields/ChoiceFormFieldBuilder.cs +++ b/itext/itext.forms/itext/forms/fields/ChoiceFormFieldBuilder.cs @@ -120,13 +120,13 @@ private PdfChoiceFormField CreateChoice(int flags) { } else { annotation = new PdfWidgetAnnotation(GetWidgetRectangle()); - if (null != GetGenericConformanceLevel()) { + if (null != GetConformance() && GetConformance().IsPdfAOrUa()) { annotation.SetFlag(PdfAnnotation.PRINT); } field = PdfFormCreator.CreateChoiceFormField(annotation, GetDocument()); } field.DisableFieldRegeneration(); - field.pdfConformanceLevel = GetGenericConformanceLevel(); + field.pdfConformance = GetConformance(); if (this.GetFont() != null) { field.SetFont(this.GetFont()); } diff --git a/itext/itext.forms/itext/forms/fields/FormFieldBuilder.cs b/itext/itext.forms/itext/forms/fields/FormFieldBuilder.cs index bfb9d8f3bd..5b43462eaa 100644 --- a/itext/itext.forms/itext/forms/fields/FormFieldBuilder.cs +++ b/itext/itext.forms/itext/forms/fields/FormFieldBuilder.cs @@ -34,8 +34,8 @@ public abstract class FormFieldBuilder /// Name of the form field. private readonly String formFieldName; - /// Conformance level of the form field. - private IConformanceLevel conformanceLevel = null; + /// Conformance of the form field. + private PdfConformance conformance = null; /// /// Creates builder for @@ -48,7 +48,7 @@ protected internal FormFieldBuilder(PdfDocument document, String formFieldName) this.document = document; this.formFieldName = formFieldName; if (document != null) { - this.conformanceLevel = document.GetConformanceLevel(); + this.conformance = document.GetConformance(); } } @@ -68,56 +68,25 @@ public virtual String GetFormFieldName() { return formFieldName; } - /// Gets conformance level for form field creation. + /// Gets conformance for form field creation. /// /// instance of - /// + /// /// to be used for form field creation /// - [System.ObsoleteAttribute(@"since 8.0.4 will return iText.Kernel.Pdf.IConformanceLevel in next major release" - )] - public virtual PdfAConformanceLevel GetConformanceLevel() { - if (conformanceLevel is PdfAConformanceLevel) { - return (PdfAConformanceLevel)conformanceLevel; - } - return null; - } - - /// Gets conformance level for form field creation. - /// - /// instance of - /// - /// to be used for form field creation - /// - [System.ObsoleteAttribute(@"since 8.0.4 will be renamed to getConformanceLevel()")] - public virtual IConformanceLevel GetGenericConformanceLevel() { - return conformanceLevel; + public virtual PdfConformance GetConformance() { + return conformance; } - /// Sets conformance level for form field creation. - /// - /// instance of - /// - /// to be used for form field creation - /// - /// this builder - [System.ObsoleteAttribute(@"since 8.0.4 conformance level param will change to iText.Kernel.Pdf.IConformanceLevel" - )] - public virtual T SetConformanceLevel(PdfAConformanceLevel conformanceLevel) { - this.conformanceLevel = conformanceLevel; - return GetThis(); - } - - /// Sets conformance level for form field creation. - /// + /// Sets conformance for form field creation. + /// /// Instance of - /// + /// /// to be used for form field creation. /// - /// This builder. - [System.ObsoleteAttribute(@"since 8.0.4 will be renamed to setConformanceLevel")] - public virtual T SetGenericConformanceLevel(IConformanceLevel conformanceLevel) { - this.conformanceLevel = conformanceLevel; + /// this builder + public virtual T SetConformance(PdfConformance conformance) { + this.conformance = conformance; return GetThis(); } diff --git a/itext/itext.forms/itext/forms/fields/NonTerminalFormFieldBuilder.cs b/itext/itext.forms/itext/forms/fields/NonTerminalFormFieldBuilder.cs index aba6f988a8..999fcbad5c 100644 --- a/itext/itext.forms/itext/forms/fields/NonTerminalFormFieldBuilder.cs +++ b/itext/itext.forms/itext/forms/fields/NonTerminalFormFieldBuilder.cs @@ -46,7 +46,7 @@ public NonTerminalFormFieldBuilder(PdfDocument document, String formFieldName) /// public virtual PdfFormField CreateNonTerminalFormField() { PdfFormField field = PdfFormCreator.CreateFormField(GetDocument()); - field.pdfConformanceLevel = GetGenericConformanceLevel(); + field.pdfConformance = GetConformance(); field.SetFieldName(GetFormFieldName()); return field; } diff --git a/itext/itext.forms/itext/forms/fields/PdfFormAnnotation.cs b/itext/itext.forms/itext/forms/fields/PdfFormAnnotation.cs index c058a60d52..7ae69cf250 100644 --- a/itext/itext.forms/itext/forms/fields/PdfFormAnnotation.cs +++ b/itext/itext.forms/itext/forms/fields/PdfFormAnnotation.cs @@ -165,9 +165,8 @@ public static iText.Forms.Fields.PdfFormAnnotation MakeFormAnnotation(PdfObject return null; } field.MakeIndirect(document); - if (document != null && document.GetReader() != null && document.GetReader().GetPdfAConformanceLevel() != - null) { - field.pdfConformanceLevel = document.GetReader().GetPdfAConformanceLevel(); + if (document != null) { + field.pdfConformance = document.GetConformance(); } return field; } @@ -439,15 +438,13 @@ public virtual float GetBorderWidth() { /// . /// public virtual iText.Forms.Fields.PdfFormAnnotation SetBorderWidth(float borderWidth) { - // Acrobat doesn't support float border width therefore we round it. - int roundedBorderWidth = (int)MathematicUtil.Round(borderWidth); PdfDictionary bs = GetWidget().GetBorderStyle(); if (bs == null) { bs = new PdfDictionary(); Put(PdfName.BS, bs); } - bs.Put(PdfName.W, new PdfNumber(roundedBorderWidth)); - this.borderWidth = roundedBorderWidth; + bs.Put(PdfName.W, new PdfNumber(borderWidth)); + this.borderWidth = borderWidth; RegenerateField(); return this; } @@ -463,7 +460,7 @@ public virtual Border GetBorder() { Border border = FormBorderFactory.GetBorder(this.GetWidget().GetBorderStyle(), borderWidth, borderColor, backgroundColor ); if (border == null && borderWidth > 0 && borderColor != null) { - border = new SolidBorder(borderColor, Math.Max(1, borderWidth)); + border = new SolidBorder(borderColor, borderWidth); } return border; } @@ -530,10 +527,10 @@ public virtual iText.Forms.Fields.PdfFormAnnotation SetPage(int pageNum) { /// /// Also note that the model element won't be used for annotations for choice form field. /// - /// model element to set. + /// model element to set /// /// this - /// . + /// /// public virtual iText.Forms.Fields.PdfFormAnnotation SetFormFieldElement(IFormField element) { this.formFieldElement = element; @@ -808,12 +805,14 @@ protected internal virtual void DrawListFormFieldAndSaveAppearance() { if (rectangle == null) { return; } + bool multiselect = parent.GetFieldFlag(PdfChoiceFormField.FF_MULTI_SELECT); if (!(formFieldElement is ListBoxField)) { // Create it once and reset properties during each widget regeneration. - formFieldElement = new ListBoxField("", 0, parent.GetFieldFlag(PdfChoiceFormField.FF_MULTI_SELECT)); + formFieldElement = new ListBoxField(parent.GetPartialFieldName().ToUnicodeString(), 0, multiselect); } - formFieldElement.SetProperty(FormProperty.FORM_FIELD_MULTIPLE, parent.GetFieldFlag(PdfChoiceFormField.FF_MULTI_SELECT - )); + formFieldElement.SetProperty(FormProperty.FORM_FIELD_MULTIPLE, multiselect); + ((ListBoxField)formFieldElement).SetTopIndex(parent is PdfChoiceFormField && ((PdfChoiceFormField)parent). + GetTopIndex() != null ? ((PdfChoiceFormField)parent).GetTopIndex().IntValue() : 0); PdfArray indices = GetParent().GetAsArray(PdfName.I); PdfArray options = parent.GetOptions(); for (int index = 0; index < options.Size(); ++index) { @@ -838,13 +837,25 @@ protected internal virtual void DrawListFormFieldAndSaveAppearance() { bool selected = indices != null && indices.Contains(new PdfNumber(index)); SelectFieldItem existingItem = ((ListBoxField)formFieldElement).GetOption(exportValue); if (existingItem == null) { - existingItem = new SelectFieldItem(exportValue, displayValue); + existingItem = displayValue == null ? new SelectFieldItem(exportValue) : new SelectFieldItem(exportValue, + displayValue); ((ListBoxField)formFieldElement).AddOption(existingItem); } existingItem.GetElement().SetProperty(Property.TEXT_ALIGNMENT, parent.GetJustification()); existingItem.GetElement().SetProperty(Property.OVERFLOW_Y, OverflowPropertyValue.VISIBLE); existingItem.GetElement().SetProperty(Property.OVERFLOW_X, OverflowPropertyValue.VISIBLE); existingItem.GetElement().SetProperty(FormProperty.FORM_FIELD_SELECTED, selected); + // Workaround for com.itextpdf.forms.form.renderer.SelectFieldListBoxRenderer.applySelectedStyle: + // in HTML rendering mode we want to draw gray background for flattened fields and blue one for interactive, + // but here we temporarily flatten formFieldElement, so blue background property is explicitly set to + // the selected item. We also need to clear background property for not selected items in case field + // is regenerated with modified indices list. + if (selected && (multiselect || index == indices.GetAsNumber(indices.Size() - 1).IntValue())) { + existingItem.GetElement().SetProperty(Property.BACKGROUND, new Background(new DeviceRgb(169, 204, 225))); + } + else { + existingItem.GetElement().SetProperty(Property.BACKGROUND, null); + } } formFieldElement.SetProperty(Property.FONT, GetFont()); if (GetColor() != null) { @@ -879,9 +890,18 @@ protected internal virtual void DrawTextFormFieldAndSaveAppearance() { formFieldElement.SetProperty(Property.FONT_SIZE, UnitValue.CreatePointValue(GetFontSize())); } else { - formFieldElement.SetProperty(Property.FONT_SIZE, UnitValue.CreatePointValue(GetFontSize(new PdfArray(rectangle - ), parent.GetValueAsString()))); + float fontSize = GetFontSize(new PdfArray(rectangle), parent.GetValueAsString()); + if (fontSize != 0) { + // We want to always draw the text using the given font size even if it's not fit into layout area. + // Without setting this property the height of the drawn field will be 0 which is unexpected. + formFieldElement.SetProperty(Property.FORCED_PLACEMENT, true); + } + formFieldElement.SetProperty(Property.FONT_SIZE, UnitValue.CreatePointValue(fontSize)); value = iText.Commons.Utils.StringUtil.ReplaceAll(value, LINE_ENDINGS_REGEXP, " "); + ((InputField)formFieldElement).SetComb(this.IsCombTextFormField()); + ((InputField)formFieldElement).SetMaxLen((parent is PdfTextFormField ? (PdfTextFormField)parent : PdfFormCreator + .CreateTextFormField(parent.GetPdfObject())).GetMaxLen()); + ((InputField)formFieldElement).UseAsPassword(parent.IsPassword()); } formFieldElement.SetValue(value); formFieldElement.SetProperty(Property.FONT, GetFont()); @@ -916,7 +936,7 @@ protected internal virtual void DrawComboBoxAndSaveAppearance() { return; } if (!(formFieldElement is ComboBoxField)) { - formFieldElement = new ComboBoxField(""); + formFieldElement = new ComboBoxField(parent.GetPartialFieldName().ToUnicodeString()); } ComboBoxField comboBoxField = (ComboBoxField)formFieldElement; PrepareComboBoxFieldWithCorrectOptionsAndValues(comboBoxField); @@ -990,7 +1010,7 @@ protected internal virtual void DrawCheckBoxAndSaveAppearance(String onStateName iText.Layout.Canvas canvasOff = new iText.Layout.Canvas(xObjectOff, GetDocument()); SetMetaInfoToCanvas(canvasOff); canvasOff.Add(formFieldElement); - if (GetPdfConformanceLevel() == null) { + if (GetPdfConformance() == null || !GetPdfConformance().IsPdfAOrUa()) { xObjectOff.GetResources().AddFont(GetDocument(), GetFont()); } normalAppearance.Put(new PdfName(OFF_STATE_VALUE), xObjectOff.GetPdfObject()); @@ -1038,49 +1058,38 @@ internal virtual bool RegenerateWidget() { } PdfName type = parent.GetFormType(); RetrieveStyles(); - if ((PdfName.Ch.Equals(type) && parent.GetFieldFlag(PdfChoiceFormField.FF_COMBO)) || this.IsCombTextFormField - ()) { - if (parent.GetFieldFlag(PdfChoiceFormField.FF_COMBO) && formFieldElement != null) { + if (PdfName.Ch.Equals(type)) { + if (parent.GetFieldFlag(PdfChoiceFormField.FF_COMBO)) { DrawComboBoxAndSaveAppearance(); return true; } - return TextAndChoiceLegacyDrawer.RegenerateTextAndChoiceField(this); + DrawListFormFieldAndSaveAppearance(); + return true; } else { - if (PdfName.Ch.Equals(type) && !parent.GetFieldFlag(PdfChoiceFormField.FF_COMBO)) { - if (formFieldElement != null) { - DrawListFormFieldAndSaveAppearance(); - return true; - } - else { - return TextAndChoiceLegacyDrawer.RegenerateTextAndChoiceField(this); - } + if (PdfName.Tx.Equals(type)) { + DrawTextFormFieldAndSaveAppearance(); + return true; } else { - if (PdfName.Tx.Equals(type)) { - DrawTextFormFieldAndSaveAppearance(); - return true; - } - else { - if (PdfName.Btn.Equals(type)) { - if (parent.GetFieldFlag(PdfButtonFormField.FF_PUSH_BUTTON)) { - DrawPushButtonFieldAndSaveAppearance(); + if (PdfName.Btn.Equals(type)) { + if (parent.GetFieldFlag(PdfButtonFormField.FF_PUSH_BUTTON)) { + DrawPushButtonFieldAndSaveAppearance(); + } + else { + if (parent.GetFieldFlag(PdfButtonFormField.FF_RADIO)) { + DrawRadioButtonAndSaveAppearance(GetRadioButtonValue()); } else { - if (parent.GetFieldFlag(PdfButtonFormField.FF_RADIO)) { - DrawRadioButtonAndSaveAppearance(GetRadioButtonValue()); - } - else { - DrawCheckBoxAndSaveAppearance(GetCheckBoxValue()); - } + DrawCheckBoxAndSaveAppearance(GetCheckBoxValue()); } - return true; } - else { - if (PdfName.Sig.Equals(type)) { - DrawSignatureFormFieldAndSaveAppearance(); - return true; - } + return true; + } + else { + if (PdfName.Sig.Equals(type)) { + DrawSignatureFormFieldAndSaveAppearance(); + return true; } } } @@ -1169,14 +1178,17 @@ internal virtual float GetFontSize(PdfArray bBox, String value) { private bool IsCombTextFormField() { PdfName type = parent.GetFormType(); - if (PdfName.Tx.Equals(type) && parent.GetFieldFlag(PdfTextFormField.FF_COMB)) { - int maxLen = PdfFormCreator.CreateTextFormField(parent.GetPdfObject()).GetMaxLen(); - if (maxLen == 0 || parent.IsMultiline()) { - LOGGER.LogError(MessageFormatUtil.Format(iText.IO.Logs.IoLogMessageConstant.COMB_FLAG_MAY_BE_SET_ONLY_IF_MAXLEN_IS_PRESENT - )); - return false; + if (PdfName.Tx.Equals(type)) { + PdfTextFormField textField = parent is PdfTextFormField ? (PdfTextFormField)parent : PdfFormCreator.CreateTextFormField + (parent.GetPdfObject()); + if (textField.IsComb()) { + if (textField.GetMaxLen() == 0 || textField.IsMultiline() || textField.IsPassword() || textField.IsFileSelect + ()) { + LOGGER.LogError(iText.IO.Logs.IoLogMessageConstant.COMB_FLAG_MAY_BE_SET_ONLY_IF_MAXLEN_IS_PRESENT); + return false; + } + return true; } - return true; } return false; } @@ -1228,7 +1240,7 @@ private void CreateCheckBox() { } formFieldElement.SetProperty(Property.FONT_SIZE, UnitValue.CreatePointValue(GetFontSize())); SetModelElementProperties(GetRect(GetPdfObject())); - ((CheckBox)formFieldElement).SetPdfConformanceLevel(GetPdfConformanceLevel()); + ((CheckBox)formFieldElement).SetPdfConformance(GetPdfConformance()); ((CheckBox)formFieldElement).SetCheckBoxType(parent.checkType.GetValue()); } @@ -1236,7 +1248,10 @@ private void SetModelElementProperties(Rectangle rectangle) { if (backgroundColor != null) { formFieldElement.SetProperty(Property.BACKGROUND, new Background(backgroundColor)); } - formFieldElement.SetProperty(Property.BORDER, GetBorder()); + formFieldElement.SetProperty(Property.BORDER_TOP, GetBorder()); + formFieldElement.SetProperty(Property.BORDER_RIGHT, GetBorder()); + formFieldElement.SetProperty(Property.BORDER_BOTTOM, GetBorder()); + formFieldElement.SetProperty(Property.BORDER_LEFT, GetBorder()); // Set fixed size BoxSizingPropertyValue? boxSizing = formFieldElement.GetProperty(Property.BOX_SIZING ); diff --git a/itext/itext.forms/itext/forms/fields/PdfFormField.cs b/itext/itext.forms/itext/forms/fields/PdfFormField.cs index cf6e694a04..0d42761929 100644 --- a/itext/itext.forms/itext/forms/fields/PdfFormField.cs +++ b/itext/itext.forms/itext/forms/fields/PdfFormField.cs @@ -270,9 +270,8 @@ public static iText.Forms.Fields.PdfFormField MakeFormField(PdfObject pdfObject, } } field.MakeIndirect(document); - if (document != null && document.GetReader() != null && document.GetReader().GetPdfAConformanceLevel() != - null) { - field.pdfConformanceLevel = document.GetReader().GetPdfAConformanceLevel(); + if (document != null) { + field.pdfConformance = document.GetConformance(); } return field; } @@ -1190,7 +1189,7 @@ public virtual iText.Forms.Fields.PdfFormField SetCheckType(CheckBoxType checkTy checkType = CheckBoxType.CROSS; } this.checkType = new NullableContainer(checkType); - if (GetPdfConformanceLevel() != null) { + if (GetPdfConformance() != null && GetPdfConformance().IsPdfAOrUa()) { return this; } try { @@ -1427,7 +1426,7 @@ internal virtual void ReplaceKids(ICollection kids) { private static PdfString GenerateDefaultAppearance(PdfName font, float fontSize, Color textColor) { System.Diagnostics.Debug.Assert(font != null); MemoryStream output = new MemoryStream(); - PdfOutputStream pdfStream = new PdfOutputStream(new OutputStream(output)); + PdfOutputStream pdfStream = new PdfOutputStream(new HighPrecisionOutputStream(output)); byte[] g = new byte[] { (byte)'g' }; byte[] rg = new byte[] { (byte)'r', (byte)'g' }; byte[] k = new byte[] { (byte)'k' }; diff --git a/itext/itext.forms/itext/forms/fields/PdfFormFieldMergeUtil.cs b/itext/itext.forms/itext/forms/fields/PdfFormFieldMergeUtil.cs index 177cd5bd5d..53e296c1a4 100644 --- a/itext/itext.forms/itext/forms/fields/PdfFormFieldMergeUtil.cs +++ b/itext/itext.forms/itext/forms/fields/PdfFormFieldMergeUtil.cs @@ -49,7 +49,7 @@ public static void MergeKidsWithSameNames(PdfFormField parentField, bool throwEx return; } PdfArray kids = parent.GetAsArray(PdfName.Kids); - if (kids == null || kids.Size() == 0) { + if (kids == null || kids.IsEmpty()) { return; } IDictionary addedKids = new LinkedDictionary(); @@ -83,6 +83,10 @@ public static void MergeKidsWithSameNames(PdfFormField parentField, bool throwEx /// true if fields is successfully merged, false otherwise. public static bool MergeTwoFieldsWithTheSameNames(PdfFormField firstField, PdfFormField secondField, bool throwExceptionOnError) { + if (firstField.GetPdfObject() == secondField.GetPdfObject()) { + // We don't need to perform any strategy on duplicated references, we can just always remove them. + return true; + } OnDuplicateFormFieldNameStrategy onDuplicateFormFieldNameStrategy = firstField.GetDocument().GetDiContainer ().GetInstance(); return onDuplicateFormFieldNameStrategy.Execute(firstField, secondField, throwExceptionOnError); diff --git a/itext/itext.forms/itext/forms/fields/PdfTextFormField.cs b/itext/itext.forms/itext/forms/fields/PdfTextFormField.cs index 0864d0c907..bec270b2c3 100644 --- a/itext/itext.forms/itext/forms/fields/PdfTextFormField.cs +++ b/itext/itext.forms/itext/forms/fields/PdfTextFormField.cs @@ -202,7 +202,13 @@ public virtual iText.Forms.Fields.PdfTextFormField SetScroll(bool scroll) { /// If true, the field is automatically divided into as many equally spaced positions, /// or combs, as the value of MaxLen, and the text is laid out into those combs. /// - /// whether or not combing is enabled + /// + /// + /// + /// if combing is enabled, + /// + /// otherwise + /// public virtual bool IsComb() { return GetFieldFlag(FF_COMB); } diff --git a/itext/itext.forms/itext/forms/fields/PushButtonFormFieldBuilder.cs b/itext/itext.forms/itext/forms/fields/PushButtonFormFieldBuilder.cs index 496bcd2a8b..c321affc26 100644 --- a/itext/itext.forms/itext/forms/fields/PushButtonFormFieldBuilder.cs +++ b/itext/itext.forms/itext/forms/fields/PushButtonFormFieldBuilder.cs @@ -71,7 +71,7 @@ public virtual PdfButtonFormField CreatePushButton() { else { annotation = new PdfWidgetAnnotation(GetWidgetRectangle()); field = PdfFormCreator.CreateButtonFormField(annotation, GetDocument()); - if (null != GetGenericConformanceLevel()) { + if (null != GetConformance() && GetConformance().IsPdfAOrUa()) { annotation.SetFlag(PdfAnnotation.PRINT); } } @@ -79,7 +79,7 @@ public virtual PdfButtonFormField CreatePushButton() { if (this.GetFont() != null) { field.SetFont(this.GetFont()); } - field.pdfConformanceLevel = GetGenericConformanceLevel(); + field.pdfConformance = GetConformance(); field.SetPushButton(true); field.SetFieldName(GetFormFieldName()); field.text = caption; diff --git a/itext/itext.forms/itext/forms/fields/RadioFormFieldBuilder.cs b/itext/itext.forms/itext/forms/fields/RadioFormFieldBuilder.cs index 07b7658c26..9c251bf416 100644 --- a/itext/itext.forms/itext/forms/fields/RadioFormFieldBuilder.cs +++ b/itext/itext.forms/itext/forms/fields/RadioFormFieldBuilder.cs @@ -46,7 +46,7 @@ public RadioFormFieldBuilder(PdfDocument document, String radioGroupFormFieldNam public virtual PdfButtonFormField CreateRadioGroup() { PdfButtonFormField radioGroup = PdfFormCreator.CreateButtonFormField(GetDocument()); radioGroup.DisableFieldRegeneration(); - radioGroup.pdfConformanceLevel = GetGenericConformanceLevel(); + radioGroup.pdfConformance = GetConformance(); radioGroup.SetFieldName(GetFormFieldName()); radioGroup.SetFieldFlags(PdfButtonFormField.FF_RADIO); radioGroup.EnableFieldRegeneration(); @@ -71,12 +71,12 @@ public virtual PdfFormAnnotation CreateRadioButton(String appearanceName, Rectan PdfName appearancePdfName = new PdfName(appearanceName); PdfWidgetAnnotation annotation = new PdfWidgetAnnotation(widgetRectangle); annotation.SetAppearanceState(appearancePdfName); - if (GetGenericConformanceLevel() != null) { + if (GetConformance() != null && GetConformance().IsPdfAOrUa()) { annotation.SetFlag(PdfAnnotation.PRINT); } PdfFormAnnotation radio = PdfFormCreator.CreateFormAnnotation(annotation, GetDocument()); SetPageToField(radio); - radio.pdfConformanceLevel = GetGenericConformanceLevel(); + radio.pdfConformance = GetConformance(); return radio; } diff --git a/itext/itext.forms/itext/forms/fields/SignatureFormFieldBuilder.cs b/itext/itext.forms/itext/forms/fields/SignatureFormFieldBuilder.cs index dabe69a64e..17d2c03ec6 100644 --- a/itext/itext.forms/itext/forms/fields/SignatureFormFieldBuilder.cs +++ b/itext/itext.forms/itext/forms/fields/SignatureFormFieldBuilder.cs @@ -52,7 +52,7 @@ public virtual PdfSignatureFormField CreateSignature() { } else { PdfWidgetAnnotation annotation = new PdfWidgetAnnotation(GetWidgetRectangle()); - if (GetGenericConformanceLevel() != null) { + if (GetConformance() != null && GetConformance().IsPdfAOrUa()) { annotation.SetFlag(PdfAnnotation.PRINT); } signatureFormField = PdfFormCreator.CreateSignatureFormField(annotation, GetDocument()); @@ -63,7 +63,7 @@ public virtual PdfSignatureFormField CreateSignature() { if (GetFont() != null) { signatureFormField.font = GetFont(); } - signatureFormField.pdfConformanceLevel = GetGenericConformanceLevel(); + signatureFormField.pdfConformance = GetConformance(); signatureFormField.SetFieldName(GetFormFieldName()); return signatureFormField; } diff --git a/itext/itext.forms/itext/forms/fields/TextAndChoiceLegacyDrawer.cs b/itext/itext.forms/itext/forms/fields/TextAndChoiceLegacyDrawer.cs deleted file mode 100644 index ef7eb03e18..0000000000 --- a/itext/itext.forms/itext/forms/fields/TextAndChoiceLegacyDrawer.cs +++ /dev/null @@ -1,382 +0,0 @@ -/* -This file is part of the iText (R) project. -Copyright (c) 1998-2024 Apryse Group NV -Authors: Apryse Software. - -This program is offered under a commercial and under the AGPL license. -For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. - -AGPL licensing: -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . -*/ -using System; -using System.Collections.Generic; -using Microsoft.Extensions.Logging; -using iText.Commons; -using iText.Forms.Logs; -using iText.Kernel.Colors; -using iText.Kernel.Font; -using iText.Kernel.Geom; -using iText.Kernel.Pdf; -using iText.Kernel.Pdf.Annot; -using iText.Kernel.Pdf.Canvas; -using iText.Kernel.Pdf.Xobject; -using iText.Layout; -using iText.Layout.Element; -using iText.Layout.Properties; - -namespace iText.Forms.Fields { -//\cond DO_NOT_DOCUMENT - internal sealed class TextAndChoiceLegacyDrawer { - private static readonly ILogger LOGGER = ITextLogManager.GetLogger(typeof(iText.Forms.Fields.TextAndChoiceLegacyDrawer - )); - - private TextAndChoiceLegacyDrawer() { - } - -//\cond DO_NOT_DOCUMENT - //Empty constructor. - internal static bool RegenerateTextAndChoiceField(PdfFormAnnotation formAnnotation) { - String value = formAnnotation.parent.GetDisplayValue(); - PdfName type = formAnnotation.parent.GetFormType(); - PdfPage page = PdfAnnotation.MakeAnnotation(formAnnotation.GetPdfObject()).GetPage(); - PdfArray bBox = formAnnotation.GetPdfObject().GetAsArray(PdfName.Rect); - //Apply Page rotation - int pageRotation = 0; - if (page != null) { - pageRotation = page.GetRotation(); - //Clockwise, so negative - pageRotation *= -1; - } - PdfArray matrix; - if (pageRotation % 90 == 0) { - //Cast angle to [-360, 360] - double angle = pageRotation % 360; - //Get angle in radians - angle = DegreeToRadians(angle); - Rectangle initialBboxRectangle = bBox.ToRectangle(); - //rotate the bounding box - Rectangle rect = initialBboxRectangle.Clone(); - //Calculate origin offset - double translationWidth = 0; - double translationHeight = 0; - if (angle >= -1 * Math.PI && angle <= -1 * Math.PI / 2) { - translationWidth = rect.GetWidth(); - } - if (angle <= -1 * Math.PI) { - translationHeight = rect.GetHeight(); - } - //Store rotation and translation in the matrix - matrix = new PdfArray(new double[] { Math.Cos(angle), -Math.Sin(angle), Math.Sin(angle), Math.Cos(angle), - translationWidth, translationHeight }); - // If the angle is a multiple of 90 and not a multiple of 180, height and width of the bounding box - // need to be switched - if (angle % (Math.PI / 2) == 0 && angle % (Math.PI) != 0) { - rect.SetWidth(initialBboxRectangle.GetHeight()); - rect.SetHeight(initialBboxRectangle.GetWidth()); - } - // Adapt origin - rect.SetX(rect.GetX() + (float)translationWidth); - rect.SetY(rect.GetY() + (float)translationHeight); - //Copy Bounding box - bBox = new PdfArray(rect); - } - else { - //Avoid NPE when handling corrupt pdfs - LOGGER.LogError(FormsLogMessageConstants.INCORRECT_PAGE_ROTATION); - matrix = new PdfArray(new double[] { 1, 0, 0, 1, 0, 0 }); - } - //Apply field rotation - float fieldRotation = 0; - if (formAnnotation.GetPdfObject().GetAsDictionary(PdfName.MK) != null && formAnnotation.GetPdfObject().GetAsDictionary - (PdfName.MK).Get(PdfName.R) != null) { - fieldRotation = (float)formAnnotation.GetPdfObject().GetAsDictionary(PdfName.MK).GetAsFloat(PdfName.R); - //Get relative field rotation - fieldRotation += pageRotation; - } - if (fieldRotation % 90 == 0) { - Rectangle initialBboxRectangle = bBox.ToRectangle(); - //Cast angle to [-360, 360] - double angle = fieldRotation % 360; - //Get angle in radians - angle = DegreeToRadians(angle); - //Calculate origin offset - double translationWidth = CalculateTranslationWidthAfterFieldRot(initialBboxRectangle, DegreeToRadians(pageRotation - ), angle); - double translationHeight = CalculateTranslationHeightAfterFieldRot(initialBboxRectangle, DegreeToRadians(pageRotation - ), angle); - //Concatenate rotation and translation into the matrix - Matrix currentMatrix = new Matrix(matrix.GetAsNumber(0).FloatValue(), matrix.GetAsNumber(1).FloatValue(), - matrix.GetAsNumber(2).FloatValue(), matrix.GetAsNumber(3).FloatValue(), matrix.GetAsNumber(4).FloatValue - (), matrix.GetAsNumber(5).FloatValue()); - Matrix toConcatenate = new Matrix((float)Math.Cos(angle), (float)(-Math.Sin(angle)), (float)(Math.Sin(angle - )), (float)(Math.Cos(angle)), (float)translationWidth, (float)translationHeight); - currentMatrix = currentMatrix.Multiply(toConcatenate); - matrix = new PdfArray(new float[] { currentMatrix.Get(0), currentMatrix.Get(1), currentMatrix.Get(3), currentMatrix - .Get(4), currentMatrix.Get(6), currentMatrix.Get(7) }); - // Construct bounding box - Rectangle rect = initialBboxRectangle.Clone(); - // If the angle is a multiple of 90 and not a multiple of 180, height and width of the bounding box - // need to be switched - if (angle % (Math.PI / 2) == 0 && angle % (Math.PI) != 0) { - rect.SetWidth(initialBboxRectangle.GetHeight()); - rect.SetHeight(initialBboxRectangle.GetWidth()); - } - rect.SetX(rect.GetX() + (float)translationWidth); - rect.SetY(rect.GetY() + (float)translationHeight); - // Copy Bounding box - bBox = new PdfArray(rect); - } - // Create appearance - Rectangle bboxRectangle = bBox.ToRectangle(); - PdfFormXObject appearance = new PdfFormXObject(new Rectangle(0, 0, bboxRectangle.GetWidth(), bboxRectangle - .GetHeight())); - appearance.Put(PdfName.Matrix, matrix); - //Create text appearance - if (PdfName.Tx.Equals(type)) { - DrawCombTextAppearance(formAnnotation, bboxRectangle, formAnnotation.GetFont(), formAnnotation.GetFontSize - (bBox, value), value, appearance); - } - else { - int topIndex = 0; - if (!formAnnotation.parent.GetFieldFlag(PdfChoiceFormField.FF_COMBO)) { - PdfNumber topIndexNum = formAnnotation.GetParent().GetAsNumber(PdfName.TI); - PdfArray options = formAnnotation.parent.GetOptions(); - if (null != options) { - topIndex = null != topIndexNum ? topIndexNum.IntValue() : 0; - PdfArray visibleOptions = topIndex > 0 ? new PdfArray(options.SubList(topIndex, options.Size())) : (PdfArray - )options.Clone(); - value = PdfFormField.OptionsArrayToString(visibleOptions); - } - } - DrawChoiceAppearance(formAnnotation, bboxRectangle, formAnnotation.GetFontSize(bBox, value), value, appearance - , topIndex); - } - PdfDictionary ap = new PdfDictionary(); - ap.Put(PdfName.N, appearance.GetPdfObject()); - ap.SetModified(); - formAnnotation.Put(PdfName.AP, ap); - return true; - } -//\endcond - -//\cond DO_NOT_DOCUMENT - internal static void DrawChoiceAppearance(PdfFormAnnotation formAnnotation, Rectangle rect, float fontSize - , String value, PdfFormXObject appearance, int topIndex) { - PdfStream stream = (PdfStream)new PdfStream().MakeIndirect(formAnnotation.GetDocument()); - PdfResources resources = appearance.GetResources(); - PdfCanvas canvas = new PdfCanvas(stream, resources, formAnnotation.GetDocument()); - float width = rect.GetWidth(); - float height = rect.GetHeight(); - float widthBorder = 6.0f; - float heightBorder = 2.0f; - formAnnotation.DrawBorder(canvas, appearance, width, height); - canvas.BeginVariableText().SaveState().Rectangle(3, 3, width - widthBorder, height - heightBorder).Clip(). - EndPath(); - iText.Layout.Canvas modelCanvas = new iText.Layout.Canvas(canvas, new Rectangle(3, 0, Math.Max(0, width - - widthBorder), Math.Max(0, height - heightBorder))); - modelCanvas.SetProperty(Property.APPEARANCE_STREAM_LAYOUT, true); - PdfFormAnnotation.SetMetaInfoToCanvas(modelCanvas); - Div div = new Div(); - if (formAnnotation.parent.GetFieldFlag(PdfChoiceFormField.FF_COMBO)) { - div.SetVerticalAlignment(VerticalAlignment.MIDDLE); - } - div.SetHeight(Math.Max(0, height - heightBorder)); - IList strings = formAnnotation.GetFont().SplitString(value, fontSize, width - widthBorder); - for (int index = 0; index < strings.Count; index++) { - bool? isFull = modelCanvas.GetRenderer().GetPropertyAsBoolean(Property.FULL); - if (true.Equals(isFull)) { - break; - } - Paragraph paragraph = new Paragraph(strings[index]).SetFont(formAnnotation.GetFont()).SetFontSize(fontSize - ).SetMargins(0, 0, 0, 0).SetMultipliedLeading(1); - paragraph.SetProperty(Property.FORCED_PLACEMENT, true); - paragraph.SetTextAlignment(formAnnotation.parent.GetJustification()); - if (formAnnotation.GetColor() != null) { - paragraph.SetFontColor(formAnnotation.GetColor()); - } - if (!formAnnotation.parent.GetFieldFlag(PdfChoiceFormField.FF_COMBO)) { - PdfArray indices = formAnnotation.GetParent().GetAsArray(PdfName.I); - if (indices != null && indices.Size() > 0) { - foreach (PdfObject ind in indices) { - if (!ind.IsNumber()) { - continue; - } - if (((PdfNumber)ind).GetValue() == index + topIndex) { - paragraph.SetBackgroundColor(new DeviceRgb(10, 36, 106)); - paragraph.SetFontColor(ColorConstants.LIGHT_GRAY); - } - } - } - } - div.Add(paragraph); - } - modelCanvas.Add(div); - canvas.RestoreState().EndVariableText(); - appearance.GetPdfObject().SetData(stream.GetBytes()); - } -//\endcond - - private static void DrawCombTextAppearance(PdfFormAnnotation formAnnotation, Rectangle rect, PdfFont font, - float fontSize, String value, PdfFormXObject appearance) { - PdfStream stream = (PdfStream)new PdfStream().MakeIndirect(formAnnotation.GetDocument()); - PdfResources resources = appearance.GetResources(); - PdfCanvas canvas = new PdfCanvas(stream, resources, formAnnotation.GetDocument()); - float height = rect.GetHeight(); - float width = rect.GetWidth(); - PdfFormXObject xObject = new PdfFormXObject(new Rectangle(0, 0, width, height)); - formAnnotation.DrawBorder(canvas, xObject, width, height); - if (formAnnotation.parent.IsPassword()) { - value = ObfuscatePassword(value); - } - canvas.BeginVariableText().SaveState().EndPath(); - iText.Layout.Canvas modelCanvas = new iText.Layout.Canvas(canvas, new Rectangle(0, -height, 0, 2 * height) - ); - modelCanvas.SetProperty(Property.APPEARANCE_STREAM_LAYOUT, true); - PdfFormAnnotation.SetMetaInfoToCanvas(modelCanvas); - Style paragraphStyle = new Style().SetFont(font).SetFontSize(fontSize); - paragraphStyle.SetProperty(Property.LEADING, new Leading(Leading.MULTIPLIED, 1)); - if (formAnnotation.GetColor() != null) { - paragraphStyle.SetProperty(Property.FONT_COLOR, new TransparentColor(formAnnotation.GetColor())); - } - int maxLen = PdfFormCreator.CreateTextFormField(formAnnotation.parent.GetPdfObject()).GetMaxLen(); - // check if /Comb has been set - float widthPerCharacter = width / maxLen; - int numberOfCharacters = Math.Min(maxLen, value.Length); - int start; - TextAlignment? textAlignment = formAnnotation.parent.GetJustification() == null ? TextAlignment.LEFT : formAnnotation - .parent.GetJustification(); - switch (textAlignment) { - case TextAlignment.RIGHT: { - start = (maxLen - numberOfCharacters); - break; - } - - case TextAlignment.CENTER: { - start = (maxLen - numberOfCharacters) / 2; - break; - } - - default: { - start = 0; - break; - } - } - float startOffset = widthPerCharacter * (start + 0.5f); - for (int i = 0; i < numberOfCharacters; i++) { - modelCanvas.ShowTextAligned(new Paragraph(value.JSubstring(i, i + 1)).AddStyle(paragraphStyle), startOffset - + widthPerCharacter * i, rect.GetHeight() / 2, TextAlignment.CENTER, VerticalAlignment.MIDDLE); - } - canvas.RestoreState().EndVariableText(); - appearance.GetPdfObject().SetData(stream.GetBytes()); - } - - private static String ObfuscatePassword(String text) { - char[] pchar = new char[text.Length]; - for (int i = 0; i < text.Length; i++) { - pchar[i] = '*'; - } - return new String(pchar); - } - - private static float CalculateTranslationHeightAfterFieldRot(Rectangle bBox, double pageRotation, double relFieldRotation - ) { - if (relFieldRotation == 0) { - return 0.0f; - } - if (pageRotation == 0) { - if (relFieldRotation == Math.PI / 2) { - return bBox.GetHeight(); - } - if (relFieldRotation == Math.PI) { - return bBox.GetHeight(); - } - } - if (pageRotation == -Math.PI / 2) { - if (relFieldRotation == -Math.PI / 2) { - return bBox.GetWidth() - bBox.GetHeight(); - } - if (relFieldRotation == Math.PI / 2) { - return bBox.GetHeight(); - } - if (relFieldRotation == Math.PI) { - return bBox.GetWidth(); - } - } - if (pageRotation == -Math.PI) { - if (relFieldRotation == -1 * Math.PI) { - return bBox.GetHeight(); - } - if (relFieldRotation == -1 * Math.PI / 2) { - return bBox.GetHeight() - bBox.GetWidth(); - } - if (relFieldRotation == Math.PI / 2) { - return bBox.GetWidth(); - } - } - if (pageRotation == -3 * Math.PI / 2) { - if (relFieldRotation == -3 * Math.PI / 2) { - return bBox.GetWidth(); - } - if (relFieldRotation == -Math.PI) { - return bBox.GetWidth(); - } - } - return 0.0f; - } - - private static float CalculateTranslationWidthAfterFieldRot(Rectangle bBox, double pageRotation, double relFieldRotation - ) { - if (relFieldRotation == 0) { - return 0.0f; - } - if (pageRotation == 0 && (relFieldRotation == Math.PI || relFieldRotation == 3 * Math.PI / 2)) { - return bBox.GetWidth(); - } - if (pageRotation == -Math.PI / 2) { - if (relFieldRotation == -Math.PI / 2 || relFieldRotation == Math.PI) { - return bBox.GetHeight(); - } - } - if (pageRotation == -Math.PI) { - if (relFieldRotation == -1 * Math.PI) { - return bBox.GetWidth(); - } - if (relFieldRotation == -1 * Math.PI / 2) { - return bBox.GetHeight(); - } - if (relFieldRotation == Math.PI / 2) { - return -1 * (bBox.GetHeight() - bBox.GetWidth()); - } - } - if (pageRotation == -3 * Math.PI / 2) { - if (relFieldRotation == -3 * Math.PI / 2) { - return -1 * (bBox.GetWidth() - bBox.GetHeight()); - } - if (relFieldRotation == -Math.PI) { - return bBox.GetHeight(); - } - if (relFieldRotation == -Math.PI / 2) { - return bBox.GetWidth(); - } - } - return 0.0f; - } - - private static double DegreeToRadians(double angle) { - return Math.PI * angle / 180.0; - } - } -//\endcond -} diff --git a/itext/itext.forms/itext/forms/fields/TextFormFieldBuilder.cs b/itext/itext.forms/itext/forms/fields/TextFormFieldBuilder.cs index 52960ef595..d5fb6f3741 100644 --- a/itext/itext.forms/itext/forms/fields/TextFormFieldBuilder.cs +++ b/itext/itext.forms/itext/forms/fields/TextFormFieldBuilder.cs @@ -57,7 +57,7 @@ private PdfTextFormField CreateText(bool multiline) { } else { PdfWidgetAnnotation annotation = new PdfWidgetAnnotation(GetWidgetRectangle()); - if (null != GetGenericConformanceLevel()) { + if (null != GetConformance() && GetConformance().IsPdfAOrUa()) { annotation.SetFlag(PdfAnnotation.PRINT); } field = PdfFormCreator.CreateTextFormField(annotation, GetDocument()); @@ -67,7 +67,7 @@ private PdfTextFormField CreateText(bool multiline) { field.SetFont(GetFont()); } field.DisableFieldRegeneration(); - field.pdfConformanceLevel = GetGenericConformanceLevel(); + field.pdfConformance = GetConformance(); field.SetMultiline(multiline); field.SetFieldName(GetFormFieldName()); field.SetValue(TEXT_FORM_FIELD_DEFAULT_VALUE); diff --git a/itext/itext.forms/itext/forms/fields/properties/SignedAppearanceText.cs b/itext/itext.forms/itext/forms/fields/properties/SignedAppearanceText.cs index 6d31c79006..8e2f0337d1 100644 --- a/itext/itext.forms/itext/forms/fields/properties/SignedAppearanceText.cs +++ b/itext/itext.forms/itext/forms/fields/properties/SignedAppearanceText.cs @@ -71,7 +71,10 @@ public virtual String GetReasonLine() { /// instance. /// public virtual iText.Forms.Fields.Properties.SignedAppearanceText SetReasonLine(String reason) { - this.reason = reason.Trim(); + if (reason != null) { + reason = reason.Trim(); + } + this.reason = reason; return this; } @@ -89,14 +92,17 @@ public virtual String GetLocationLine() { /// PdfSigner#setLocation /// will be used. /// - /// new signing location. + /// new signing location /// /// this same /// - /// instance. + /// instance /// public virtual iText.Forms.Fields.Properties.SignedAppearanceText SetLocationLine(String location) { - this.location = location.Trim(); + if (location != null) { + location = location.Trim(); + } + this.location = location; return this; } @@ -106,19 +112,22 @@ public virtual iText.Forms.Fields.Properties.SignedAppearanceText SetLocationLin /// /// Note, that the signer name will be replaced by the one from the signing certificate during the actual signing. /// - /// name of the signer. + /// name of the signer /// /// this same /// - /// instance. + /// instance /// public virtual iText.Forms.Fields.Properties.SignedAppearanceText SetSignedBy(String signedBy) { - this.signedBy = signedBy.Trim(); + if (signedBy != null) { + signedBy = signedBy.Trim(); + } + this.signedBy = signedBy; return this; } /// Gets the name of the signer from the certificate. - /// signedBy name of the signer. + /// signedBy name of the signer public virtual String GetSignedBy() { return signedBy; } @@ -137,11 +146,11 @@ public virtual DateTime GetSignDate() { /// PdfSigner /// during the signing. /// - /// new signature date. + /// new signature date /// /// this same /// - /// instance. + /// instance /// public virtual iText.Forms.Fields.Properties.SignedAppearanceText SetSignDate(DateTime signDate) { this.signDate = signDate; @@ -150,7 +159,7 @@ public virtual iText.Forms.Fields.Properties.SignedAppearanceText SetSignDate(Da } /// Generates the signature description text based on the provided parameters. - /// signature description. + /// signature description public virtual String GenerateDescriptionText() { StringBuilder buf = new StringBuilder(); if (signedBy != null && !String.IsNullOrEmpty(signedBy)) { diff --git a/itext/itext.forms/itext/forms/form/FormProperty.cs b/itext/itext.forms/itext/forms/form/FormProperty.cs index b6e89f111d..01cab91ed1 100644 --- a/itext/itext.forms/itext/forms/form/FormProperty.cs +++ b/itext/itext.forms/itext/forms/form/FormProperty.cs @@ -20,8 +20,6 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ -using System; - namespace iText.Forms.Form { /// Set of constants that will be used as keys to get and set properties. public sealed class FormProperty { @@ -58,10 +56,6 @@ public sealed class FormProperty { /// The Constant FORM_FIELD_LABEL. public const int FORM_FIELD_LABEL = PROPERTY_START + 10; - /// The Constant FORM_ACCESSIBILITY_LANGUAGE. - [Obsolete] - public const int FORM_ACCESSIBILITY_LANGUAGE = PROPERTY_START + 11; - /// The Constant FORM_FIELD_RADIO_GROUP_NAME. public const int FORM_FIELD_RADIO_GROUP_NAME = PROPERTY_START + 12; @@ -74,6 +68,21 @@ public sealed class FormProperty { /// The Constant FORM_CONFORMANCE_LEVEL. public const int FORM_CONFORMANCE_LEVEL = PROPERTY_START + 15; + /// The Constant LIST_BOX_TOP_INDEX representing the index of the first visible option in a scrollable list. + /// + public const int LIST_BOX_TOP_INDEX = PROPERTY_START + 16; + + /// + /// The Constant TEXT_FIELD_COMB_FLAG representing + /// Comb + /// flag for the text field. + /// + public const int TEXT_FIELD_COMB_FLAG = PROPERTY_START + 17; + + /// The Constant TEXT_FIELD_MAX_LEN representing the maximum length of the field's text, in characters. + /// + public const int TEXT_FIELD_MAX_LEN = PROPERTY_START + 18; + private FormProperty() { } // Empty constructor. diff --git a/itext/itext.forms/itext/forms/form/element/AbstractSelectField.cs b/itext/itext.forms/itext/forms/form/element/AbstractSelectField.cs index 14f4d417d8..875351f668 100644 --- a/itext/itext.forms/itext/forms/form/element/AbstractSelectField.cs +++ b/itext/itext.forms/itext/forms/form/element/AbstractSelectField.cs @@ -23,7 +23,6 @@ You should have received a copy of the GNU Affero General Public License using System; using System.Collections.Generic; using iText.Forms.Form; -using iText.Layout.Element; namespace iText.Forms.Form.Element { /// An abstract class for fields that represents a control for selecting one or several of the provided options. @@ -41,15 +40,6 @@ protected internal AbstractSelectField(String id) : base(id) { } - /// Add a container with options. - /// Add a container with options. This might be a container for options group. - /// a container with options - [System.ObsoleteAttribute(@"starting from 8.0.1.")] - public virtual void AddOption(IBlockElement optionElement) { - String value = TryAndExtractText(optionElement); - AddOption(new SelectFieldItem(value, optionElement)); - } - /// Add an option to the element. /// /// a @@ -81,14 +71,14 @@ public virtual void AddOption(SelectFieldItem option, bool selected) { /// . /// /// a list of options. - public virtual IList GetItems() { + public virtual IList GetOptions() { return options; } /// Gets the total amount of options available. /// the number of options in the element. public virtual int OptionsCount() { - return this.GetItems().Count; + return this.GetOptions().Count; } /// Checks if the element has any options. @@ -116,19 +106,6 @@ public virtual SelectFieldItem GetOption(String value) { return null; } - /// Gets a list of containers with option(s). - /// Gets a list of containers with option(s). Every container might be a container for options group. - /// - /// a list of containers with options. - [System.ObsoleteAttribute(@"starting from 8.0.1.")] - public virtual IList GetOptions() { - IList blockElements = new List(); - foreach (SelectFieldItem option in options) { - blockElements.Add(option.GetElement()); - } - return blockElements; - } - /// Checks if the field has options with export and display values. /// /// @@ -145,23 +122,5 @@ public virtual bool HasExportAndDisplayValues() { } return false; } - - private String TryAndExtractText(IBlockElement optionElement) { - String label = optionElement.GetProperty(FormProperty.FORM_FIELD_LABEL); - if (label != null) { - return label; - } - foreach (IElement child in optionElement.GetChildren()) { - if (child is Text) { - return ((Text)child).GetText(); - } - else { - if (child is IBlockElement) { - return TryAndExtractText((IBlockElement)child); - } - } - } - return ""; - } } } diff --git a/itext/itext.forms/itext/forms/form/element/CheckBox.cs b/itext/itext.forms/itext/forms/form/element/CheckBox.cs index 4d81eafa21..aff13866aa 100644 --- a/itext/itext.forms/itext/forms/form/element/CheckBox.cs +++ b/itext/itext.forms/itext/forms/form/element/CheckBox.cs @@ -67,26 +67,11 @@ public virtual iText.Forms.Form.Element.CheckBox SetChecked(bool @checked) { return this; } - /// Sets the PDF/A conformance level for the checkbox. - /// - /// Sets the PDF/A conformance level for the checkbox. - /// This method is deprecated use setPdfConformanceLevel. - /// - /// The PDF/A conformance level to set. - /// This checkbox instance. - [Obsolete] - public virtual iText.Forms.Form.Element.CheckBox SetPdfAConformanceLevel(PdfAConformanceLevel conformanceLevel - ) { - SetProperty(FormProperty.FORM_CONFORMANCE_LEVEL, conformanceLevel); - return this; - } - - /// Sets the conformance level for the checkbox. - /// The PDF/A conformance level to set. - /// tThis checkbox instance. - public virtual iText.Forms.Form.Element.CheckBox SetPdfConformanceLevel(IConformanceLevel conformanceLevel - ) { - SetProperty(FormProperty.FORM_CONFORMANCE_LEVEL, conformanceLevel); + /// Sets the conformance for the checkbox. + /// The PDF conformance to set. + /// this checkbox instance + public virtual iText.Forms.Form.Element.CheckBox SetPdfConformance(PdfConformance conformance) { + SetProperty(FormProperty.FORM_CONFORMANCE_LEVEL, conformance); return this; } diff --git a/itext/itext.forms/itext/forms/form/element/ComboBoxField.cs b/itext/itext.forms/itext/forms/form/element/ComboBoxField.cs index c9d0762613..f86ffef005 100644 --- a/itext/itext.forms/itext/forms/form/element/ComboBoxField.cs +++ b/itext/itext.forms/itext/forms/form/element/ComboBoxField.cs @@ -61,12 +61,12 @@ public virtual String GetSelectedExportValue() { /// instance. /// public virtual iText.Forms.Form.Element.ComboBoxField SetSelected(int index) { - if (index < 0 || index >= this.GetItems().Count) { - String message = MessageFormatUtil.Format(FormsExceptionMessageConstant.INDEX_OUT_OF_BOUNDS, index, this.GetItems + if (index < 0 || index >= this.GetOptions().Count) { + String message = MessageFormatUtil.Format(FormsExceptionMessageConstant.INDEX_OUT_OF_BOUNDS, index, this.GetOptions ().Count); throw new IndexOutOfRangeException(message); } - SetSelected(this.GetItems()[index]); + SetSelected(this.GetOptions()[index]); return this; } @@ -81,7 +81,7 @@ public virtual iText.Forms.Form.Element.ComboBoxField SetSelected(String value) ClearSelected(); selectedExportValue = value; bool found = false; - foreach (SelectFieldItem option in this.GetItems()) { + foreach (SelectFieldItem option in this.GetOptions()) { if (option.GetExportValue().Equals(value)) { if (!found) { option.GetElement().SetProperty(FormProperty.FORM_FIELD_SELECTED, true); @@ -121,7 +121,7 @@ public virtual iText.Forms.Form.Element.ComboBoxField SetSelected(SelectFieldIte /// public override void AddOption(SelectFieldItem option) { bool found = false; - foreach (SelectFieldItem item in this.GetItems()) { + foreach (SelectFieldItem item in this.GetOptions()) { if (item.GetExportValue().Equals(option.GetExportValue())) { found = true; break; @@ -139,7 +139,7 @@ public virtual SelectFieldItem GetSelectedOption() { if (selectedExportValue == null) { return null; } - foreach (SelectFieldItem option in this.GetItems()) { + foreach (SelectFieldItem option in this.GetOptions()) { if (option.GetExportValue().Equals(selectedExportValue)) { return option; } @@ -162,7 +162,7 @@ protected override IRenderer MakeNewRenderer() { private void ClearSelected() { this.selectedExportValue = null; - foreach (SelectFieldItem option in this.GetItems()) { + foreach (SelectFieldItem option in this.GetOptions()) { option.GetElement().DeleteOwnProperty(FormProperty.FORM_FIELD_SELECTED); } } diff --git a/itext/itext.forms/itext/forms/form/element/IFormField.cs b/itext/itext.forms/itext/forms/form/element/IFormField.cs index 638653789a..4777f6d8cf 100644 --- a/itext/itext.forms/itext/forms/form/element/IFormField.cs +++ b/itext/itext.forms/itext/forms/form/element/IFormField.cs @@ -31,11 +31,11 @@ public interface IFormField : IBlockElement { /// /// property. /// - /// string value of the property to be set. + /// string value of the property to be set /// /// this same /// - /// instance. + /// instance /// IFormField SetValue(String value); @@ -46,34 +46,34 @@ public interface IFormField : IBlockElement { /// if the form field element shall be added into Acroform, /// /// otherwise. - /// By default, the form field element is not interactive and drawn on a page. + /// By default, the form field element is not interactive and drawn on a page /// /// /// this same /// - /// instance. + /// instance /// IFormField SetInteractive(bool interactive); /// Gets the id. - /// the id. + /// the id String GetId(); /// Set the form field's width. - /// form field's width. + /// form field's width /// /// this /// - /// element. + /// element /// IFormField SetWidth(float width); /// Set the form field's height. - /// form field's height. + /// form field's height /// /// this /// - /// element. + /// element /// IFormField SetHeight(float height); } diff --git a/itext/itext.forms/itext/forms/form/element/InputField.cs b/itext/itext.forms/itext/forms/form/element/InputField.cs index aa11303e0d..58ca5e557d 100644 --- a/itext/itext.forms/itext/forms/form/element/InputField.cs +++ b/itext/itext.forms/itext/forms/form/element/InputField.cs @@ -101,6 +101,14 @@ public override T1 GetDefaultProperty(int property) { return (T1)(Object)20; } + case FormProperty.TEXT_FIELD_COMB_FLAG: { + return (T1)(Object)false; + } + + case FormProperty.TEXT_FIELD_MAX_LEN: { + return (T1)(Object)0; + } + default: { return base.GetDefaultProperty(property); } @@ -117,11 +125,11 @@ public virtual int GetRotation() { /// /// new rotation value, counterclockwise. Must be a multiple of 90 degrees. /// It has sense only in interactive mode, see - /// . + /// /// /// /// the edited - /// . + /// /// public virtual iText.Forms.Form.Element.InputField SetRotation(int rotation) { if (rotation % 90 != 0) { @@ -131,6 +139,43 @@ public virtual iText.Forms.Form.Element.InputField SetRotation(int rotation) { return this; } + /// + /// Sets + /// Comb + /// flag for the text field. + /// + /// + /// Sets + /// Comb + /// flag for the text field. Meaningful only if the MaxLen entry is present in the text field + /// dictionary and if the Multiline, Password and FileSelect flags are clear. + /// + /// If true, the field is automatically divided into as many equally spaced positions, or combs, + /// as the value of MaxLen, and the text is laid out into those combs. + /// + /// boolean value specifying whether to enable combing + /// + /// this + /// + /// instance + /// + public virtual iText.Forms.Form.Element.InputField SetComb(bool isComb) { + SetProperty(FormProperty.TEXT_FIELD_COMB_FLAG, isComb); + return this; + } + + /// Sets the maximum length of the field's text, in characters. + /// the current maximum text length + /// + /// this + /// + /// instance + /// + public virtual iText.Forms.Form.Element.InputField SetMaxLen(int maxLen) { + SetProperty(FormProperty.TEXT_FIELD_MAX_LEN, maxLen); + return this; + } + /// public override AccessibilityProperties GetAccessibilityProperties() { if (tagProperties == null) { diff --git a/itext/itext.forms/itext/forms/form/element/ListBoxField.cs b/itext/itext.forms/itext/forms/form/element/ListBoxField.cs index 8de203c23c..691f4377f7 100644 --- a/itext/itext.forms/itext/forms/form/element/ListBoxField.cs +++ b/itext/itext.forms/itext/forms/form/element/ListBoxField.cs @@ -68,6 +68,10 @@ public override T1 GetDefaultProperty(int property) { return (T1)(Object)4; } + case FormProperty.LIST_BOX_TOP_INDEX: { + return (T1)(Object)0; + } + default: { return base.GetDefaultProperty(property); } @@ -127,6 +131,18 @@ public virtual IList GetSelectedStrings() { return selectedStrings; } + /// Sets the index of the first visible option in a scrollable list. + /// the index of the first option + /// + /// this + /// + /// instance + /// + public virtual iText.Forms.Form.Element.ListBoxField SetTopIndex(int topIndex) { + SetProperty(FormProperty.LIST_BOX_TOP_INDEX, topIndex); + return this; + } + /// public override AccessibilityProperties GetAccessibilityProperties() { if (tagProperties == null) { diff --git a/itext/itext.forms/itext/forms/form/element/SignatureFieldAppearance.cs b/itext/itext.forms/itext/forms/form/element/SignatureFieldAppearance.cs index e25b75d451..b391e2bbb0 100644 --- a/itext/itext.forms/itext/forms/form/element/SignatureFieldAppearance.cs +++ b/itext/itext.forms/itext/forms/form/element/SignatureFieldAppearance.cs @@ -62,12 +62,24 @@ public class SignatureFieldAppearance : FormField /// instance. /// - /// the id. + /// + /// signature field name if you use this + /// + /// in pure layout for the new + /// interactive signature field creation. ID will be ignored if this + /// + /// is used for signing or for existing signature field + /// public SignatureFieldAppearance(String id) : base( - // We should support signing of existing fields with dots in name. + // ID is required for the new interactive signature field creation. We can't provide parameterless constructor + + // since the user might misuse it for unintended purpose, and we have to generate a unique field name + + // that doesn't exist in the document acroform, which we don't have access to at this level. id != null && id.Contains(".") ? "" : id) { if (id.Contains(".")) { + // We should support signing of existing fields with dots in name. idWithDots = id; } // Draw the borders inside the element by default diff --git a/itext/itext.forms/itext/forms/form/element/TextArea.cs b/itext/itext.forms/itext/forms/form/element/TextArea.cs index d932492c75..62613bf043 100644 --- a/itext/itext.forms/itext/forms/form/element/TextArea.cs +++ b/itext/itext.forms/itext/forms/form/element/TextArea.cs @@ -56,27 +56,6 @@ public TextArea(String id) SetProperties(); } - /// Determines, whether the input field will be password. - /// - /// Determines, whether the input field will be password. - /// - /// Usually means that instead of glyphs '*' will be shown in case of flatten field. - /// - /// If the field is not flatten, value will be ignored. - /// - /// - /// - /// - /// is this field shall be considered as password, - /// - /// otherwise - /// - /// this input field - public virtual iText.Forms.Form.Element.TextArea UseAsPassword(bool isPassword) { - SetProperty(FormProperty.FORM_FIELD_PASSWORD_FLAG, isPassword); - return this; - } - /* (non-Javadoc) * @see FormField#getDefaultProperty(int) */ diff --git a/itext/itext.forms/itext/forms/form/renderer/AbstractFormFieldRenderer.cs b/itext/itext.forms/itext/forms/form/renderer/AbstractFormFieldRenderer.cs index 12a8f6be8b..1fde55b093 100644 --- a/itext/itext.forms/itext/forms/form/renderer/AbstractFormFieldRenderer.cs +++ b/itext/itext.forms/itext/forms/form/renderer/AbstractFormFieldRenderer.cs @@ -234,48 +234,32 @@ protected internal virtual bool IsRendererFit(float availableWidth, float availa .VISIBLE)); } - /// Gets the accessibility language. + /// + /// Gets the accessibility language using + /// . + /// /// the accessibility language. - [System.ObsoleteAttribute(@"use iText.Layout.Tagging.IAccessibleElement.GetAccessibilityProperties() instead" - )] protected internal virtual String GetLang() { String language = null; if (this.GetModelElement() is IAccessibleElement) { language = ((IAccessibleElement)this.GetModelElement()).GetAccessibilityProperties().GetLanguage(); } - if (language == null) { - language = this.GetProperty(FormProperty.FORM_ACCESSIBILITY_LANGUAGE); - } return language; } - /// Gets the conformance level. - /// Gets the conformance level. If the conformance level is not set, the conformance level of the document is used. - /// - /// the document - /// the conformance level or null if the conformance level is not set. - [System.ObsoleteAttribute(@"since 8.0.4 will return iText.Kernel.Pdf.IConformanceLevel")] - protected internal virtual PdfAConformanceLevel GetConformanceLevel(PdfDocument document) { - return PdfAConformanceLevel.GetPDFAConformance(this.GetProperty(FormProperty.FORM_CONFORMANCE_LEVEL - ), document); - } - - /// Gets the conformance level. - /// Gets the conformance level. If the conformance level is not set, the conformance level of the document is used. - /// + /// Gets the conformance. + /// Gets the conformance. If the conformance is not set, the conformance of the document is used. /// the document - /// the conformance level or null if the conformance level is not set. - [System.ObsoleteAttribute(@"since 8.0.4 will be renamed to getConformanceLevel()")] - protected internal virtual IConformanceLevel GetGenericConformanceLevel(PdfDocument document) { - IConformanceLevel conformanceLevel = this.GetProperty(FormProperty.FORM_CONFORMANCE_LEVEL - ); - if (conformanceLevel != null) { - return conformanceLevel; + /// the conformance or null if the conformance is not set. + protected internal virtual PdfConformance GetConformance(PdfDocument document) { + PdfConformance conformance = this.GetProperty(FormProperty.FORM_CONFORMANCE_LEVEL); + if (conformance != null) { + return conformance; } if (document == null) { return null; } - return document.GetConformanceLevel(); + return document.GetConformance(); } /// Determines, whether the layout is based in the renderer itself or flat renderer. diff --git a/itext/itext.forms/itext/forms/form/renderer/AbstractSelectFieldRenderer.cs b/itext/itext.forms/itext/forms/form/renderer/AbstractSelectFieldRenderer.cs index fe04df6378..6fc959a791 100644 --- a/itext/itext.forms/itext/forms/form/renderer/AbstractSelectFieldRenderer.cs +++ b/itext/itext.forms/itext/forms/form/renderer/AbstractSelectFieldRenderer.cs @@ -49,11 +49,12 @@ public abstract class AbstractSelectFieldRenderer : BlockRenderer { /// the model element protected internal AbstractSelectFieldRenderer(AbstractSelectField modelElement) : base(modelElement) { - AddChild(CreateFlatRenderer()); } /// public override LayoutResult Layout(LayoutContext layoutContext) { + childRenderers.Clear(); + AddChild(CreateFlatRenderer()); // Resolve width here in case it's relative, while parent width is still intact. // If it's inline-block context, relative width is already resolved. float? width = RetrieveWidth(layoutContext.GetArea().GetBBox().GetWidth()); @@ -122,16 +123,16 @@ public override void DrawChildren(DrawContext drawContext) { } } - /// Gets the accessibility language. + /// + /// Gets the accessibility language using + /// . + /// /// the accessibility language. protected internal virtual String GetLang() { String language = null; if (this.GetModelElement() is IAccessibleElement) { language = ((IAccessibleElement)this.GetModelElement()).GetAccessibilityProperties().GetLanguage(); } - if (language == null) { - language = this.GetProperty(FormProperty.FORM_ACCESSIBILITY_LANGUAGE); - } return language; } @@ -206,7 +207,7 @@ protected internal virtual String GetModelId() { /// protected internal virtual void SetupBuilderValues(ChoiceFormFieldBuilder builder, AbstractSelectField field ) { - IList options = field.GetItems(); + IList options = field.GetOptions(); if (options.IsEmpty()) { builder.SetOptions(new String[0]); return; @@ -252,33 +253,19 @@ protected internal virtual float GetFinalSelectFieldHeight(float availableHeight return actualHeight; } - /// Gets the conformance level. - /// Gets the conformance level. If the conformance level is not set, the conformance level of the document is used. - /// + /// Gets the conformance. + /// Gets the conformance. If the conformance is not set, the conformance of the document is used. /// the document - /// the conformance level or null if the conformance level is not set. - [System.ObsoleteAttribute(@"since 8.0.4 will be return iText.Kernel.Pdf.IConformanceLevel")] - protected internal virtual PdfAConformanceLevel GetConformanceLevel(PdfDocument document) { - return PdfAConformanceLevel.GetPDFAConformance(this.GetProperty(FormProperty.FORM_CONFORMANCE_LEVEL - ), document); - } - - /// Gets the conformance level. - /// Gets the conformance level. If the conformance level is not set, the conformance level of the document is used. - /// - /// the document - /// the conformance level or null if the conformance level is not set. - [System.ObsoleteAttribute(@"since 8.0.4 will be renamed to getConformanceLevel()")] - protected internal virtual IConformanceLevel GetGenericConformanceLevel(PdfDocument document) { - IConformanceLevel conformanceLevel = this.GetProperty(FormProperty.FORM_CONFORMANCE_LEVEL - ); - if (conformanceLevel != null) { - return conformanceLevel; + /// the conformance or null if the conformance is not set. + protected internal virtual PdfConformance GetConformance(PdfDocument document) { + PdfConformance conformance = this.GetProperty(FormProperty.FORM_CONFORMANCE_LEVEL); + if (conformance != null) { + return conformance; } if (document == null) { return null; } - return document.GetConformanceLevel(); + return document.GetConformance(); } /// Gets options that are marked as selected from the select field options subtree. diff --git a/itext/itext.forms/itext/forms/form/renderer/ButtonRenderer.cs b/itext/itext.forms/itext/forms/form/renderer/ButtonRenderer.cs index 1c1ab368b2..41269e6872 100644 --- a/itext/itext.forms/itext/forms/form/renderer/ButtonRenderer.cs +++ b/itext/itext.forms/itext/forms/form/renderer/ButtonRenderer.cs @@ -243,7 +243,7 @@ protected internal override void ApplyAcroField(DrawContext drawContext) { modelElement.SetProperty(Property.RENDERING_MODE, this.GetProperty(Property.RENDERING_MODE )); PdfButtonFormField button = new PushButtonFormFieldBuilder(doc, name).SetWidgetRectangle(area).SetFont(font - ).SetGenericConformanceLevel(GetGenericConformanceLevel(doc)).CreatePushButton(); + ).SetConformance(GetConformance(doc)).CreatePushButton(); button.DisableFieldRegeneration(); button.SetFontSize(fontSizeValue); button.GetFirstFormAnnotation().SetBackgroundColor(backgroundColor); diff --git a/itext/itext.forms/itext/forms/form/renderer/CheckBoxRenderer.cs b/itext/itext.forms/itext/forms/form/renderer/CheckBoxRenderer.cs index 64c49787a9..bb5822f132 100644 --- a/itext/itext.forms/itext/forms/form/renderer/CheckBoxRenderer.cs +++ b/itext/itext.forms/itext/forms/form/renderer/CheckBoxRenderer.cs @@ -77,15 +77,6 @@ public override IRenderer GetNextRenderer() { return RenderingMode.DEFAULT_LAYOUT_MODE; } - /// Returns whether or not the checkbox is in PDF/A mode. - /// true if the checkbox is in PDF/A mode, false otherwise - [System.ObsoleteAttribute(@"since 8.0.4 will be removed")] - public virtual bool IsPdfA() { - IConformanceLevel conformanceLevel = this.GetProperty(FormProperty.FORM_CONFORMANCE_LEVEL - ); - return conformanceLevel is PdfAConformanceLevel; - } - /// Gets the checkBoxType. /// the checkBoxType public virtual CheckBoxType GetCheckBoxType() { @@ -100,8 +91,8 @@ public virtual CheckBoxType GetCheckBoxType() { public virtual ICheckBoxRenderingStrategy CreateCheckBoxRenderStrategy() { // html rendering is PDFA compliant this means we don't have to check if its PDFA. ICheckBoxRenderingStrategy renderingStrategy; - bool isConformantPdfDocument = this.GetProperty(FormProperty.FORM_CONFORMANCE_LEVEL) != - null; + PdfConformance conformance = this.GetProperty(FormProperty.FORM_CONFORMANCE_LEVEL); + bool isConformantPdfDocument = conformance != null && conformance.IsPdfAOrUa(); if (GetRenderingMode() == RenderingMode.HTML_MODE) { renderingStrategy = new HtmlCheckBoxRenderingStrategy(); } @@ -182,7 +173,10 @@ protected internal override IRenderer CreateFlatRenderer() { paragraph.SetProperty(Property.BOX_SIZING, this.GetProperty(Property.BOX_SIZING)); modelElement.SetProperty(Property.RENDERING_MODE, this.GetProperty(Property.RENDERING_MODE )); - paragraph.SetBorder(this.GetProperty(Property.BORDER)); + paragraph.SetBorderTop(this.GetProperty(Property.BORDER_TOP)); + paragraph.SetBorderRight(this.GetProperty(Property.BORDER_RIGHT)); + paragraph.SetBorderBottom(this.GetProperty(Property.BORDER_BOTTOM)); + paragraph.SetBorderLeft(this.GetProperty(Property.BORDER_LEFT)); paragraph.SetProperty(Property.BACKGROUND, this.GetProperty(Property.BACKGROUND)); //In html 2 pdf rendering the boxes height width ratio is always 1:1 // with chrome taking the max of the two as the size of the box @@ -200,8 +194,8 @@ protected internal override void ApplyAcroField(DrawContext drawContext) { Rectangle area = flatRenderer.GetOccupiedArea().GetBBox().Clone(); IDictionary properties = FormFieldRendererUtil.RemoveProperties(this.modelElement); PdfPage page = doc.GetPage(occupiedArea.GetPageNumber()); - CheckBoxFormFieldBuilder builder = new CheckBoxFormFieldBuilder(doc, name).SetWidgetRectangle(area).SetGenericConformanceLevel - (this.GetProperty(FormProperty.FORM_CONFORMANCE_LEVEL)); + CheckBoxFormFieldBuilder builder = new CheckBoxFormFieldBuilder(doc, name).SetWidgetRectangle(area).SetConformance + (this.GetProperty(FormProperty.FORM_CONFORMANCE_LEVEL)); if (this.HasProperty(FormProperty.FORM_CHECKBOX_TYPE)) { builder.SetCheckType((CheckBoxType)this.GetProperty(FormProperty.FORM_CHECKBOX_TYPE)); } diff --git a/itext/itext.forms/itext/forms/form/renderer/InputFieldRenderer.cs b/itext/itext.forms/itext/forms/form/renderer/InputFieldRenderer.cs index ae810a4e75..d354ee7458 100644 --- a/itext/itext.forms/itext/forms/form/renderer/InputFieldRenderer.cs +++ b/itext/itext.forms/itext/forms/form/renderer/InputFieldRenderer.cs @@ -33,6 +33,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Forms.Util; using iText.Kernel.Geom; using iText.Kernel.Pdf; +using iText.Layout.Element; using iText.Layout.Font; using iText.Layout.Layout; using iText.Layout.Minmaxwidth; @@ -46,6 +47,8 @@ namespace iText.Forms.Form.Renderer { /// implementation for input fields. /// public class InputFieldRenderer : AbstractOneLineTextFieldRenderer { + private const float DEFAULT_COMB_PADDING = 0; + /// /// Creates a new /// @@ -83,7 +86,52 @@ internal override IRenderer CreateParagraphRenderer(String defaultValue) { )modelElement).GetPlaceholder().IsEmpty()) { return ((InputField)modelElement).GetPlaceholder().CreateRendererSubTree(); } - IRenderer flatRenderer = base.CreateParagraphRenderer(defaultValue); + if (String.IsNullOrEmpty(defaultValue)) { + defaultValue = "\u00a0"; + } + IRenderer flatRenderer; + if (IsComb()) { + SetProperty(Property.PADDING_LEFT, UnitValue.CreatePointValue(DEFAULT_COMB_PADDING)); + SetProperty(Property.PADDING_RIGHT, UnitValue.CreatePointValue(DEFAULT_COMB_PADDING)); + int maxLen = GetMaxLen(); + int numberOfCharacters = Math.Min(maxLen, defaultValue.Length); + int start; + TextAlignment? textAlignment = this.GetProperty(Property.TEXT_ALIGNMENT, TextAlignment.LEFT + ); + switch (textAlignment) { + case TextAlignment.RIGHT: { + start = (maxLen - numberOfCharacters); + break; + } + + case TextAlignment.CENTER: { + start = (maxLen - numberOfCharacters) / 2; + break; + } + + default: { + start = 0; + break; + } + } + Paragraph paragraph = new Paragraph(); + for (int i = 0; i < start; i++) { + paragraph.Add(GetSubParagraph("", maxLen)); + } + for (int i = 0; i < numberOfCharacters; i++) { + paragraph.Add(GetSubParagraph(defaultValue.JSubstring(i, i + 1), maxLen)); + } + for (int i = start + numberOfCharacters; i < maxLen; i++) { + paragraph.Add(GetSubParagraph("", maxLen)); + } + flatRenderer = paragraph.SetMargin(0).CreateRendererSubTree(); + } + else { + Text text = new Text(defaultValue); + FormFieldValueNonTrimmingTextRenderer nextRenderer = new FormFieldValueNonTrimmingTextRenderer(text); + text.SetNextRenderer(nextRenderer); + flatRenderer = new Paragraph(text).SetMargin(0).CreateRendererSubTree(); + } flatRenderer.SetProperty(Property.NO_SOFT_WRAP_INLINE, true); return flatRenderer; } @@ -144,17 +192,21 @@ protected internal override void ApplyAcroField(DrawContext drawContext) { // Default html2pdf input field appearance differs from the default one for form fields. // That's why we got rid of several properties we set by default during InputField instance creation. modelElement.SetProperty(Property.BOX_SIZING, BoxSizingPropertyValue.BORDER_BOX); - PdfFormField inputField = new TextFormFieldBuilder(doc, name).SetWidgetRectangle(area).SetFont(font).SetGenericConformanceLevel - (GetGenericConformanceLevel(doc)).CreateText(); + PdfTextFormField inputField = new TextFormFieldBuilder(doc, name).SetWidgetRectangle(area).SetFont(font).SetConformance + (GetConformance(doc)).CreateText(); inputField.DisableFieldRegeneration(); inputField.SetValue(value); inputField.SetFontSize(fontSizeValue); if (password) { - inputField.SetFieldFlag(PdfFormField.FF_PASSWORD, true); + inputField.SetPassword(true); } else { inputField.SetDefaultValue(new PdfString(value)); } + if (IsComb()) { + inputField.SetComb(true); + inputField.SetMaxLen(GetMaxLen()); + } int rotation = ((InputField)modelElement).GetRotation(); if (rotation != 0) { inputField.GetFirstFormAnnotation().SetRotation(rotation); @@ -213,6 +265,26 @@ protected override bool SetMinMaxWidthBasedOnFixedWidth(MinMaxWidth minMaxWidth) return result; } + private static Paragraph GetSubParagraph(String value, int maxLen) { + Text text = new Text(value); + FormFieldValueNonTrimmingTextRenderer nextRenderer = new FormFieldValueNonTrimmingTextRenderer(text); + text.SetNextRenderer(nextRenderer); + return new Paragraph(text).SetTextAlignment(TextAlignment.CENTER).SetWidth(UnitValue.CreatePercentValue((float + )100 / maxLen)).SetHeight(UnitValue.CreatePercentValue(100)).SetMargin(0); + } + + /// Checks if the input field is a comb field. + /// true, if the input field is a comb field + private bool IsComb() { + return (bool)this.GetProperty(FormProperty.TEXT_FIELD_COMB_FLAG, false); + } + + /// Gets the maximum length of the field's text, in characters. + /// the current maximum text length + private int GetMaxLen() { + return (int)this.GetProperty(FormProperty.TEXT_FIELD_MAX_LEN, 0); + } + /// Obfuscates the content of a password input field. /// the password /// a string consisting of '*' characters. diff --git a/itext/itext.forms/itext/forms/form/renderer/RadioRenderer.cs b/itext/itext.forms/itext/forms/form/renderer/RadioRenderer.cs index 05347dec2f..c276247e1c 100644 --- a/itext/itext.forms/itext/forms/form/renderer/RadioRenderer.cs +++ b/itext/itext.forms/itext/forms/form/renderer/RadioRenderer.cs @@ -125,7 +125,10 @@ protected internal override IRenderer CreateFlatRenderer() { Paragraph paragraph = new Paragraph().SetWidth(size).SetHeight(size).SetHorizontalAlignment(DEFAULT_HORIZONTAL_ALIGNMENT ).SetVerticalAlignment(DEFAULT_VERTICAL_ALIGNMENT).SetMargin(0); paragraph.SetProperty(Property.BOX_SIZING, this.GetProperty(Property.BOX_SIZING)); - paragraph.SetBorder(this.GetProperty(Property.BORDER)); + paragraph.SetBorderTop(this.GetProperty(Property.BORDER_TOP)); + paragraph.SetBorderRight(this.GetProperty(Property.BORDER_RIGHT)); + paragraph.SetBorderBottom(this.GetProperty(Property.BORDER_BOTTOM)); + paragraph.SetBorderLeft(this.GetProperty(Property.BORDER_LEFT)); paragraph.SetProperty(Property.BACKGROUND, this.GetProperty(Property.BACKGROUND)); paragraph.SetBorderRadius(new BorderRadius(UnitValue.CreatePercentValue(50))); return new RadioRenderer.FlatParagraphRenderer(this, paragraph); @@ -155,8 +158,8 @@ protected internal override void ApplyAcroField(DrawContext drawContext) { } PdfButtonFormField radioGroup = (PdfButtonFormField)form.GetField(groupName); if (null == radioGroup) { - radioGroup = new RadioFormFieldBuilder(doc, groupName).SetGenericConformanceLevel(GetGenericConformanceLevel - (doc)).CreateRadioGroup(); + radioGroup = new RadioFormFieldBuilder(doc, groupName).SetConformance(GetConformance(doc)).CreateRadioGroup + (); radioGroup.DisableFieldRegeneration(); radioGroup.SetValue(PdfFormAnnotation.OFF_STATE_VALUE); } @@ -166,8 +169,8 @@ protected internal override void ApplyAcroField(DrawContext drawContext) { if (IsBoxChecked()) { radioGroup.SetValue(GetModelId()); } - PdfFormAnnotation radio = new RadioFormFieldBuilder(doc, null).SetGenericConformanceLevel(GetGenericConformanceLevel - (doc)).CreateRadioButton(GetModelId(), area); + PdfFormAnnotation radio = new RadioFormFieldBuilder(doc, null).SetConformance(GetConformance(doc)).CreateRadioButton + (GetModelId(), area); radio.DisableFieldRegeneration(); Background background = this.GetProperty(Property.BACKGROUND); if (background != null) { @@ -209,10 +212,13 @@ public override void DrawChildren(DrawContext drawContext) { canvas.OpenTag(tp.GetTagReference()); } Rectangle rectangle = this.GetOccupiedArea().GetBBox().Clone(); - Border border = this.GetProperty(Property.BORDER); - if (border != null) { - rectangle.ApplyMargins(border.GetWidth(), border.GetWidth(), border.GetWidth(), border.GetWidth(), false); - } + Border borderTop = this.GetProperty(Property.BORDER_TOP); + Border borderRight = this.GetProperty(Property.BORDER_RIGHT); + Border borderBottom = this.GetProperty(Property.BORDER_BOTTOM); + Border borderLeft = this.GetProperty(Property.BORDER_LEFT); + rectangle.ApplyMargins(borderTop == null ? 0 : borderTop.GetWidth(), borderRight == null ? 0 : borderRight + .GetWidth(), borderBottom == null ? 0 : borderBottom.GetWidth(), borderLeft == null ? 0 : borderLeft.GetWidth + (), false); float radius = Math.Min(rectangle.GetWidth(), rectangle.GetHeight()) / 2; canvas.SaveState(); canvas.SetFillColor(RadioRenderer.DEFAULT_CHECKED_COLOR); diff --git a/itext/itext.forms/itext/forms/form/renderer/SelectFieldComboBoxRenderer.cs b/itext/itext.forms/itext/forms/form/renderer/SelectFieldComboBoxRenderer.cs index 8c494fbe9a..3bd0efc05e 100644 --- a/itext/itext.forms/itext/forms/form/renderer/SelectFieldComboBoxRenderer.cs +++ b/itext/itext.forms/itext/forms/form/renderer/SelectFieldComboBoxRenderer.cs @@ -94,7 +94,7 @@ protected internal override void ApplyAcroField(DrawContext drawContext) { PdfPage page = doc.GetPage(occupiedArea.GetPageNumber()); PdfFont font = GetResolvedFont(doc); ChoiceFormFieldBuilder builder = new ChoiceFormFieldBuilder(doc, name).SetWidgetRectangle(area).SetFont(font - ).SetGenericConformanceLevel(GetGenericConformanceLevel(doc)); + ).SetConformance(GetConformance(doc)); ApplyMargins(area, false); IDictionary properties = FormFieldRendererUtil.RemoveProperties(this.modelElement); modelElement.SetProperty(Property.FONT_PROVIDER, this.GetProperty(Property.FONT_PROVIDER)); @@ -152,7 +152,7 @@ private UnitValue GetFontSize() { private IRenderer CreateFlatRenderer(bool addAllOptionsToChildren) { AbstractSelectField selectField = (AbstractSelectField)modelElement; - IList options = selectField.GetItems(); + IList options = selectField.GetOptions(); Div pseudoContainer = new Div(); foreach (SelectFieldItem option in options) { pseudoContainer.Add(option.GetElement()); @@ -253,7 +253,7 @@ private void ProcessLangAttribute(Paragraph optionFlatElement, IRenderer origina IPropertyContainer propertyContainer = originalOptionRenderer.GetModelElement(); if (propertyContainer is IAccessibleElement) { String lang = ((IAccessibleElement)propertyContainer).GetAccessibilityProperties().GetLanguage(); - AccessibilityProperties properties = ((IAccessibleElement)optionFlatElement).GetAccessibilityProperties(); + AccessibilityProperties properties = optionFlatElement.GetAccessibilityProperties(); if (properties.GetLanguage() == null) { properties.SetLanguage(lang); } diff --git a/itext/itext.forms/itext/forms/form/renderer/SelectFieldListBoxRenderer.cs b/itext/itext.forms/itext/forms/form/renderer/SelectFieldListBoxRenderer.cs index eda94ac86d..157c545c9c 100644 --- a/itext/itext.forms/itext/forms/form/renderer/SelectFieldListBoxRenderer.cs +++ b/itext/itext.forms/itext/forms/form/renderer/SelectFieldListBoxRenderer.cs @@ -99,10 +99,12 @@ protected override bool AllowLastYLineRecursiveExtraction() { protected internal override IRenderer CreateFlatRenderer() { AbstractSelectField selectField = (AbstractSelectField)modelElement; - IList options = selectField.GetOptions(); + IList options = selectField.GetOptions(); Div optionsContainer = new Div(); - foreach (IBlockElement option in options) { - optionsContainer.Add(option); + int topIndex = (int)this.GetProperty(FormProperty.LIST_BOX_TOP_INDEX, 0); + IList visibleOptions = topIndex > 0 ? options.SubList(topIndex, options.Count) : options; + foreach (SelectFieldItem option in visibleOptions) { + optionsContainer.Add(option.GetElement()); } String lang = GetLang(); if (lang != null) { @@ -174,8 +176,8 @@ protected internal override void ApplyAcroField(DrawContext drawContext) { )); ListBoxField lbModelElement = (ListBoxField)modelElement; IList selectedOptions = lbModelElement.GetSelectedStrings(); - ChoiceFormFieldBuilder builder = new ChoiceFormFieldBuilder(doc, GetModelId()).SetGenericConformanceLevel( - GetGenericConformanceLevel(doc)).SetFont(font).SetWidgetRectangle(area); + ChoiceFormFieldBuilder builder = new ChoiceFormFieldBuilder(doc, GetModelId()).SetConformance(GetConformance + (doc)).SetFont(font).SetWidgetRectangle(area); SetupBuilderValues(builder, lbModelElement); PdfChoiceFormField choiceField = builder.CreateList(); choiceField.DisableFieldRegeneration(); @@ -183,6 +185,10 @@ protected internal override void ApplyAcroField(DrawContext drawContext) { choiceField.SetFontSize(fontSize.GetValue()); choiceField.SetMultiSelect(IsMultiple()); choiceField.SetListSelected(selectedOptions.ToArray(new String[selectedOptions.Count])); + int? topIndex = modelElement.GetOwnProperty(FormProperty.LIST_BOX_TOP_INDEX); + if (topIndex != null) { + choiceField.SetTopIndex((int)topIndex); + } TransparentColor color = GetPropertyAsTransparentColor(Property.FONT_COLOR); if (color != null) { choiceField.SetColor(color.GetColor()); @@ -270,7 +276,14 @@ private bool IsMultiple() { } private void ApplySelectedStyle(IRenderer selectedOption) { - selectedOption.SetProperty(Property.BACKGROUND, new Background(new DeviceRgb(0, 120, 215))); + RenderingMode? mode = this.GetProperty(Property.RENDERING_MODE); + if (RenderingMode.HTML_MODE.Equals(mode) && IsFlatten() && selectedOption.GetProperty(Property + .BACKGROUND) == null) { + selectedOption.SetProperty(Property.BACKGROUND, new Background(new DeviceRgb(206, 206, 206))); + } + else { + selectedOption.SetProperty(Property.BACKGROUND, new Background(new DeviceRgb(169, 204, 225))); + } SetFontColorRecursively(selectedOption); } @@ -280,7 +293,7 @@ private void ApplySelectedStyle(IRenderer selectedOption) { /// otherwise it will be not applied due to the css resolving mechanism. /// private void SetFontColorRecursively(IRenderer selectedOption) { - selectedOption.SetProperty(Property.FONT_COLOR, new TransparentColor(ColorConstants.WHITE)); + selectedOption.SetProperty(Property.FONT_COLOR, new TransparentColor(ColorConstants.BLACK)); foreach (IRenderer renderer in selectedOption.GetChildRenderers()) { SetFontColorRecursively(renderer); } diff --git a/itext/itext.forms/itext/forms/form/renderer/SignatureAppearanceRenderer.cs b/itext/itext.forms/itext/forms/form/renderer/SignatureAppearanceRenderer.cs index 1d7282f97e..5a35e9da72 100644 --- a/itext/itext.forms/itext/forms/form/renderer/SignatureAppearanceRenderer.cs +++ b/itext/itext.forms/itext/forms/form/renderer/SignatureAppearanceRenderer.cs @@ -218,8 +218,8 @@ protected internal override void ApplyAcroField(DrawContext drawContext) { modelElement.SetProperty(Property.FONT_PROVIDER, this.GetProperty(Property.FONT_PROVIDER)); modelElement.SetProperty(Property.RENDERING_MODE, this.GetProperty(Property.RENDERING_MODE)); - PdfSignatureFormField sigField = new SignatureFormFieldBuilder(doc, name).SetWidgetRectangle(area).SetGenericConformanceLevel - (GetGenericConformanceLevel(doc)).SetFont(font).CreateSignature(); + PdfSignatureFormField sigField = new SignatureFormFieldBuilder(doc, name).SetWidgetRectangle(area).SetConformance + (GetConformance(doc)).SetFont(font).CreateSignature(); sigField.DisableFieldRegeneration(); sigField.SetFontSize(fontSizeValue); sigField.GetFirstFormAnnotation().SetBackgroundColor(backgroundColor); diff --git a/itext/itext.forms/itext/forms/form/renderer/TextAreaRenderer.cs b/itext/itext.forms/itext/forms/form/renderer/TextAreaRenderer.cs index 22639cc4e5..c3aab79362 100644 --- a/itext/itext.forms/itext/forms/form/renderer/TextAreaRenderer.cs +++ b/itext/itext.forms/itext/forms/form/renderer/TextAreaRenderer.cs @@ -165,8 +165,8 @@ protected internal override void ApplyAcroField(DrawContext drawContext) { // Default html2pdf text area appearance differs from the default one for form fields. // That's why we got rid of several properties we set by default during TextArea instance creation. modelElement.SetProperty(Property.BOX_SIZING, BoxSizingPropertyValue.BORDER_BOX); - PdfFormField inputField = new TextFormFieldBuilder(doc, name).SetWidgetRectangle(area).SetGenericConformanceLevel - (GetGenericConformanceLevel(doc)).SetFont(font).CreateMultilineText(); + PdfFormField inputField = new TextFormFieldBuilder(doc, name).SetWidgetRectangle(area).SetConformance(GetConformance + (doc)).SetFont(font).CreateMultilineText(); inputField.DisableFieldRegeneration(); inputField.SetValue(value); inputField.SetFontSize(fontSizeValue); diff --git a/itext/itext.forms/itext/forms/form/renderer/checkboximpl/PdfCheckBoxRenderingStrategy.cs b/itext/itext.forms/itext/forms/form/renderer/checkboximpl/PdfCheckBoxRenderingStrategy.cs index 8ca9c1d1df..ff2e0986f9 100644 --- a/itext/itext.forms/itext/forms/form/renderer/checkboximpl/PdfCheckBoxRenderingStrategy.cs +++ b/itext/itext.forms/itext/forms/form/renderer/checkboximpl/PdfCheckBoxRenderingStrategy.cs @@ -67,12 +67,13 @@ public void DrawCheckBoxContent(DrawContext drawContext, CheckBoxRenderer checkB if (!checkBoxRenderer.IsBoxChecked()) { return; } - float borderWidth = CheckBoxRenderer.DEFAULT_BORDER_WIDTH; - Border border = checkBoxRenderer.GetProperty(Property.BORDER); - if (border != null) { - borderWidth = border.GetWidth(); - rectangle.ApplyMargins(borderWidth, borderWidth, borderWidth, borderWidth, true); - } + Border borderTop = checkBoxRenderer.GetProperty(Property.BORDER_TOP); + Border borderRight = checkBoxRenderer.GetProperty(Property.BORDER_RIGHT); + Border borderBottom = checkBoxRenderer.GetProperty(Property.BORDER_BOTTOM); + Border borderLeft = checkBoxRenderer.GetProperty(Property.BORDER_LEFT); + rectangle.ApplyMargins(borderTop == null ? 0 : borderTop.GetWidth(), borderRight == null ? 0 : borderRight + .GetWidth(), borderBottom == null ? 0 : borderBottom.GetWidth(), borderLeft == null ? 0 : borderLeft.GetWidth + (), true); PdfCanvas canvas = drawContext.GetCanvas(); canvas.SaveState(); canvas.SetFillColor(ColorConstants.BLACK); @@ -81,18 +82,40 @@ public void DrawCheckBoxContent(DrawContext drawContext, CheckBoxRenderer checkB canvas.ConcatMatrix(1, 0, 0, 1, rectangle.GetLeft(), rectangle.GetBottom()); CheckBoxType checkBoxType = checkBoxRenderer.GetCheckBoxType(); if (checkBoxType == CheckBoxType.CROSS || checkBoxType == null) { - float customBorderWidth = border == null ? 1 : borderWidth; + float customBorderWidth = RetrieveBorderWidth(1, borderTop, borderRight, borderBottom, borderLeft); DrawingUtil.DrawCross(canvas, rectangle.GetWidth(), rectangle.GetHeight(), customBorderWidth); } else { String text = ZAPFDINGBATS_CHECKBOX_MAPPING.GetByKey(checkBoxType); PdfFont fontContainingSymbols = LoadFontContainingSymbols(); - float fontSize = CalculateFontSize(checkBoxRenderer, fontContainingSymbols, text, rectangle, borderWidth); + float fontSize = CalculateFontSize(checkBoxRenderer, fontContainingSymbols, text, rectangle, RetrieveBorderWidth + (CheckBoxRenderer.DEFAULT_BORDER_WIDTH, borderTop, borderRight, borderBottom, borderLeft)); DrawZapfdingbatsIcon(fontContainingSymbols, text, fontSize, rectangle, canvas); } canvas.RestoreState(); } + private static float RetrieveBorderWidth(float defaultWidth, Border borderTop, Border borderRight, Border + borderBottom, Border borderLeft) { + if (borderTop == null && borderRight == null && borderBottom == null && borderLeft == null) { + return defaultWidth; + } + float borderWidth = 0; + if (borderTop != null) { + borderWidth = Math.Max(borderWidth, borderTop.GetWidth()); + } + if (borderRight != null) { + borderWidth = Math.Max(borderWidth, borderRight.GetWidth()); + } + if (borderBottom != null) { + borderWidth = Math.Max(borderWidth, borderBottom.GetWidth()); + } + if (borderLeft != null) { + borderWidth = Math.Max(borderWidth, borderLeft.GetWidth()); + } + return borderWidth; + } + private PdfFont LoadFontContainingSymbols() { try { return PdfFontFactory.CreateFont(StandardFonts.ZAPFDINGBATS); diff --git a/itext/itext.forms/itext/forms/util/BorderStyleUtil.cs b/itext/itext.forms/itext/forms/util/BorderStyleUtil.cs index 12403d087b..64b8fd38cb 100644 --- a/itext/itext.forms/itext/forms/util/BorderStyleUtil.cs +++ b/itext/itext.forms/itext/forms/util/BorderStyleUtil.cs @@ -38,11 +38,8 @@ public sealed class BorderStyleUtil { /// property container to apply border properties from. /// the annotation to set border characteristics to. public static void ApplyBorderProperty(IPropertyContainer container, PdfFormAnnotation annotation) { - Border border = container.GetProperty(Property.BORDER); - if (border == null) { - // For now, we set left border to an annotation, but appropriate borders for an element will be drawn. - border = container.GetProperty(Property.BORDER_LEFT); - } + // For now, we set left border to an annotation, but appropriate borders for an element will be drawn. + Border border = container.GetProperty(Property.BORDER_LEFT); if (border != null) { annotation.SetBorderStyle(TransformBorderTypeToBorderStyleDictionary(border.GetBorderType())); annotation.SetBorderColor(border.GetColor()); diff --git a/itext/itext.hyph/Properties/AssemblyInfo.cs b/itext/itext.hyph/Properties/AssemblyInfo.cs index 0a8181a072..dbe3d8d00f 100644 --- a/itext/itext.hyph/Properties/AssemblyInfo.cs +++ b/itext/itext.hyph/Properties/AssemblyInfo.cs @@ -15,6 +15,6 @@ [assembly: Guid("56137079-541a-425a-ab97-43af63793c97")] -[assembly: AssemblyVersion("8.0.5.0")] -[assembly: AssemblyFileVersion("8.0.5.0")] -[assembly: AssemblyInformationalVersion("8.0.5")] +[assembly: AssemblyVersion("9.0.0.0")] +[assembly: AssemblyFileVersion("9.0.0.0")] +[assembly: AssemblyInformationalVersion("9.0.0")] diff --git a/itext/itext.hyph/iText Hyph.nuspec b/itext/itext.hyph/iText Hyph.nuspec index b68a18b466..98621a8e61 100644 --- a/itext/itext.hyph/iText Hyph.nuspec +++ b/itext/itext.hyph/iText Hyph.nuspec @@ -2,7 +2,7 @@ itext.hyph - 8.0.5 + 9.0.0 iText Hyph Apryse Software Apryse Software diff --git a/itext/itext.io/Properties/AssemblyInfo.cs b/itext/itext.io/Properties/AssemblyInfo.cs index abff6474fd..012a1ad3f4 100644 --- a/itext/itext.io/Properties/AssemblyInfo.cs +++ b/itext/itext.io/Properties/AssemblyInfo.cs @@ -35,6 +35,6 @@ [assembly: Guid("39631ecb-1d39-4eb2-b775-37bd34cbf5a4")] -[assembly: AssemblyVersion("8.0.5.0")] -[assembly: AssemblyFileVersion("8.0.5.0")] -[assembly: AssemblyInformationalVersion("8.0.5")] +[assembly: AssemblyVersion("9.0.0.0")] +[assembly: AssemblyFileVersion("9.0.0.0")] +[assembly: AssemblyInformationalVersion("9.0.0")] diff --git a/itext/itext.io/itext/io/codec/Jbig2SegmentReader.cs b/itext/itext.io/itext/io/codec/Jbig2SegmentReader.cs index 16d04dd9ce..555cc747c8 100644 --- a/itext/itext.io/itext/io/codec/Jbig2SegmentReader.cs +++ b/itext/itext.io/itext/io/codec/Jbig2SegmentReader.cs @@ -128,29 +128,29 @@ public class Jbig2SegmentReader { /// Inner class that holds information about a JBIG2 segment. public class Jbig2Segment : IComparable { - public readonly int segmentNumber; + private readonly int segmentNumber; - public long dataLength = -1; + private long dataLength = -1; - public int page = -1; + private int page = -1; - public int[] referredToSegmentNumbers = null; + private int[] referredToSegmentNumbers = null; - public bool[] segmentRetentionFlags = null; + private bool[] segmentRetentionFlags = null; - public int type = -1; + private int type = -1; - public bool deferredNonRetain = false; + private bool deferredNonRetain = false; - public int countOfReferredToSegments = -1; + private int countOfReferredToSegments = -1; - public byte[] data = null; + private byte[] data = null; - public byte[] headerData = null; + private byte[] headerData = null; - public bool page_association_size = false; + private bool pageAssociationSize = false; - public int page_association_offset = -1; + private int pageAssociationOffset = -1; public Jbig2Segment(int segment_number) { this.segmentNumber = segment_number; @@ -159,26 +159,198 @@ public Jbig2Segment(int segment_number) { public virtual int CompareTo(Jbig2SegmentReader.Jbig2Segment s) { return this.segmentNumber - s.segmentNumber; } + + /// Retrieves the data length of a JBig2Segment object. + /// data length value + public virtual long GetDataLength() { + return dataLength; + } + + /// Sets the data length of a JBig2Segment object. + /// data length value + public virtual void SetDataLength(long dataLength) { + this.dataLength = dataLength; + } + + /// Retrieves the page number of a JBig2Segment object. + /// page number + public virtual int GetPage() { + return page; + } + + /// Sets the page number of a JBig2Segment object. + /// page number + public virtual void SetPage(int page) { + this.page = page; + } + + /// Retrieves the referred-to segment numbers of a JBig2Segment object. + /// Every referred-to segment number + public virtual int[] GetReferredToSegmentNumbers() { + return referredToSegmentNumbers; + } + + /// Sets the referred-to segment numbers of a JBig2Segment object. + /// Referred-to segment numbers + public virtual void SetReferredToSegmentNumbers(int[] referredToSegmentNumbers) { + this.referredToSegmentNumbers = referredToSegmentNumbers; + } + + /// Retrieves segment retention flags of a JBig2Segment object. + /// Every segment retention flag value + public virtual bool[] GetSegmentRetentionFlags() { + return segmentRetentionFlags; + } + + /// Sets segment retention flags of a JBig2Segment object. + /// Segment retention flag values + public virtual void SetSegmentRetentionFlags(bool[] segmentRetentionFlags) { + this.segmentRetentionFlags = segmentRetentionFlags; + } + + /// Retrieves type of the JBig2Segment object. + /// Type value + public virtual int GetType() { + return type; + } + + /// Sets type of the JBig2Segment object. + /// Type value + public virtual void SetType(int type) { + this.type = type; + } + + /// Retrieves whether the object is deferred without retention. + /// + /// Retrieves whether the object is deferred without retention. + /// Default value is false. + /// + /// true if deferred without retention, false otherwise + public virtual bool IsDeferredNonRetain() { + return deferredNonRetain; + } + + /// Sets whether the JBig2Segments object is deferred without retention. + /// true for deferred without retention, false otherwise + public virtual void SetDeferredNonRetain(bool deferredNonRetain) { + this.deferredNonRetain = deferredNonRetain; + } + + /// Retrieves the count of the referred-to segments. + /// count of referred-to segments + public virtual int GetCountOfReferredToSegments() { + return countOfReferredToSegments; + } + + /// Sets the count of referred-to segments of the JBig2Segment object. + /// count of referred segments + public virtual void SetCountOfReferredToSegments(int countOfReferredToSegments) { + this.countOfReferredToSegments = countOfReferredToSegments; + } + + /// Retrieves data of the JBig2Segment object. + /// data bytes + public virtual byte[] GetData() { + return data; + } + + /// Sets data of the JBig2Segment object. + /// data bytes + public virtual void SetData(byte[] data) { + this.data = data; + } + + /// Retrieves header data of the JBig2Segment object. + /// header data bytes + public virtual byte[] GetHeaderData() { + return headerData; + } + + /// Sets header data of the JBig2Segment object. + /// header date bytes + public virtual void SetHeaderData(byte[] headerData) { + this.headerData = headerData; + } + + /// Retrieves page association size of the JBig2Segment object. + /// page association size value + public virtual bool IsPageAssociationSize() { + return pageAssociationSize; + } + + /// Sets page association size of the JBig2Segment object. + /// page association size + public virtual void SetPageAssociationSize(bool pageAssociationSize) { + this.pageAssociationSize = pageAssociationSize; + } + + /// Retrieves the page association offset of the JBig2Segment object. + /// page association offset value + public virtual int GetPageAssociationOffset() { + return pageAssociationOffset; + } + + /// Sets page association offset of the JBig2Segment object. + /// page association offset + public virtual void SetPageAssociationOffset(int pageAssociationOffset) { + this.pageAssociationOffset = pageAssociationOffset; + } + + /// Retrieves the segment number of the JBig2Segment object. + /// segment number + public virtual int GetSegmentNumber() { + return segmentNumber; + } } /// Inner class that holds information about a JBIG2 page. public class Jbig2Page { - public readonly int page; + private readonly int page; private readonly Jbig2SegmentReader sr; private readonly IDictionary segs = new SortedDictionary(); - public int pageBitmapWidth = -1; + private int pageBitmapWidth = -1; - public int pageBitmapHeight = -1; + private int pageBitmapHeight = -1; public Jbig2Page(int page, Jbig2SegmentReader sr) { this.page = page; this.sr = sr; } + /// Retrieves the page number of the Jbig2Page object. + /// page number + public virtual int GetPage() { + return page; + } + + /// Retrieves page bitmap width of the Jbig2Page object. + /// width of page bitmap + public virtual int GetPageBitmapWidth() { + return pageBitmapWidth; + } + + /// Sets page bitmap width of the JBig2Page object. + /// page bitmap width + public virtual void SetPageBitmapWidth(int pageBitmapWidth) { + this.pageBitmapWidth = pageBitmapWidth; + } + + /// Retrieves page bitmap height of the JBig2Page object. + /// height of the page bitmap + public virtual int GetPageBitmapHeight() { + return pageBitmapHeight; + } + + /// Sets the height of the page bitmap of a Jbig2Page object. + /// height of the page bitmap + public virtual void SetPageBitmapHeight(int pageBitmapHeight) { + this.pageBitmapHeight = pageBitmapHeight; + } + /// /// return as a single byte array the header-data for each segment in segment number /// order, EMBEDDED organization, but I am putting the needed segments in SEQUENTIAL organization. @@ -196,34 +368,34 @@ public virtual byte[] GetData(bool for_embedding) { Jbig2SegmentReader.Jbig2Segment s = segs.Get(sn); // pdf reference 1.4, section 3.3.6 Jbig2Decode Filter // D.3 Embedded organisation - if (for_embedding && (s.type == END_OF_FILE || s.type == END_OF_PAGE)) { + if (for_embedding && (s.GetType() == END_OF_FILE || s.GetType() == END_OF_PAGE)) { continue; } if (for_embedding) { // change the page association to page 1 - byte[] headerData_emb = CopyByteArray(s.headerData); - if (s.page_association_size) { - headerData_emb[s.page_association_offset] = 0x0; - headerData_emb[s.page_association_offset + 1] = 0x0; - headerData_emb[s.page_association_offset + 2] = 0x0; - headerData_emb[s.page_association_offset + 3] = 0x1; + byte[] headerDataEmb = CopyByteArray(s.GetHeaderData()); + if (s.IsPageAssociationSize()) { + headerDataEmb[s.GetPageAssociationOffset()] = 0x0; + headerDataEmb[s.GetPageAssociationOffset() + 1] = 0x0; + headerDataEmb[s.GetPageAssociationOffset() + 2] = 0x0; + headerDataEmb[s.GetPageAssociationOffset() + 3] = 0x1; } else { - headerData_emb[s.page_association_offset] = 0x1; + headerDataEmb[s.GetPageAssociationOffset()] = 0x1; } - os.Write(headerData_emb); + os.Write(headerDataEmb); } else { - os.Write(s.headerData); + os.Write(s.GetHeaderData()); } - os.Write(s.data); + os.Write(s.GetData()); } os.Dispose(); return os.ToArray(); } public virtual void AddSegment(Jbig2SegmentReader.Jbig2Segment s) { - segs.Put(s.segmentNumber, s); + segs.Put(s.GetSegmentNumber(), s); } } @@ -249,7 +421,7 @@ public virtual void Read() { do { Jbig2SegmentReader.Jbig2Segment tmp = ReadHeader(); ReadSegment(tmp); - segments.Put(tmp.segmentNumber, tmp); + segments.Put(tmp.GetSegmentNumber(), tmp); } while (this.ra.GetPosition() < this.ra.Length()); } @@ -258,9 +430,9 @@ public virtual void Read() { Jbig2SegmentReader.Jbig2Segment tmp; do { tmp = ReadHeader(); - segments.Put(tmp.segmentNumber, tmp); + segments.Put(tmp.GetSegmentNumber(), tmp); } - while (tmp.type != END_OF_FILE); + while (tmp.GetType() != END_OF_FILE); foreach (int integer in segments.Keys) { ReadSegment(segments.Get(integer)); } @@ -271,25 +443,25 @@ public virtual void Read() { internal virtual void ReadSegment(Jbig2SegmentReader.Jbig2Segment s) { int ptr = (int)ra.GetPosition(); //TODO DEVSIX-6406 7.2.7 not supported - if (s.dataLength == unchecked((long)(0xffffffffl))) { + if (s.GetDataLength() == unchecked((long)(0xffffffffl))) { return; } - byte[] data = new byte[(int)s.dataLength]; + byte[] data = new byte[(int)s.GetDataLength()]; ra.Read(data); - s.data = data; - if (s.type == PAGE_INFORMATION) { + s.SetData(data); + if (s.GetType() == PAGE_INFORMATION) { int last = (int)ra.GetPosition(); ra.Seek(ptr); int page_bitmap_width = ra.ReadInt(); int page_bitmap_height = ra.ReadInt(); ra.Seek(last); - Jbig2SegmentReader.Jbig2Page p = pages.Get(s.page); + Jbig2SegmentReader.Jbig2Page p = pages.Get(s.GetPage()); if (p == null) { throw new iText.IO.Exceptions.IOException("Referring to widht or height of a page we haven't seen yet: {0}" - ).SetMessageParams(s.page); + ).SetMessageParams(s.GetPage()); } - p.pageBitmapWidth = page_bitmap_width; - p.pageBitmapHeight = page_bitmap_height; + p.SetPageBitmapWidth(page_bitmap_width); + p.SetPageBitmapHeight(page_bitmap_height); } } //\endcond @@ -303,10 +475,10 @@ internal virtual Jbig2SegmentReader.Jbig2Segment ReadHeader() { // 7.2.3 int segment_header_flags = ra.Read(); bool deferred_non_retain = (segment_header_flags & 0x80) == 0x80; - s.deferredNonRetain = deferred_non_retain; + s.SetDeferredNonRetain(deferred_non_retain); bool page_association_size = (segment_header_flags & 0x40) == 0x40; int segment_type = segment_header_flags & 0x3f; - s.type = segment_type; + s.SetType(segment_type); //7.2.4 int referred_to_byte0 = ra.Read(); int count_of_referred_to_segments = (referred_to_byte0 & 0xE0) >> 5; @@ -345,8 +517,8 @@ internal virtual Jbig2SegmentReader.Jbig2Segment ReadHeader() { } } } - s.segmentRetentionFlags = segment_retention_flags; - s.countOfReferredToSegments = count_of_referred_to_segments; + s.SetSegmentRetentionFlags(segment_retention_flags); + s.SetCountOfReferredToSegments(count_of_referred_to_segments); // 7.2.5 referred_to_segment_numbers = new int[count_of_referred_to_segments + 1]; for (int i = 1; i <= count_of_referred_to_segments; i++) { @@ -362,7 +534,7 @@ internal virtual Jbig2SegmentReader.Jbig2Segment ReadHeader() { } } } - s.referredToSegmentNumbers = referred_to_segment_numbers; + s.SetReferredToSegmentNumbers(referred_to_segment_numbers); // 7.2.6 int segment_page_association; int page_association_offset = (int)ra.GetPosition() - ptr; @@ -376,10 +548,10 @@ internal virtual Jbig2SegmentReader.Jbig2Segment ReadHeader() { throw new iText.IO.Exceptions.IOException("Page {0} is invalid for segment {1} starting at {2}").SetMessageParams (segment_page_association, segment_number, ptr); } - s.page = segment_page_association; + s.SetPage(segment_page_association); // so we can change the page association at embedding time. - s.page_association_size = page_association_size; - s.page_association_offset = page_association_offset; + s.SetPageAssociationSize(page_association_size); + s.SetPageAssociationOffset(page_association_offset); if (segment_page_association > 0 && !pages.ContainsKey(segment_page_association)) { pages.Put(segment_page_association, new Jbig2SegmentReader.Jbig2Page(segment_page_association, this)); } @@ -392,12 +564,12 @@ internal virtual Jbig2SegmentReader.Jbig2Segment ReadHeader() { // 7.2.7 long segment_data_length = ra.ReadUnsignedInt(); //TODO DEVSIX-6406 the 0xffffffff value that might be here, and how to understand those afflicted segments - s.dataLength = segment_data_length; + s.SetDataLength(segment_data_length); int end_ptr = (int)ra.GetPosition(); ra.Seek(ptr); byte[] header_data = new byte[end_ptr - ptr]; ra.Read(header_data); - s.headerData = header_data; + s.SetHeaderData(header_data); return s; } //\endcond @@ -431,11 +603,11 @@ public virtual int NumberOfPages() { } public virtual int GetPageHeight(int i) { - return pages.Get(i).pageBitmapHeight; + return pages.Get(i).GetPageBitmapHeight(); } public virtual int GetPageWidth(int i) { - return pages.Get(i).pageBitmapWidth; + return pages.Get(i).GetPageBitmapWidth(); } public virtual Jbig2SegmentReader.Jbig2Page GetPage(int page) { @@ -448,11 +620,11 @@ public virtual byte[] GetGlobal(bool for_embedding) { try { foreach (Object element in globals) { Jbig2SegmentReader.Jbig2Segment s = (Jbig2SegmentReader.Jbig2Segment)element; - if (for_embedding && (s.type == END_OF_FILE || s.type == END_OF_PAGE)) { + if (for_embedding && (s.GetType() == END_OF_FILE || s.GetType() == END_OF_PAGE)) { continue; } - os.Write(s.headerData); - os.Write(s.data); + os.Write(s.GetHeaderData()); + os.Write(s.GetData()); } if (os.Length > 0) { streamBytes = os.ToArray(); diff --git a/itext/itext.io/itext/io/font/CFFFont.cs b/itext/itext.io/itext/io/font/CFFFont.cs index a72de44734..5fe213d724 100644 --- a/itext/itext.io/itext/io/font/CFFFont.cs +++ b/itext/itext.io/itext/io/font/CFFFont.cs @@ -365,7 +365,13 @@ public virtual void Xref() { } protected internal abstract class OffsetItem : CFFFont.Item { - public int value; + private int offset; + + /// Retrieves offset of an OffsetItem object. + /// offset value + public virtual int GetOffset() { + return offset; + } /// Set the value of an offset item that was initially unknown. /// @@ -373,18 +379,18 @@ protected internal abstract class OffsetItem : CFFFont.Item { /// It will be fixed up latex by a call to xref on some marker. /// /// offset to set - public virtual void Set(int offset) { - this.value = offset; + public virtual void SetOffset(int offset) { + this.offset = offset; } } /// A range item. protected internal sealed class RangeItem : CFFFont.Item { - public int offset; + private readonly int offset; - public int length; + private readonly int length; - private RandomAccessFileOrArray buf; + private readonly RandomAccessFileOrArray buf; public RangeItem(RandomAccessFileOrArray buf, int offset, int length) { this.offset = offset; @@ -421,11 +427,11 @@ public override void Emit(byte[] buffer) { /// variable-size representation. /// protected internal sealed class IndexOffsetItem : CFFFont.OffsetItem { - public readonly int size; + private readonly int size; public IndexOffsetItem(int size, int value) { this.size = size; - this.value = value; + this.SetOffset(value); } public IndexOffsetItem(int size) { @@ -440,7 +446,7 @@ public override void Increment(int[] currentOffset) { public override void Emit(byte[] buffer) { if (size >= 1 && size <= 4) { for (int i = 0; i < size; i++) { - buffer[myOffset + i] = (byte)((int)(((uint)value) >> ((size - 1 - i) << 3)) & 0xFF); + buffer[myOffset + i] = (byte)((int)(((uint)base.GetOffset()) >> ((size - 1 - i) << 3)) & 0xFF); } } } @@ -452,9 +458,9 @@ public IndexBaseItem() { } protected internal sealed class IndexMarkerItem : CFFFont.Item { - private CFFFont.OffsetItem offItem; + private readonly CFFFont.OffsetItem offItem; - private CFFFont.IndexBaseItem indexBase; + private readonly CFFFont.IndexBaseItem indexBase; public IndexMarkerItem(CFFFont.OffsetItem offItem, CFFFont.IndexBaseItem indexBase) { this.offItem = offItem; @@ -463,14 +469,14 @@ public IndexMarkerItem(CFFFont.OffsetItem offItem, CFFFont.IndexBaseItem indexBa public override void Xref() { //System.err.println("index marker item, base="+indexBase.myOffset+" my="+this.myOffset); - offItem.Set(this.myOffset - indexBase.myOffset + 1); + offItem.SetOffset(this.myOffset - indexBase.myOffset + 1); } } protected internal sealed class SubrMarkerItem : CFFFont.Item { - private CFFFont.OffsetItem offItem; + private readonly CFFFont.OffsetItem offItem; - private CFFFont.IndexBaseItem indexBase; + private readonly CFFFont.IndexBaseItem indexBase; public SubrMarkerItem(CFFFont.OffsetItem offItem, CFFFont.IndexBaseItem indexBase) { this.offItem = offItem; @@ -479,7 +485,7 @@ public SubrMarkerItem(CFFFont.OffsetItem offItem, CFFFont.IndexBaseItem indexBas public override void Xref() { //System.err.println("index marker item, base="+indexBase.myOffset+" my="+this.myOffset); - offItem.Set(this.myOffset - indexBase.myOffset); + offItem.SetOffset(this.myOffset - indexBase.myOffset); } } @@ -504,17 +510,17 @@ public override void Increment(int[] currentOffset) { public override void Emit(byte[] buffer) { if (size == 5) { buffer[myOffset] = 29; - buffer[myOffset + 1] = (byte)((int)(((uint)value) >> 24) & 0xff); - buffer[myOffset + 2] = (byte)((int)(((uint)value) >> 16) & 0xff); - buffer[myOffset + 3] = (byte)((int)(((uint)value) >> 8) & 0xff); - buffer[myOffset + 4] = (byte)((int)(((uint)value) >> 0) & 0xff); + buffer[myOffset + 1] = (byte)((int)(((uint)base.GetOffset()) >> 24) & 0xff); + buffer[myOffset + 2] = (byte)((int)(((uint)base.GetOffset()) >> 16) & 0xff); + buffer[myOffset + 3] = (byte)((int)(((uint)base.GetOffset()) >> 8) & 0xff); + buffer[myOffset + 4] = (byte)((int)(((uint)base.GetOffset()) >> 0) & 0xff); } } } /// Card24 item. protected internal sealed class UInt24Item : CFFFont.Item { - public int value; + private readonly int value; public UInt24Item(int value) { this.value = value; @@ -535,7 +541,7 @@ public override void Emit(byte[] buffer) { /// Card32 item. protected internal sealed class UInt32Item : CFFFont.Item { - public int value; + private readonly int value; public UInt32Item(int value) { this.value = value; @@ -557,7 +563,7 @@ public override void Emit(byte[] buffer) { /// A SID or Card16 item. protected internal sealed class UInt16Item : CFFFont.Item { - public char value; + private readonly char value; public UInt16Item(char value) { this.value = value; @@ -580,7 +586,7 @@ public override void Emit(byte[] buffer) { /// A Card8 item. protected internal sealed class UInt8Item : CFFFont.Item { - public char value; + private readonly char value; public UInt8Item(char value) { this.value = value; @@ -599,7 +605,7 @@ public override void Emit(byte[] buffer) { } protected internal sealed class StringItem : CFFFont.Item { - public String s; + private readonly String s; public StringItem(String s) { this.s = s; @@ -624,14 +630,26 @@ public override void Emit(byte[] buffer) { /// representation. /// protected internal sealed class DictNumberItem : CFFFont.Item { - public readonly int value; + private readonly int value; - public int size = 5; + private int size = 5; public DictNumberItem(int value) { this.value = value; } + /// Retrieves the size of a DictNumberItem. + /// size value + public int GetSize() { + return size; + } + + /// Sets the size of a DictNumberItem. + /// size value + public void SetSize(int size) { + this.size = size; + } + public override void Increment(int[] currentOffset) { base.Increment(currentOffset); currentOffset[0] += size; @@ -664,7 +682,7 @@ public MarkerItem(CFFFont.OffsetItem pointerToMarker) { } public override void Xref() { - p.Set(this.myOffset); + p.SetOffset(this.myOffset); } } @@ -702,7 +720,7 @@ public virtual byte[] GetCID(String fontName) { //throws java.io.FileNotFoundException int j; for (j = 0; j < fonts.Length; j++) { - if (fontName.Equals(fonts[j].name)) { + if (fontName.Equals(fonts[j].GetName())) { break; } } @@ -719,9 +737,9 @@ public virtual byte[] GetCID(String fontName) { l.AddLast(new CFFFont.RangeItem(buf, 0, hdrSize)); int nglyphs = -1; int nstrings = -1; - if (!fonts[j].isCID) { + if (!fonts[j].IsCID()) { // count the glyphs - Seek(fonts[j].charstringsOffset); + Seek(fonts[j].GetCharstringsOffset()); nglyphs = GetCard16(); Seek(stringIndexOffset); nstrings = GetCard16() + standardStrings.Length; @@ -734,8 +752,8 @@ public virtual byte[] GetCID(String fontName) { l.AddLast(new CFFFont.UInt8Item((char)1)); // first offset l.AddLast(new CFFFont.UInt8Item((char)1)); - l.AddLast(new CFFFont.UInt8Item((char)(1 + fonts[j].name.Length))); - l.AddLast(new CFFFont.StringItem(fonts[j].name)); + l.AddLast(new CFFFont.UInt8Item((char)(1 + fonts[j].GetName().Length))); + l.AddLast(new CFFFont.StringItem(fonts[j].GetName())); // create the topdict Index // count l.AddLast(new CFFFont.UInt16Item((char)1)); @@ -759,7 +777,7 @@ public virtual byte[] GetCID(String fontName) { CFFFont.OffsetItem charstringsRef = new CFFFont.DictOffsetItem(); CFFFont.OffsetItem fdarrayRef = new CFFFont.DictOffsetItem(); CFFFont.OffsetItem fdselectRef = new CFFFont.DictOffsetItem(); - if (!fonts[j].isCID) { + if (!fonts[j].IsCID()) { // create a ROS key l.AddLast(new CFFFont.DictNumberItem(nstrings)); l.AddLast(new CFFFont.DictNumberItem(nstrings + 1)); @@ -804,11 +822,11 @@ public virtual byte[] GetCID(String fontName) { // Copy the string index and append new strings. // We need 3 more strings: Registry, Ordering, and a FontName for one FD. // The total length is at most "Adobe"+"Identity"+63 = 76 - if (fonts[j].isCID) { + if (fonts[j].IsCID()) { l.AddLast(GetEntireIndexRange(stringIndexOffset)); } else { - String fdFontName = fonts[j].name + "-OneRange"; + String fdFontName = fonts[j].GetName() + "-OneRange"; if (fdFontName.Length > 127) { fdFontName = fdFontName.JSubstring(0, 127); } @@ -853,7 +871,7 @@ public virtual byte[] GetCID(String fontName) { // copy the global subroutine index l.AddLast(GetEntireIndexRange(gsubrIndexOffset)); // deal with fdarray, fdselect, and the font descriptors - if (fonts[j].isCID) { + if (fonts[j].IsCID()) { } else { // copy the FDArray, FDSelect, charset @@ -896,7 +914,7 @@ public virtual byte[] GetCID(String fontName) { //l.addLast(new DictNumberItem((standardStrings.length+(stringOffsets.length-1)+2))); //l.addLast(new UInt8Item((char)12)); //l.addLast(new UInt8Item((char)38)); // FontName - l.AddLast(new CFFFont.DictNumberItem(fonts[j].privateLength)); + l.AddLast(new CFFFont.DictNumberItem(fonts[j].GetPrivateLength())); CFFFont.OffsetItem privateRef = new CFFFont.DictOffsetItem(); l.AddLast(privateRef); // Private @@ -907,15 +925,15 @@ public virtual byte[] GetCID(String fontName) { // copy the private dict and the local subroutines. // the length of the private dict seems to NOT include // the local subroutines. - l.AddLast(new CFFFont.RangeItem(buf, fonts[j].privateOffset, fonts[j].privateLength)); - if (fonts[j].privateSubrs >= 0) { + l.AddLast(new CFFFont.RangeItem(buf, fonts[j].GetPrivateOffset(), fonts[j].GetPrivateLength())); + if (fonts[j].GetPrivateSubrs() >= 0) { //System.err.println("has subrs="+fonts[j].privateSubrs+" ,len="+fonts[j].privateLength); - l.AddLast(GetEntireIndexRange(fonts[j].privateSubrs)); + l.AddLast(GetEntireIndexRange(fonts[j].GetPrivateSubrs())); } } // copy the charstring index l.AddLast(new CFFFont.MarkerItem(charstringsRef)); - l.AddLast(GetEntireIndexRange(fonts[j].charstringsOffset)); + l.AddLast(GetEntireIndexRange(fonts[j].GetCharstringsOffset())); // now create the new CFF font int[] currentOffset = new int[1]; currentOffset[0] = 0; @@ -940,8 +958,8 @@ public virtual bool IsCID() { public virtual bool IsCID(String fontName) { int j; for (j = 0; j < fonts.Length; j++) { - if (fontName.Equals(fonts[j].name)) { - return fonts[j].isCID; + if (fontName.Equals(fonts[j].GetName())) { + return fonts[j].IsCID(); } } return false; @@ -950,7 +968,7 @@ public virtual bool IsCID(String fontName) { public virtual bool Exists(String fontName) { int j; for (j = 0; j < fonts.Length; j++) { - if (fontName.Equals(fonts[j].name)) { + if (fontName.Equals(fonts[j].GetName())) { return true; } } @@ -960,7 +978,7 @@ public virtual bool Exists(String fontName) { public virtual String[] GetNames() { String[] names = new String[fonts.Length]; for (int i = 0; i < fonts.Length; i++) { - names[i] = fonts[i].name; + names[i] = fonts[i].GetName(); } return names; } @@ -968,7 +986,7 @@ public virtual String[] GetNames() { /// A random Access File or an array protected internal RandomAccessFileOrArray buf; - private int offSize; + private readonly int offSize; protected internal int nameIndexOffset; @@ -987,70 +1005,430 @@ public virtual String[] GetNames() { protected internal int[] gsubrOffsets; protected internal sealed class Font { - public String name; + private String name; - public String fullName; + private String fullName; - public bool isCID = false; + private bool isCID = false; // only if not CID - public int privateOffset = -1; + private int privateOffset = -1; // only if not CID - public int privateLength = -1; + private int privateLength = -1; - public int privateSubrs = -1; + private int privateSubrs = -1; - public int charstringsOffset = -1; + private int charstringsOffset = -1; - public int encodingOffset = -1; + private int encodingOffset = -1; - public int charsetOffset = -1; + private int charsetOffset = -1; // only if CID - public int fdarrayOffset = -1; + private int fdarrayOffset = -1; // only if CID - public int fdselectOffset = -1; + private int fdselectOffset = -1; - public int[] fdprivateOffsets; + private int[] fdprivateOffsets; - public int[] fdprivateLengths; + private int[] fdprivateLengths; - public int[] fdprivateSubrs; + private int[] fdprivateSubrs; // Added by Oren & Ygal - public int nglyphs; + private int nglyphs; + + private int nstrings; + + private int charsetLength; + + private int[] charstringsOffsets; + + private int[] charset; + + private int[] FDSelect; + + private int FDSelectLength; + + private int FDSelectFormat; + + private int charstringType = 2; + + private int FDArrayCount; + + private int FDArrayOffsize; + + private int[] FDArrayOffsets; + + private int[] privateSubrsOffset; + + private int[][] privateSubrsOffsetsArray; + + private int[] subrsOffsets; + + private int[] gidToCid; + + /// Retrieves the name of the font. + /// font name + public String GetName() { + return this.name; + } + + /// Sets the name of the font. + /// font name + public void SetName(String name) { + this.name = name; + } + + /// Retrieves the full name of the font. + /// full font name + public String GetFullName() { + return this.fullName; + } + + /// Sets the full name of the font. + /// full font name + public void SetFullName(String fullName) { + this.fullName = fullName; + } + + /// Retrieves whether the font is a CID font. + /// true if font is CID font, false otherwise + public bool IsCID() { + return this.isCID; + } + + /// Sets if font is CID font. + /// true if font is CID font, false otherwise + public void SetCID(bool CID) { + this.isCID = CID; + } + + /// Retrieves the private offset of the font. + /// private offset value + public int GetPrivateOffset() { + return this.privateOffset; + } + + /// Sets the private offset of the font. + /// private offset value + public void SetPrivateOffset(int privateOffset) { + this.privateOffset = privateOffset; + } + + /// Retrieves the private length of the font. + /// private length value + public int GetPrivateLength() { + return this.privateLength; + } + + /// Sets the private length of the font. + /// private length value + public void SetPrivateLength(int privateLength) { + this.privateLength = privateLength; + } + + /// Retrieves the private subrs of the font. + /// private subrs value + public int GetPrivateSubrs() { + return this.privateSubrs; + } + + /// Sets the private subrs of the font. + /// private subrs value + public void SetPrivateSubrs(int privateSubrs) { + this.privateSubrs = privateSubrs; + } + + /// Retrieves the char string offset of the font. + /// char string offset + public int GetCharstringsOffset() { + return this.charstringsOffset; + } + + /// Sets the char string offset of the font. + /// char string offset + public void SetCharstringsOffset(int charstringsOffset) { + this.charstringsOffset = charstringsOffset; + } + + /// Retrieves the encoding offset of the font. + /// encoding offset + public int GetEncodingOffset() { + return this.encodingOffset; + } + + /// Sets the encoding offset of the font. + /// encoding offset + public void SetEncodingOffset(int encodingOffset) { + this.encodingOffset = encodingOffset; + } + + /// Retrieves the charset offset of the font. + /// charset offset + public int GetCharsetOffset() { + return this.charsetOffset; + } + + /// Sets the charset offset of the font. + /// charset offset + public void SetCharsetOffset(int charsetOffset) { + this.charsetOffset = charsetOffset; + } + + /// Retrieves the font dictionary array offset of the object. + /// FD array offset + public int GetFdarrayOffset() { + return this.fdarrayOffset; + } - public int nstrings; + /// Sets the font dictionary array offset of the object. + /// FD array offset + public void SetFdarrayOffset(int fdarrayOffset) { + this.fdarrayOffset = fdarrayOffset; + } + + /// Retrieves the font dictionary select offset of the object. + /// FD select offset + public int GetFdselectOffset() { + return this.fdselectOffset; + } + + /// Sets the font dictionary select offset of the object. + /// FD select offset + public void SetFdselectOffset(int fdselectOffset) { + this.fdselectOffset = fdselectOffset; + } + + /// Retrieves the font dictionary private offsets of the object. + /// FD private offsets + public int[] GetFdprivateOffsets() { + return this.fdprivateOffsets; + } + + /// Sets the font dictionary private offsets of the object. + /// FD private offsets + public void SetFdprivateOffsets(int[] fdprivateOffsets) { + this.fdprivateOffsets = fdprivateOffsets; + } + + /// Retrieves the font dictionary private lengths of the object. + /// FD private lengths + public int[] GetFdprivateLengths() { + return this.fdprivateLengths; + } + + /// Sets the font dictionary private lengths of the object. + /// FD private lengths + public void SetFdprivateLengths(int[] fdprivateLengths) { + this.fdprivateLengths = fdprivateLengths; + } + + /// Retrieves the font dictionary private subrs of the object. + /// FD private subrs + public int[] GetFdprivateSubrs() { + return this.fdprivateSubrs; + } + + /// Sets the font dictionary private subrs of the object. + /// FD private subrs + public void SetFdprivateSubrs(int[] fdprivateSubrs) { + this.fdprivateSubrs = fdprivateSubrs; + } - public int CharsetLength; + /// Retrieves the number of glyphs of the font. + /// number of glyphs + public int GetNglyphs() { + return this.nglyphs; + } - public int[] charstringsOffsets; + /// Sets the number of glyphs of the font. + /// number of glyphs + public void SetNglyphs(int nglyphs) { + this.nglyphs = nglyphs; + } - public int[] charset; + /// Retrieves the number of strings of the font. + /// number of strings + public int GetNstrings() { + return this.nstrings; + } - public int[] FDSelect; + /// Sets the number of strings of the font. + /// number of strings + public void SetNstrings(int nstrings) { + this.nstrings = nstrings; + } - public int FDSelectLength; + /// Retrieves the charset length of the font. + /// charset length + public int GetCharsetLength() { + return this.charsetLength; + } - public int FDSelectFormat; + /// Sets the charset length of the font. + /// charset length + public void SetCharsetLength(int charsetLength) { + this.charsetLength = charsetLength; + } - public int CharstringType = 2; + /// Retrieves the char strings offsets of the font. + /// char strings offsets + public int[] GetCharstringsOffsets() { + return this.charstringsOffsets; + } - public int FDArrayCount; + /// Sets the char strings offsets of the font. + /// char strings offsets + public void SetCharstringsOffsets(int[] charstringsOffsets) { + this.charstringsOffsets = charstringsOffsets; + } - public int FDArrayOffsize; + /// Retrieves the charset of the font. + /// charset + public int[] GetCharset() { + return this.charset; + } - public int[] FDArrayOffsets; + /// Sets the charset of the font. + /// charset + public void SetCharset(int[] charset) { + this.charset = charset; + } + + /// Retrieves the font dictionary select of the object. + /// FD select + public int[] GetFDSelect() { + return this.FDSelect; + } + + /// Sets the font dictionary select of the object. + /// FD select + public void SetFDSelect(int[] FDSelect) { + this.FDSelect = FDSelect; + } - public int[] PrivateSubrsOffset; + /// Retrieves the font dictionary select length of the object. + /// FD select length + public int GetFDSelectLength() { + return this.FDSelectLength; + } - public int[][] PrivateSubrsOffsetsArray; + /// Sets the font dictionary select length of the object. + /// FD select length + public void SetFDSelectLength(int FDSelectLength) { + this.FDSelectLength = FDSelectLength; + } - public int[] SubrsOffsets; + /// Retrieves the font dictionary select format of the object. + /// FD select format + public int GetFDSelectFormat() { + return this.FDSelectFormat; + } - public int[] gidToCid; + /// Sets the font dictionary select format of the object. + /// FD select format + public void SetFDSelectFormat(int FDSelectFormat) { + this.FDSelectFormat = FDSelectFormat; + } + + /// Retrieves the char string type of the font. + /// char string type + public int GetCharstringType() { + return this.charstringType; + } + + /// Sets the char string type of the font. + /// char string type + public void SetCharstringType(int charstringType) { + this.charstringType = charstringType; + } + + /// Retrieves the font dictionary array count of the object. + /// FD array count + public int GetFDArrayCount() { + return this.FDArrayCount; + } + + /// Sets the font dictionary array count of the object. + /// FD array count + public void SetFDArrayCount(int FDArrayCount) { + this.FDArrayCount = FDArrayCount; + } + + /// Retrieves the font dictionary array offsize of the object. + /// FD array offsize + public int GetFDArrayOffsize() { + return this.FDArrayOffsize; + } + + /// Sets the font dictionary array offsize of the object. + /// FD array offsize + public void SetFDArrayOffsize(int FDArrayOffsize) { + this.FDArrayOffsize = FDArrayOffsize; + } + + /// Retrieves the font dictionary array offsets of the object. + /// FD array offsets + public int[] GetFDArrayOffsets() { + return this.FDArrayOffsets; + } + + /// Sets the font dictionary array offsets of the object. + /// FD array offsets + public void SetFDArrayOffsets(int[] FDArrayOffsets) { + this.FDArrayOffsets = FDArrayOffsets; + } + + /// Retrieves the private subrs offset of the font. + /// private subrs offset + public int[] GetPrivateSubrsOffset() { + return this.privateSubrsOffset; + } + + /// Set the private subrs offset of the font + /// private subrs offset + public void SetPrivateSubrsOffset(int[] privateSubrsOffset) { + this.privateSubrsOffset = privateSubrsOffset; + } + + /// Retrieves the private subrs offsets array of the font. + /// private subrs offsets array + public int[][] GetPrivateSubrsOffsetsArray() { + return this.privateSubrsOffsetsArray; + } + + /// Sets the private subrs offsets array of the font. + /// private subrs offsets array + public void SetPrivateSubrsOffsetsArray(int[][] privateSubrsOffsetsArray) { + this.privateSubrsOffsetsArray = privateSubrsOffsetsArray; + } + + /// Retrieves the subrs offsets of the font. + /// subrs offsets + public int[] GetSubrsOffsets() { + return this.subrsOffsets; + } + + /// Sets the subrs offsets of the font. + /// subrs offsets + public void SetSubrsOffsets(int[] subrsOffsets) { + this.subrsOffsets = subrsOffsets; + } + + /// Retrieves the glyphs to character id array of the font. + /// glyphs to character id array + public int[] GetGidToCid() { + return this.gidToCid; + } + + /// Sets the glyphs to character id array of the font. + /// glyphs to character id array + public void SetGidToCid(int[] gidToCid) { + this.gidToCid = gidToCid; + } internal Font(CFFFont _enclosing) { this._enclosing = _enclosing; @@ -1101,9 +1479,9 @@ public CFFFont(byte[] cff) { for (int j = 0; j < nameOffsets.Length - 1; j++) { fonts[j] = new CFFFont.Font(this); Seek(nameOffsets[j]); - fonts[j].name = ""; + fonts[j].SetName(""); for (int k = nameOffsets[j]; k < nameOffsets[j + 1]; k++) { - fonts[j].name += GetCard8(); + fonts[j].SetName(fonts[j].GetName() + GetCard8()); } } //System.err.println("name["+j+"]=<"+fonts[j].name+">"); @@ -1129,21 +1507,21 @@ public CFFFont(byte[] cff) { GetDictItem(); if (key == "FullName") { //System.err.println("getting fullname sid = "+((Integer)args[0]).intValue()); - fonts[j].fullName = GetString((char)((int?)args[0]).Value); + fonts[j].SetFullName(GetString((char)((int?)args[0]).Value)); } else { //System.err.println("got it"); if (key == "ROS") { - fonts[j].isCID = true; + fonts[j].SetCID(true); } else { if (key == "Private") { - fonts[j].privateLength = (int)((int?)args[0]).Value; - fonts[j].privateOffset = (int)((int?)args[1]).Value; + fonts[j].SetPrivateLength((int)((int?)args[0]).Value); + fonts[j].SetPrivateOffset((int)((int?)args[1]).Value); } else { if (key == "charset") { - fonts[j].charsetOffset = (int)((int?)args[0]).Value; + fonts[j].SetCharsetOffset((int)((int?)args[0]).Value); } else { // else if (key=="Encoding"){ @@ -1154,24 +1532,24 @@ public CFFFont(byte[] cff) { // } // } if (key == "CharStrings") { - fonts[j].charstringsOffset = (int)((int?)args[0]).Value; + fonts[j].SetCharstringsOffset((int)((int?)args[0]).Value); //System.err.println("charstrings "+fonts[j].charstringsOffset); // Added by Oren & Ygal int p = GetPosition(); - fonts[j].charstringsOffsets = GetIndex(fonts[j].charstringsOffset); + fonts[j].SetCharstringsOffsets(GetIndex(fonts[j].GetCharstringsOffset())); Seek(p); } else { if (key == "FDArray") { - fonts[j].fdarrayOffset = (int)((int?)args[0]).Value; + fonts[j].SetFdarrayOffset((int)((int?)args[0]).Value); } else { if (key == "FDSelect") { - fonts[j].fdselectOffset = (int)((int?)args[0]).Value; + fonts[j].SetFdselectOffset((int)((int?)args[0]).Value); } else { if (key == "CharstringType") { - fonts[j].CharstringType = (int)((int?)args[0]).Value; + fonts[j].SetCharstringType((int)((int?)args[0]).Value); } } } @@ -1182,31 +1560,35 @@ public CFFFont(byte[] cff) { } } // private dict - if (fonts[j].privateOffset >= 0) { + if (fonts[j].GetPrivateOffset() >= 0) { //System.err.println("PRIVATE::"); - Seek(fonts[j].privateOffset); - while (GetPosition() < fonts[j].privateOffset + fonts[j].privateLength) { + Seek(fonts[j].GetPrivateOffset()); + while (GetPosition() < fonts[j].GetPrivateOffset() + fonts[j].GetPrivateLength()) { GetDictItem(); if (key == "Subrs") { //Add the private offset to the lsubrs since the offset is // relative to the beginning of the PrivateDict - fonts[j].privateSubrs = (int)((int?)args[0]).Value + fonts[j].privateOffset; + fonts[j].SetPrivateSubrs((int)((int?)args[0]).Value + fonts[j].GetPrivateOffset()); } } } // fdarray index - if (fonts[j].fdarrayOffset >= 0) { - int[] fdarrayOffsets = GetIndex(fonts[j].fdarrayOffset); - fonts[j].fdprivateOffsets = new int[fdarrayOffsets.Length - 1]; - fonts[j].fdprivateLengths = new int[fdarrayOffsets.Length - 1]; + if (fonts[j].GetFdarrayOffset() >= 0) { + int[] fdarrayOffsets = GetIndex(fonts[j].GetFdarrayOffset()); + fonts[j].SetFdprivateOffsets(new int[fdarrayOffsets.Length - 1]); + fonts[j].SetFdprivateLengths(new int[fdarrayOffsets.Length - 1]); //System.err.println("FD Font::"); for (int k = 0; k < fdarrayOffsets.Length - 1; k++) { Seek(fdarrayOffsets[k]); while (GetPosition() < fdarrayOffsets[k + 1]) { GetDictItem(); if (key == "Private") { - fonts[j].fdprivateLengths[k] = (int)((int?)args[0]).Value; - fonts[j].fdprivateOffsets[k] = (int)((int?)args[1]).Value; + int[] fdprivateLengths = fonts[j].GetFdprivateLengths(); + fdprivateLengths[k] = (int)((int?)args[0]).Value; + fonts[j].SetFdprivateLengths(fdprivateLengths); + int[] fdprivateOffsets = fonts[j].GetFdprivateOffsets(); + fdprivateOffsets[k] = (int)((int?)args[1]).Value; + fonts[j].SetFdprivateOffsets(fdprivateOffsets); } } } diff --git a/itext/itext.io/itext/io/font/CFFFontSubset.cs b/itext/itext.io/itext/io/font/CFFFontSubset.cs index e4055861dd..062904e640 100644 --- a/itext/itext.io/itext/io/font/CFFFontSubset.cs +++ b/itext/itext.io/itext/io/font/CFFFontSubset.cs @@ -172,29 +172,29 @@ internal CFFFontSubset(byte[] cff, ICollection GlyphsUsed, bool isCidParsin glyphsInList = new List(GlyphsUsed); for (int i = 0; i < fonts.Length; ++i) { // Read the number of glyphs in the font - Seek(fonts[i].charstringsOffset); - fonts[i].nglyphs = GetCard16(); + Seek(fonts[i].GetCharstringsOffset()); + fonts[i].SetNglyphs(GetCard16()); // Jump to the count field of the String Index Seek(stringIndexOffset); - fonts[i].nstrings = GetCard16() + standardStrings.Length; + fonts[i].SetNstrings(GetCard16() + standardStrings.Length); // For each font save the offset array of the charstring - fonts[i].charstringsOffsets = GetIndex(fonts[i].charstringsOffset); + fonts[i].SetCharstringsOffsets(GetIndex(fonts[i].GetCharstringsOffset())); if (isCidParsingRequired) { - InitGlyphIdToCharacterIdArray(i, fonts[i].nglyphs, fonts[i].charsetOffset); + InitGlyphIdToCharacterIdArray(i, fonts[i].GetNglyphs(), fonts[i].GetCharsetOffset()); } // Process the FDSelect if exist - if (fonts[i].fdselectOffset >= 0) { + if (fonts[i].GetFdselectOffset() >= 0) { // Process the FDSelect ReadFDSelect(i); // Build the FDArrayUsed Map BuildFDArrayUsed(i); } - if (fonts[i].isCID) { + if (fonts[i].IsCID()) { // Build the FD Array used Map ReadFDArray(i); } // compute the charset length - fonts[i].CharsetLength = CountCharset(fonts[i].charsetOffset, fonts[i].nglyphs); + fonts[i].SetCharsetLength(CountCharset(fonts[i].GetCharsetOffset(), fonts[i].GetNglyphs())); } } //\endcond @@ -264,22 +264,22 @@ internal virtual int CountRange(int NumofGlyphs, int Type) { /// The index of the font being processed protected internal virtual void ReadFDSelect(int Font) { // Restore the number of glyphs - int NumOfGlyphs = fonts[Font].nglyphs; - int[] FDSelect = new int[NumOfGlyphs]; + int numOfGlyphs = fonts[Font].GetNglyphs(); + int[] FDSelect = new int[numOfGlyphs]; // Go to the beginning of the FDSelect - Seek(fonts[Font].fdselectOffset); + Seek(fonts[Font].GetFdselectOffset()); // Read the FDSelect's format - fonts[Font].FDSelectFormat = GetCard8(); - switch (fonts[Font].FDSelectFormat) { + fonts[Font].SetFDSelectFormat(GetCard8()); + switch (fonts[Font].GetFDSelectFormat()) { // Format==0 means each glyph has an entry that indicated // its FD. case 0: { - for (int i = 0; i < NumOfGlyphs; i++) { + for (int i = 0; i < numOfGlyphs; i++) { FDSelect[i] = GetCard8(); } // The FDSelect's Length is one for each glyph + the format // for later use - fonts[Font].FDSelectLength = fonts[Font].nglyphs + 1; + fonts[Font].SetFDSelectLength(fonts[Font].GetNglyphs() + 1); break; } @@ -305,7 +305,7 @@ protected internal virtual void ReadFDSelect(int Font) { first = last; } // Store the length for later use - fonts[Font].FDSelectLength = 1 + 2 + nRanges * 3 + 2; + fonts[Font].SetFDSelectLength(1 + 2 + nRanges * 3 + 2); break; } @@ -314,19 +314,19 @@ protected internal virtual void ReadFDSelect(int Font) { } } // Save the FDSelect of the font - fonts[Font].FDSelect = FDSelect; + fonts[Font].SetFDSelect(FDSelect); } /// Function reads the FDSelect and builds the FDArrayUsed Map According to the glyphs used /// the Number of font being processed protected internal virtual void BuildFDArrayUsed(int Font) { - int[] FDSelect = fonts[Font].FDSelect; + int[] fdSelect = fonts[Font].GetFDSelect(); // For each glyph used foreach (int? glyphsInList1 in glyphsInList) { // Pop the glyphs index int glyph = (int)glyphsInList1; // Pop the glyph's FD - int FD = FDSelect[glyph]; + int FD = fdSelect[glyph]; // Put the FD index into the FDArrayUsed Map FDArrayUsed.Add(FD); } @@ -335,15 +335,15 @@ protected internal virtual void BuildFDArrayUsed(int Font) { /// Read the FDArray count, offsize and Offset array /// the Number of font being processed protected internal virtual void ReadFDArray(int Font) { - Seek(fonts[Font].fdarrayOffset); - fonts[Font].FDArrayCount = GetCard16(); - fonts[Font].FDArrayOffsize = GetCard8(); + Seek(fonts[Font].GetFdarrayOffset()); + fonts[Font].SetFDArrayCount(GetCard16()); + fonts[Font].SetFDArrayOffsize(GetCard8()); // Since we will change values inside the FDArray objects // We increase its offsize to prevent errors - if (fonts[Font].FDArrayOffsize < 4) { - fonts[Font].FDArrayOffsize++; + if (fonts[Font].GetFDArrayOffsize() < 4) { + fonts[Font].SetFDArrayOffsize(fonts[Font].GetFDArrayOffsize() + 1); } - fonts[Font].FDArrayOffsets = GetIndex(fonts[Font].fdarrayOffset); + fonts[Font].SetFDArrayOffsets(GetIndex(fonts[Font].GetFdarrayOffset())); } /// @@ -357,7 +357,7 @@ public virtual byte[] Process(String fontName) { // Find the Font that we will be dealing with int j; for (j = 0; j < fonts.Length; j++) { - if (fontName.Equals(fonts[j].name)) { + if (fontName.Equals(fonts[j].GetName())) { break; } } @@ -408,7 +408,7 @@ protected internal virtual int CalcBias(int Offset, int Font) { Seek(Offset); int nSubrs = GetCard16(); // If type==1 -> bias=0 - if (fonts[Font].CharstringType == 1) { + if (fonts[Font].GetCharstringType() == 1) { return 0; } else { @@ -430,7 +430,7 @@ protected internal virtual int CalcBias(int Offset, int Font) { /// Function uses BuildNewIndex to create the new index of the subset charstrings. /// the font protected internal virtual void BuildNewCharString(int FontIndex) { - NewCharStringsIndex = BuildNewIndex(fonts[FontIndex].charstringsOffsets, GlyphsUsed, ENDCHAR_OP); + NewCharStringsIndex = BuildNewIndex(fonts[FontIndex].GetCharstringsOffsets(), GlyphsUsed, ENDCHAR_OP); } /// Function builds the new local and global subsrs indices. @@ -442,17 +442,17 @@ protected internal virtual void BuildNewCharString(int FontIndex) { protected internal virtual void BuildNewLGSubrs(int Font) { // If the font is CID then the lsubrs are divided into FontDicts. // for each FD array the lsubrs will be subsetted. - if (fonts[Font].isCID) { + if (fonts[Font].IsCID()) { // Init the Map-array and the list-array to hold the subrs used // in each private dict. - hSubrsUsed = new GenericArray>(fonts[Font].fdprivateOffsets.Length); - lSubrsUsed = new GenericArray>(fonts[Font].fdprivateOffsets.Length); + hSubrsUsed = new GenericArray>(fonts[Font].GetFdprivateOffsets().Length); + lSubrsUsed = new GenericArray>(fonts[Font].GetFdprivateOffsets().Length); // A [][] which will store the byte array for each new FD Array lsubs index - NewLSubrsIndex = new byte[fonts[Font].fdprivateOffsets.Length][]; + NewLSubrsIndex = new byte[fonts[Font].GetFdprivateOffsets().Length][]; // An array to hold the offset for each Lsubr index - fonts[Font].PrivateSubrsOffset = new int[fonts[Font].fdprivateOffsets.Length]; + fonts[Font].SetPrivateSubrsOffset(new int[fonts[Font].GetFdprivateOffsets().Length]); // A [][] which will store the offset array for each lsubr index - fonts[Font].PrivateSubrsOffsetsArray = new int[fonts[Font].fdprivateOffsets.Length][]; + fonts[Font].SetPrivateSubrsOffsetsArray(new int[fonts[Font].GetFdprivateOffsets().Length][]); // Put the FDarrayUsed into a list IList FDInList = new List(FDArrayUsed); // For each FD array which is used subset the lsubr @@ -465,34 +465,34 @@ protected internal virtual void BuildNewLGSubrs(int Font) { // store both the offset for the index and its offset array BuildFDSubrsOffsets(Font, FD); // Verify that FDPrivate has a LSubrs index - if (fonts[Font].PrivateSubrsOffset[FD] >= 0) { + if (fonts[Font].GetPrivateSubrsOffset()[FD] >= 0) { //Scans the Charstring data storing the used Local and Global subroutines // by the glyphs. Scans the Subrs recursively. - BuildSubrUsed(Font, FD, fonts[Font].PrivateSubrsOffset[FD], fonts[Font].PrivateSubrsOffsetsArray[FD], hSubrsUsed - .Get(FD), lSubrsUsed.Get(FD)); + BuildSubrUsed(Font, FD, fonts[Font].GetPrivateSubrsOffset()[FD], fonts[Font].GetPrivateSubrsOffsetsArray() + [FD], hSubrsUsed.Get(FD), lSubrsUsed.Get(FD)); // Builds the New Local Subrs index - NewLSubrsIndex[FD] = BuildNewIndex(fonts[Font].PrivateSubrsOffsetsArray[FD], hSubrsUsed.Get(FD), RETURN_OP + NewLSubrsIndex[FD] = BuildNewIndex(fonts[Font].GetPrivateSubrsOffsetsArray()[FD], hSubrsUsed.Get(FD), RETURN_OP ); } } } else { // If the font is not CID && the Private Subr exists then subset: - if (fonts[Font].privateSubrs >= 0) { + if (fonts[Font].GetPrivateSubrs() >= 0) { // Build the subrs offsets; - fonts[Font].SubrsOffsets = GetIndex(fonts[Font].privateSubrs); + fonts[Font].SetSubrsOffsets(GetIndex(fonts[Font].GetPrivateSubrs())); //Scans the Charstring data storing the used Local and Global subroutines // by the glyphs. Scans the Subrs recursively. - BuildSubrUsed(Font, -1, fonts[Font].privateSubrs, fonts[Font].SubrsOffsets, hSubrsUsedNonCID, lSubrsUsedNonCID + BuildSubrUsed(Font, -1, fonts[Font].GetPrivateSubrs(), fonts[Font].GetSubrsOffsets(), hSubrsUsedNonCID, lSubrsUsedNonCID ); } } // For all fonts subset the Global Subroutines // Scan the Global Subr Map recursively on the Gsubrs BuildGSubrsUsed(Font); - if (fonts[Font].privateSubrs >= 0) { + if (fonts[Font].GetPrivateSubrs() >= 0) { // Builds the New Local Subrs index - NewSubrsIndexNonCID = BuildNewIndex(fonts[Font].SubrsOffsets, hSubrsUsedNonCID, RETURN_OP); + NewSubrsIndexNonCID = BuildNewIndex(fonts[Font].GetSubrsOffsets(), hSubrsUsedNonCID, RETURN_OP); } //Builds the New Global Subrs index // NOTE We copy all global subroutines to index here. @@ -511,20 +511,26 @@ protected internal virtual void BuildNewLGSubrs(int Font) { /// The FDARRAY processed protected internal virtual void BuildFDSubrsOffsets(int Font, int FD) { // Initiate to -1 to indicate lsubr operator present - fonts[Font].PrivateSubrsOffset[FD] = -1; + int[] privateSubrsOffset = fonts[Font].GetPrivateSubrsOffset(); + privateSubrsOffset[FD] = -1; + fonts[Font].SetPrivateSubrsOffset(privateSubrsOffset); // Goto beginning of objects - Seek(fonts[Font].fdprivateOffsets[FD]); + Seek(fonts[Font].GetFdprivateOffsets()[FD]); // While in the same object: - while (GetPosition() < fonts[Font].fdprivateOffsets[FD] + fonts[Font].fdprivateLengths[FD]) { + while (GetPosition() < fonts[Font].GetFdprivateOffsets()[FD] + fonts[Font].GetFdprivateLengths()[FD]) { GetDictItem(); // If the dictItem is the "Subrs" then find and store offset, if ("Subrs".Equals(key)) { - fonts[Font].PrivateSubrsOffset[FD] = (int)((int?)args[0]) + fonts[Font].fdprivateOffsets[FD]; + privateSubrsOffset = fonts[Font].GetPrivateSubrsOffset(); + privateSubrsOffset[FD] = (int)((int?)args[0]) + fonts[Font].GetFdprivateOffsets()[FD]; + fonts[Font].SetPrivateSubrsOffset(privateSubrsOffset); } } //Read the lsubr index if the lsubr was found - if (fonts[Font].PrivateSubrsOffset[FD] >= 0) { - fonts[Font].PrivateSubrsOffsetsArray[FD] = GetIndex(fonts[Font].PrivateSubrsOffset[FD]); + if (fonts[Font].GetPrivateSubrsOffset()[FD] >= 0) { + int[][] privateSubrsOffsetsArray = fonts[Font].GetPrivateSubrsOffsetsArray(); + privateSubrsOffsetsArray[FD] = GetIndex(fonts[Font].GetPrivateSubrsOffset()[FD]); + fonts[Font].SetPrivateSubrsOffsetsArray(privateSubrsOffsetsArray); } } @@ -547,24 +553,24 @@ protected internal virtual void BuildSubrUsed(int Font, int FD, int SubrOffset, // For each glyph used find its GID, start & end pos foreach (int? usedGlyph in glyphsInList) { int glyph = (int)usedGlyph; - int Start = fonts[Font].charstringsOffsets[glyph]; - int End = fonts[Font].charstringsOffsets[glyph + 1]; + int start = fonts[Font].GetCharstringsOffsets()[glyph]; + int end = fonts[Font].GetCharstringsOffsets()[glyph + 1]; // IF CID: if (FD >= 0) { EmptyStack(); NumOfHints = 0; // Using FDSELECT find the FD Array the glyph belongs to. - int GlyphFD = fonts[Font].FDSelect[glyph]; + int glyphFD = fonts[Font].GetFDSelect()[glyph]; // If the Glyph is part of the FD being processed - if (GlyphFD == FD) { + if (glyphFD == FD) { // Find the Subrs called by the glyph and insert to hash: - ReadASubr(Start, End, GBias, LBias, hSubr, lSubr, SubrsOffsets); + ReadASubr(start, end, GBias, LBias, hSubr, lSubr, SubrsOffsets); } } else { // If the font is not CID //Find the Subrs called by the glyph and insert to hash: - ReadASubr(Start, End, GBias, LBias, hSubr, lSubr, SubrsOffsets); + ReadASubr(start, end, GBias, LBias, hSubr, lSubr, SubrsOffsets); } } // For all Lsubrs used, check recursively for Lsubr & Gsubr used @@ -589,8 +595,8 @@ protected internal virtual void BuildSubrUsed(int Font, int FD, int SubrOffset, protected internal virtual void BuildGSubrsUsed(int Font) { int LBias = 0; int SizeOfNonCIDSubrsUsed = 0; - if (fonts[Font].privateSubrs >= 0) { - LBias = CalcBias(fonts[Font].privateSubrs, Font); + if (fonts[Font].GetPrivateSubrs() >= 0) { + LBias = CalcBias(fonts[Font].GetPrivateSubrs(), Font); SizeOfNonCIDSubrsUsed = lSubrsUsedNonCID.Count; } // For each global subr used @@ -601,20 +607,20 @@ protected internal virtual void BuildGSubrsUsed(int Font) { // Read the subr and process int Start = gsubrOffsets[Subr]; int End = gsubrOffsets[Subr + 1]; - if (fonts[Font].isCID) { + if (fonts[Font].IsCID()) { ReadASubr(Start, End, GBias, 0, hGSubrsUsed, lGSubrsUsed, null); } else { - ReadASubr(Start, End, GBias, LBias, hSubrsUsedNonCID, lSubrsUsedNonCID, fonts[Font].SubrsOffsets); + ReadASubr(Start, End, GBias, LBias, hSubrsUsedNonCID, lSubrsUsedNonCID, fonts[Font].GetSubrsOffsets()); if (SizeOfNonCIDSubrsUsed < lSubrsUsedNonCID.Count) { for (int j = SizeOfNonCIDSubrsUsed; j < lSubrsUsedNonCID.Count; j++) { //Pop the value + check valid - int LSubr = (int)lSubrsUsedNonCID[j]; - if (LSubr < fonts[Font].SubrsOffsets.Length - 1 && LSubr >= 0) { + int lSubr = (int)lSubrsUsedNonCID[j]; + if (lSubr < fonts[Font].GetSubrsOffsets().Length - 1 && lSubr >= 0) { // Read the subr and process - int LStart = fonts[Font].SubrsOffsets[LSubr]; - int LEnd = fonts[Font].SubrsOffsets[LSubr + 1]; - ReadASubr(LStart, LEnd, GBias, LBias, hSubrsUsedNonCID, lSubrsUsedNonCID, fonts[Font].SubrsOffsets); + int lStart = fonts[Font].GetSubrsOffsets()[lSubr]; + int lEnd = fonts[Font].GetSubrsOffsets()[lSubr + 1]; + ReadASubr(lStart, lEnd, GBias, LBias, hSubrsUsedNonCID, lSubrsUsedNonCID, fonts[Font].GetSubrsOffsets()); } } SizeOfNonCIDSubrsUsed = lSubrsUsedNonCID.Count; @@ -1132,8 +1138,8 @@ protected internal virtual byte[] BuildNewFile(int Font) { CopyHeader(); // create a name index BuildIndexHeader(1, 1, 1); - OutputList.AddLast(new CFFFont.UInt8Item((char)(1 + fonts[Font].name.Length))); - OutputList.AddLast(new CFFFont.StringItem(fonts[Font].name)); + OutputList.AddLast(new CFFFont.UInt8Item((char)(1 + fonts[Font].GetName().Length))); + OutputList.AddLast(new CFFFont.StringItem(fonts[Font].GetName())); // create the topdict Index BuildIndexHeader(1, 2, 1); CFFFont.OffsetItem topdictIndex1Ref = new CFFFont.IndexOffsetItem(2); @@ -1147,15 +1153,15 @@ protected internal virtual byte[] BuildNewFile(int Font) { CFFFont.OffsetItem fdselectRef = new CFFFont.DictOffsetItem(); CFFFont.OffsetItem privateRef = new CFFFont.DictOffsetItem(); // If the font is not CID create the following keys - if (!fonts[Font].isCID) { + if (!fonts[Font].IsCID()) { // create a ROS key - OutputList.AddLast(new CFFFont.DictNumberItem(fonts[Font].nstrings)); - OutputList.AddLast(new CFFFont.DictNumberItem(fonts[Font].nstrings + 1)); + OutputList.AddLast(new CFFFont.DictNumberItem(fonts[Font].GetNstrings())); + OutputList.AddLast(new CFFFont.DictNumberItem(fonts[Font].GetNstrings() + 1)); OutputList.AddLast(new CFFFont.DictNumberItem(0)); OutputList.AddLast(new CFFFont.UInt8Item((char)12)); OutputList.AddLast(new CFFFont.UInt8Item((char)30)); // create a CIDCount key - OutputList.AddLast(new CFFFont.DictNumberItem(fonts[Font].nglyphs)); + OutputList.AddLast(new CFFFont.DictNumberItem(fonts[Font].GetNglyphs())); OutputList.AddLast(new CFFFont.UInt8Item((char)12)); OutputList.AddLast(new CFFFont.UInt8Item((char)34)); } @@ -1185,7 +1191,7 @@ protected internal virtual byte[] BuildNewFile(int Font) { // Mark the end of the top dict area OutputList.AddLast(new CFFFont.IndexMarkerItem(topdictIndex1Ref, topdictBase)); // Copy the string index - if (fonts[Font].isCID) { + if (fonts[Font].IsCID()) { OutputList.AddLast(GetEntireIndexRange(stringIndexOffset)); } else { @@ -1199,26 +1205,28 @@ protected internal virtual byte[] BuildNewFile(int Font) { )), 0, NewGSubrsIndex.Length)); // deal with fdarray, fdselect, and the font descriptors // If the font is CID: - if (fonts[Font].isCID) { + if (fonts[Font].IsCID()) { // copy the FDArray, FDSelect, charset // Copy FDSelect // Mark the beginning OutputList.AddLast(new CFFFont.MarkerItem(fdselectRef)); // If an FDSelect exists copy it - if (fonts[Font].fdselectOffset >= 0) { - OutputList.AddLast(new CFFFont.RangeItem(buf, fonts[Font].fdselectOffset, fonts[Font].FDSelectLength)); + if (fonts[Font].GetFdselectOffset() >= 0) { + OutputList.AddLast(new CFFFont.RangeItem(buf, fonts[Font].GetFdselectOffset(), fonts[Font].GetFDSelectLength + ())); } else { // Else create a new one - CreateFDSelect(fdselectRef, fonts[Font].nglyphs); + CreateFDSelect(fdselectRef, fonts[Font].GetNglyphs()); } // Copy the Charset // Mark the beginning and copy entirely OutputList.AddLast(new CFFFont.MarkerItem(charsetRef)); - OutputList.AddLast(new CFFFont.RangeItem(buf, fonts[Font].charsetOffset, fonts[Font].CharsetLength)); + OutputList.AddLast(new CFFFont.RangeItem(buf, fonts[Font].GetCharsetOffset(), fonts[Font].GetCharsetLength + ())); // Copy the FDArray // If an FDArray exists - if (fonts[Font].fdarrayOffset >= 0) { + if (fonts[Font].GetFdarrayOffset() >= 0) { // Mark the beginning OutputList.AddLast(new CFFFont.MarkerItem(fdarrayRef)); // Build a new FDArray with its private dicts and their LSubrs @@ -1232,14 +1240,14 @@ protected internal virtual byte[] BuildNewFile(int Font) { else { // If the font is not CID // create FDSelect - CreateFDSelect(fdselectRef, fonts[Font].nglyphs); + CreateFDSelect(fdselectRef, fonts[Font].GetNglyphs()); // recreate a new charset - CreateCharset(charsetRef, fonts[Font].nglyphs); + CreateCharset(charsetRef, fonts[Font].GetNglyphs()); // create a font dict index (fdarray) CreateFDArray(fdarrayRef, privateRef, Font); } // if a private dict exists insert its subsetted version - if (fonts[Font].privateOffset >= 0) { + if (fonts[Font].GetPrivateOffset() >= 0) { // Mark the beginning of the private dict CFFFont.IndexBaseItem PrivateBase = new CFFFont.IndexBaseItem(); OutputList.AddLast(PrivateBase); @@ -1356,7 +1364,7 @@ protected internal virtual void CreateKeys(CFFFont.OffsetItem fdarrayRef, CFFFon /// /// the font protected internal virtual void CreateNewStringIndex(int Font) { - String fdFontName = fonts[Font].name + "-OneRange"; + String fdFontName = fonts[Font].GetName() + "-OneRange"; if (fdFontName.Length > 127) { fdFontName = fdFontName.JSubstring(0, 127); } @@ -1469,14 +1477,15 @@ protected internal virtual void CreateFDArray(CFFFont.OffsetItem fdarrayRef, CFF OutputList.AddLast(privateBase); // Calc the new size of the private after subsetting // Origianl size - int NewSize = fonts[Font].privateLength; + int newSize = fonts[Font].GetPrivateLength(); // Calc the original size of the Subr offset in the private - int OrgSubrsOffsetSize = CalcSubrOffsetSize(fonts[Font].privateOffset, fonts[Font].privateLength); + int orgSubrsOffsetSize = CalcSubrOffsetSize(fonts[Font].GetPrivateOffset(), fonts[Font].GetPrivateLength() + ); // Increase the ptivate's size - if (OrgSubrsOffsetSize != 0) { - NewSize += 5 - OrgSubrsOffsetSize; + if (orgSubrsOffsetSize != 0) { + newSize += 5 - orgSubrsOffsetSize; } - OutputList.AddLast(new CFFFont.DictNumberItem(NewSize)); + OutputList.AddLast(new CFFFont.DictNumberItem(newSize)); OutputList.AddLast(privateRef); // Private OutputList.AddLast(new CFFFont.UInt8Item((char)18)); @@ -1488,9 +1497,10 @@ protected internal virtual void CreateFDArray(CFFFont.OffsetItem fdarrayRef, CFF /// the font internal virtual void Reconstruct(int Font) { // Init for later use - CFFFont.OffsetItem[] fdPrivate = new CFFFont.DictOffsetItem[fonts[Font].FDArrayOffsets.Length - 1]; - CFFFont.IndexBaseItem[] fdPrivateBase = new CFFFont.IndexBaseItem[fonts[Font].fdprivateOffsets.Length]; - CFFFont.OffsetItem[] fdSubrs = new CFFFont.DictOffsetItem[fonts[Font].fdprivateOffsets.Length]; + CFFFont.OffsetItem[] fdPrivate = new CFFFont.DictOffsetItem[fonts[Font].GetFDArrayOffsets().Length - 1]; + CFFFont.IndexBaseItem[] fdPrivateBase = new CFFFont.IndexBaseItem[fonts[Font].GetFdprivateOffsets().Length + ]; + CFFFont.OffsetItem[] fdSubrs = new CFFFont.DictOffsetItem[fonts[Font].GetFdprivateOffsets().Length]; // Reconstruct each type ReconstructFDArray(Font, fdPrivate); ReconstructPrivateDict(Font, fdPrivate, fdPrivateBase, fdSubrs); @@ -1504,11 +1514,11 @@ internal virtual void Reconstruct(int Font) { /// OffsetItem Array (one for each FDArray) internal virtual void ReconstructFDArray(int Font, CFFFont.OffsetItem[] fdPrivate) { // Build the header of the index - BuildIndexHeader(fonts[Font].FDArrayCount, fonts[Font].FDArrayOffsize, 1); + BuildIndexHeader(fonts[Font].GetFDArrayCount(), fonts[Font].GetFDArrayOffsize(), 1); // For each offset create an Offset Item - CFFFont.OffsetItem[] fdOffsets = new CFFFont.IndexOffsetItem[fonts[Font].FDArrayOffsets.Length - 1]; - for (int i = 0; i < fonts[Font].FDArrayOffsets.Length - 1; i++) { - fdOffsets[i] = new CFFFont.IndexOffsetItem(fonts[Font].FDArrayOffsize); + CFFFont.OffsetItem[] fdOffsets = new CFFFont.IndexOffsetItem[fonts[Font].GetFDArrayOffsets().Length - 1]; + for (int i = 0; i < fonts[Font].GetFDArrayOffsets().Length - 1; i++) { + fdOffsets[i] = new CFFFont.IndexOffsetItem(fonts[Font].GetFDArrayOffsize()); OutputList.AddLast(fdOffsets[i]); } // Declare beginning of the object array @@ -1518,12 +1528,12 @@ internal virtual void ReconstructFDArray(int Font, CFFFont.OffsetItem[] fdPrivat // if is used build a new one by changing the private object // Else do nothing // At the end of each object mark its ending (Even if wasn't written) - for (int k = 0; k < fonts[Font].FDArrayOffsets.Length - 1; k++) { + for (int k = 0; k < fonts[Font].GetFDArrayOffsets().Length - 1; k++) { // if (FDArrayUsed.contains(Integer.valueOf(k))) // { // Goto beginning of objects - Seek(fonts[Font].FDArrayOffsets[k]); - while (GetPosition() < fonts[Font].FDArrayOffsets[k + 1]) { + Seek(fonts[Font].GetFDArrayOffsets()[k]); + while (GetPosition() < fonts[Font].GetFDArrayOffsets()[k + 1]) { int p1 = GetPosition(); GetDictItem(); int p2 = GetPosition(); @@ -1531,16 +1541,16 @@ internal virtual void ReconstructFDArray(int Font, CFFFont.OffsetItem[] fdPrivat // use marker for offset and write operator number if ("Private".Equals(key)) { // Save the original length of the private dict - int NewSize = (int)((int?)args[0]); + int newSize = (int)((int?)args[0]); // Save the size of the offset to the subrs in that private - int OrgSubrsOffsetSize = CalcSubrOffsetSize(fonts[Font].fdprivateOffsets[k], fonts[Font].fdprivateLengths[ - k]); + int orgSubrsOffsetSize = CalcSubrOffsetSize(fonts[Font].GetFdprivateOffsets()[k], fonts[Font].GetFdprivateLengths + ()[k]); // Increase the private's length accordingly - if (OrgSubrsOffsetSize != 0) { - NewSize += 5 - OrgSubrsOffsetSize; + if (orgSubrsOffsetSize != 0) { + newSize += 5 - orgSubrsOffsetSize; } // Insert the new size, OffsetItem and operator key number - OutputList.AddLast(new CFFFont.DictNumberItem(NewSize)); + OutputList.AddLast(new CFFFont.DictNumberItem(newSize)); fdPrivate[k] = new CFFFont.DictOffsetItem(); OutputList.AddLast(fdPrivate[k]); // Private @@ -1572,7 +1582,7 @@ internal virtual void ReconstructPrivateDict(int Font, CFFFont.OffsetItem[] fdPr // For each fdarray private dict check if that FD is used. // if is used build a new one by changing the subrs offset // Else do nothing - for (int i = 0; i < fonts[Font].fdprivateOffsets.Length; i++) { + for (int i = 0; i < fonts[Font].GetFdprivateOffsets().Length; i++) { // if (FDArrayUsed.contains(Integer.valueOf(i))) // { // Mark beginning @@ -1580,8 +1590,8 @@ internal virtual void ReconstructPrivateDict(int Font, CFFFont.OffsetItem[] fdPr fdPrivateBase[i] = new CFFFont.IndexBaseItem(); OutputList.AddLast(fdPrivateBase[i]); // Goto beginning of objects - Seek(fonts[Font].fdprivateOffsets[i]); - while (GetPosition() < fonts[Font].fdprivateOffsets[i] + fonts[Font].fdprivateLengths[i]) { + Seek(fonts[Font].GetFdprivateOffsets()[i]); + while (GetPosition() < fonts[Font].GetFdprivateOffsets()[i] + fonts[Font].GetFdprivateLengths()[i]) { int p1 = GetPosition(); GetDictItem(); int p2 = GetPosition(); @@ -1611,10 +1621,10 @@ internal virtual void ReconstructPrivateDict(int Font, CFFFont.OffsetItem[] fdPr internal virtual void ReconstructPrivateSubrs(int Font, CFFFont.IndexBaseItem[] fdPrivateBase, CFFFont.OffsetItem [] fdSubrs) { // For each private dict - for (int i = 0; i < fonts[Font].fdprivateLengths.Length; i++) { + for (int i = 0; i < fonts[Font].GetFdprivateLengths().Length; i++) { // If that private dict's Subrs are used insert the new LSubrs // computed earlier - if (fdSubrs[i] != null && fonts[Font].PrivateSubrsOffset[i] >= 0) { + if (fdSubrs[i] != null && fonts[Font].GetPrivateSubrsOffset()[i] >= 0) { OutputList.AddLast(new CFFFont.SubrMarkerItem(fdSubrs[i], fdPrivateBase[i])); if (NewLSubrsIndex[i] != null) { OutputList.AddLast(new CFFFont.RangeItem(new RandomAccessFileOrArray(rasFactory.CreateSource(NewLSubrsIndex @@ -1688,8 +1698,8 @@ protected internal virtual int CountEntireIndexRange(int indexOffset) { /// The OffsetItem for the subrs of the private internal virtual void CreateNonCIDPrivate(int Font, CFFFont.OffsetItem Subr) { // Go to the beginning of the private dict and read until the end - Seek(fonts[Font].privateOffset); - while (GetPosition() < fonts[Font].privateOffset + fonts[Font].privateLength) { + Seek(fonts[Font].GetPrivateOffset()); + while (GetPosition() < fonts[Font].GetPrivateOffset() + fonts[Font].GetPrivateLength()) { int p1 = GetPosition(); GetDictItem(); int p2 = GetPosition(); @@ -1743,12 +1753,13 @@ internal virtual int GetCidForGlyphId(int gid) { /// glyph identifier /// CID value internal virtual int GetCidForGlyphId(int fontIndex, int gid) { - if (fonts[fontIndex].gidToCid == null) { + if (fonts[fontIndex].GetGidToCid() == null) { return gid; } // gidToCid mapping starts with value corresponding to gid == 1, becuase .notdef is omitted int index = gid - 1; - return index >= 0 && index < fonts[fontIndex].gidToCid.Length ? fonts[fontIndex].gidToCid[index] : gid; + return index >= 0 && index < fonts[fontIndex].GetGidToCid().Length ? fonts[fontIndex].GetGidToCid()[index] + : gid; } //\endcond @@ -1763,12 +1774,14 @@ private void InitGlyphIdToCharacterIdArray(int fontIndex, int numOfGlyphs, int o int format = GetCard8(); // .notdef is omitted, therefore remaining number of elements is one less than overall number int numOfElements = numOfGlyphs - 1; - fonts[fontIndex].gidToCid = new int[numOfElements]; + fonts[fontIndex].SetGidToCid(new int[numOfElements]); switch (format) { case 0: { for (int i = 0; i < numOfElements; i++) { int cid = GetCard16(); - fonts[fontIndex].gidToCid[i] = cid; + int[] gidToCid = fonts[fontIndex].GetGidToCid(); + gidToCid[i] = cid; + fonts[fontIndex].SetGidToCid(gidToCid); } break; } @@ -1780,7 +1793,9 @@ private void InitGlyphIdToCharacterIdArray(int fontIndex, int numOfGlyphs, int o int first = GetCard16(); int nLeft = format == 1 ? GetCard8() : GetCard16(); for (int i = 0; i <= nLeft && start < numOfElements; i++) { - fonts[fontIndex].gidToCid[start++] = first + i; + int[] gidToCid = fonts[fontIndex].GetGidToCid(); + gidToCid[start++] = first + i; + fonts[fontIndex].SetGidToCid(gidToCid); } } break; diff --git a/itext/itext.io/itext/io/font/FontCache.cs b/itext/itext.io/itext/io/font/FontCache.cs index f8013f2c91..dfe1fb349b 100644 --- a/itext/itext.io/itext/io/font/FontCache.cs +++ b/itext/itext.io/itext/io/font/FontCache.cs @@ -23,86 +23,11 @@ You should have received a copy of the GNU Affero General Public License using System; using System.Collections.Concurrent; using System.Collections.Generic; -using iText.IO.Font.Cmap; namespace iText.IO.Font { public class FontCache { - private static IDictionary fontCache = new ConcurrentDictionary(); - - /// - /// Checks if the font with the given name and encoding is one - /// of the predefined CID fonts. - /// - /// the font name. - /// - /// - /// - /// if it is CJKFont. - /// - [System.ObsoleteAttribute(@"in favour of CjkResourceLoader .")] - protected internal static bool IsPredefinedCidFont(String fontName) { - return CjkResourceLoader.IsPredefinedCidFont(fontName); - } - - /// Finds a CJK font family which is compatible to the given CMap. - /// a name of the CMap for which compatible font is searched. - /// a CJK font name if there's known compatible font for the given cmap name, or null otherwise. - [System.ObsoleteAttribute(@"in favour of CjkResourceLoader .")] - public static String GetCompatibleCidFont(String cmap) { - return CjkResourceLoader.GetCompatibleCidFont(cmap); - } - - /// - /// Finds all CMap names that belong to the same registry to which a given - /// font belongs. - /// - /// a name of the font for which CMap's are searched. - /// a set of CMap names corresponding to the given font. - [System.ObsoleteAttribute(@"in favour of CjkResourceLoader .")] - public static ICollection GetCompatibleCmaps(String fontName) { - return CjkResourceLoader.GetCompatibleCmaps(fontName); - } - - [Obsolete] - public static IDictionary> GetAllPredefinedCidFonts() { - return CjkResourceLoader.GetAllPredefinedCidFonts(); - } - - [Obsolete] - public static IDictionary> GetRegistryNames() { - return CjkResourceLoader.GetRegistryNames(); - } - - /// Parses CMap with a given name producing it in a form of cid to unicode mapping. - /// a CMap name. It is expected that CMap identified by this name defines unicode to cid mapping. - /// - /// an object for convenient mapping from cid to unicode. If no CMap was found for provided name an exception is thrown. - /// - [System.ObsoleteAttribute(@"in favour of CjkResourceLoader .")] - public static CMapCidUni GetCid2UniCmap(String uniMap) { - return CjkResourceLoader.GetCid2UniCmap(uniMap); - } - - [Obsolete] - public static CMapUniCid GetUni2CidCmap(String uniMap) { - return CjkResourceLoader.GetUni2CidCmap(uniMap); - } - - [Obsolete] - public static CMapByteCid GetByte2CidCmap(String cmap) { - return CjkResourceLoader.GetByte2CidCmap(cmap); - } - - [Obsolete] - public static CMapCidToCodepoint GetCidToCodepointCmap(String cmap) { - return CjkResourceLoader.GetCidToCodepointCmap(cmap); - } - - [Obsolete] - public static CMapCodepointToCid GetCodepointToCidCmap(String uniMap) { - return CjkResourceLoader.GetCodepointToCidCmap(uniMap); - } + private static readonly IDictionary fontCache = new ConcurrentDictionary(); /// /// Clears the cache by removing fonts that were added via diff --git a/itext/itext.io/itext/io/font/OpenTypeParser.cs b/itext/itext.io/itext/io/font/OpenTypeParser.cs index d0ddbd5803..ec84058b2e 100644 --- a/itext/itext.io/itext/io/font/OpenTypeParser.cs +++ b/itext/itext.io/itext/io/font/OpenTypeParser.cs @@ -1004,6 +1004,7 @@ private void ReadCmapTable() { int map31 = 0; int map30 = 0; int mapExt = 0; + int map03 = 0; cmaps = new OpenTypeParser.CmapTable(); for (int k = 0; k < num_tables; ++k) { int platId = raf.ReadUnsignedShort(); @@ -1025,6 +1026,11 @@ private void ReadCmapTable() { if (platId == 1 && platSpecId == 0) { map10 = offset; } + else { + if (platId == 0 && platSpecId == 3) { + map03 = offset; + } + } } } } @@ -1049,6 +1055,26 @@ private void ReadCmapTable() { } } } + if (map03 > 0) { + // Unicode platform, Unicode >2.0 semantics, expect format 4 or 6 subtable + raf.Seek(table_location[0] + map03); + int format = raf.ReadUnsignedShort(); + // We treat this table as equivalent to (platformId = 3, encodingId = 1) + // for downstream processing, since both are intended to address the Unicode BMP. + // Note that only one of these encoding subtables is used at a time. If multiple encoding subtables + // are found, the ‘cmap’ parsing software determines which one to use. + switch (format) { + case 4: { + cmaps.cmap31 = ReadFormat4(false); + break; + } + + case 6: { + cmaps.cmap31 = ReadFormat6(); + break; + } + } + } if (map31 > 0) { raf.Seek(table_location[0] + map31); int format = raf.ReadUnsignedShort(); diff --git a/itext/itext.io/itext/io/font/cmap/CMapByteCid.cs b/itext/itext.io/itext/io/font/cmap/CMapByteCid.cs index 43b3f76e84..d32727a2bf 100644 --- a/itext/itext.io/itext/io/font/cmap/CMapByteCid.cs +++ b/itext/itext.io/itext/io/font/cmap/CMapByteCid.cs @@ -27,17 +27,41 @@ You should have received a copy of the GNU Affero General Public License namespace iText.IO.Font.Cmap { public class CMapByteCid : AbstractCMap { protected internal class Cursor { - public int offset; + private int offset; - public int length; + private int length; public Cursor(int offset, int length) { this.offset = offset; this.length = length; } + + /// Retrieves the offset of the object. + /// offset value + public virtual int GetOffset() { + return offset; + } + + /// Sets the offset of the object. + /// offset value + public virtual void SetOffset(int offset) { + this.offset = offset; + } + + /// Retrieves the length of the object. + /// length value + public virtual int GetLength() { + return length; + } + + /// Sets the length value of the object. + /// length value + public virtual void SetLength(int length) { + this.length = length; + } } - private IList planes = new List(); + private readonly IList planes = new List(); public CMapByteCid() { planes.Add(new int[256]); @@ -67,11 +91,12 @@ public virtual String DecodeSequence(byte[] cidBytes, int offset, int length) { } protected internal virtual int DecodeSingle(byte[] cidBytes, CMapByteCid.Cursor cursor) { - int end = cursor.offset + cursor.length; + int end = cursor.GetOffset() + cursor.GetLength(); int currentPlane = 0; - while (cursor.offset < end) { - int one = cidBytes[cursor.offset++] & 0xff; - cursor.length--; + while (cursor.GetOffset() < end) { + int one = cidBytes[cursor.GetOffset()] & 0xff; + cursor.SetOffset(cursor.GetOffset() + 1); + cursor.SetLength(cursor.GetLength() - 1); int[] plane = planes[currentPlane]; int cid = plane[one]; if ((cid & 0x8000) == 0) { diff --git a/itext/itext.io/itext/io/font/cmap/CMapContentParser.cs b/itext/itext.io/itext/io/font/cmap/CMapContentParser.cs index 4d1ec9da4e..10890dc21f 100644 --- a/itext/itext.io/itext/io/font/cmap/CMapContentParser.cs +++ b/itext/itext.io/itext/io/font/cmap/CMapContentParser.cs @@ -204,18 +204,6 @@ public virtual bool NextValidToken() { return false; } - /// - /// Use - /// - /// instead. - /// - /// to decode - /// decoded content - [System.ObsoleteAttribute] - protected internal static String DecodeName(byte[] content) { - return PdfNameUtil.DecodeName(content); - } - private static String ToHex4(int n) { String s = "0000" + JavaUtil.IntegerToHexString(n); return s.Substring(s.Length - 4); diff --git a/itext/itext.io/itext/io/font/cmap/CMapToUnicode.cs b/itext/itext.io/itext/io/font/cmap/CMapToUnicode.cs index fa2609cc22..508dcfadbc 100644 --- a/itext/itext.io/itext/io/font/cmap/CMapToUnicode.cs +++ b/itext/itext.io/itext/io/font/cmap/CMapToUnicode.cs @@ -30,8 +30,8 @@ You should have received a copy of the GNU Affero General Public License namespace iText.IO.Font.Cmap { /// This class represents a CMap file. public class CMapToUnicode : AbstractCMap { - public static iText.IO.Font.Cmap.CMapToUnicode EmptyCMapToUnicodeMap = new iText.IO.Font.Cmap.CMapToUnicode - (true); + public static readonly iText.IO.Font.Cmap.CMapToUnicode EMPTY_CMAP = new iText.IO.Font.Cmap.CMapToUnicode( + true); private readonly IDictionary byteMappings; diff --git a/itext/itext.io/itext/io/font/constants/FontDescriptorFlags.cs b/itext/itext.io/itext/io/font/constants/FontDescriptorFlags.cs index 032ebcedb4..9ff1b2178b 100644 --- a/itext/itext.io/itext/io/font/constants/FontDescriptorFlags.cs +++ b/itext/itext.io/itext/io/font/constants/FontDescriptorFlags.cs @@ -26,22 +26,22 @@ public sealed class FontDescriptorFlags { private FontDescriptorFlags() { } - public static int FixedPitch = 1; + public const int FIXED_PITCH = 1; - public static int Serif = 1 << 1; + public const int SERIF = 1 << 1; - public static int Symbolic = 1 << 2; + public const int SYMBOLIC = 1 << 2; - public static int Script = 1 << 3; + public const int SCRIPT = 1 << 3; - public static int Nonsymbolic = 1 << 5; + public const int NONSYMBOLIC = 1 << 5; - public static int Italic = 1 << 6; + public const int ITALIC = 1 << 6; - public static int AllCap = 1 << 16; + public const int ALL_CAP = 1 << 16; - public static int SmallCap = 1 << 17; + public const int SMALL_CAP = 1 << 17; - public static int ForceBold = 1 << 18; + public const int FORCE_BOLD = 1 << 18; } } diff --git a/itext/itext.io/itext/io/font/otf/ActualTextIterator.cs b/itext/itext.io/itext/io/font/otf/ActualTextIterator.cs index f02ad72266..5527746712 100644 --- a/itext/itext.io/itext/io/font/otf/ActualTextIterator.cs +++ b/itext/itext.io/itext/io/font/otf/ActualTextIterator.cs @@ -35,7 +35,7 @@ public class ActualTextIterator : IEnumerator public ActualTextIterator(GlyphLine glyphLine) { this.glyphLine = glyphLine; - this.pos = glyphLine.start; + this.pos = glyphLine.GetStart(); } public ActualTextIterator(GlyphLine glyphLine, int start, int end) @@ -61,25 +61,25 @@ public void Reset() public GlyphLine.GlyphLinePart Next() { if (glyphLine.actualText == null) { - GlyphLine.GlyphLinePart result = new GlyphLine.GlyphLinePart(pos, glyphLine.end, + GlyphLine.GlyphLinePart result = new GlyphLine.GlyphLinePart(pos, glyphLine.GetEnd(), null); - pos = glyphLine.end; + pos = glyphLine.GetEnd(); return result; } else { GlyphLine.GlyphLinePart currentResult = NextGlyphLinePart(pos); if (currentResult == null) { return null; } - pos = currentResult.end; + pos = currentResult.GetEnd(); if (!GlyphLinePartNeedsActualText(currentResult)) { - currentResult.actualText = null; + currentResult.SetActualText(null); // Try to add more pieces without "actual text" - while (pos < glyphLine.end) { + while (pos < glyphLine.GetEnd()) { GlyphLine.GlyphLinePart nextResult = NextGlyphLinePart(pos); if (nextResult != null && !GlyphLinePartNeedsActualText(nextResult)) { - currentResult.end = nextResult.end; - pos = nextResult.end; + currentResult.SetEnd(nextResult.GetEnd()); + pos = nextResult.GetEnd(); } else { break; } @@ -91,7 +91,7 @@ public GlyphLine.GlyphLinePart Next() { } public bool HasNext() { - return pos < glyphLine.end; + return pos < glyphLine.GetEnd(); } @@ -104,29 +104,29 @@ object IEnumerator.Current private GlyphLine.GlyphLinePart NextGlyphLinePart(int pos) { - if (pos >= glyphLine.end) + if (pos >= glyphLine.GetEnd()) { return null; } int startPos = pos; GlyphLine.ActualText startActualText = glyphLine.actualText[pos]; - while (pos < glyphLine.end && glyphLine.actualText[pos] == startActualText) + while (pos < glyphLine.GetEnd() && glyphLine.actualText[pos] == startActualText) { pos++; } return new GlyphLine.GlyphLinePart(startPos, pos, startActualText != null ? startActualText - .value : null); + .GetValue() : null); } private bool GlyphLinePartNeedsActualText(GlyphLine.GlyphLinePart glyphLinePart) { - if (glyphLinePart.actualText == null) + if (glyphLinePart.GetActualText() == null) { return false; } bool needsActualText = false; StringBuilder toUnicodeMapResult = new StringBuilder(); - for (int i = glyphLinePart.start; i < glyphLinePart.end; i++) + for (int i = glyphLinePart.GetStart(); i < glyphLinePart.GetEnd(); i++) { Glyph currentGlyph = glyphLine.glyphs[i]; if (!currentGlyph.HasValidUnicode()) @@ -136,7 +136,7 @@ private bool GlyphLinePartNeedsActualText(GlyphLine.GlyphLinePart glyphLinePart) } toUnicodeMapResult.Append(TextUtil.ConvertFromUtf32(currentGlyph.GetUnicode())); } - return needsActualText || !toUnicodeMapResult.ToString().Equals(glyphLinePart.actualText + return needsActualText || !toUnicodeMapResult.ToString().Equals(glyphLinePart.GetActualText() ); } diff --git a/itext/itext.io/itext/io/font/otf/ChainingContextualTable.cs b/itext/itext.io/itext/io/font/otf/ChainingContextualTable.cs index 26a1127809..a17d487b17 100644 --- a/itext/itext.io/itext/io/font/otf/ChainingContextualTable.cs +++ b/itext/itext.io/itext/io/font/otf/ChainingContextualTable.cs @@ -30,17 +30,17 @@ protected internal ChainingContextualTable(OpenTypeFontTableReader openReader, i } public override T GetMatchingContextRule(GlyphLine line) { - if (line.idx >= line.end) { + if (line.GetIdx() >= line.GetEnd()) { return null; } - Glyph g = line.Get(line.idx); + Glyph g = line.Get(line.GetIdx()); IList rules = GetSetOfRulesForStartGlyph(g.GetCode()); foreach (T rule in rules) { int lastGlyphIndex = CheckIfContextMatch(line, rule); if (lastGlyphIndex != -1 && CheckIfLookaheadContextMatch(line, rule, lastGlyphIndex) && CheckIfBacktrackContextMatch (line, rule)) { - line.start = line.idx; - line.end = lastGlyphIndex + 1; + line.SetStart(line.GetIdx()); + line.SetEnd(lastGlyphIndex + 1); return rule; } } @@ -54,11 +54,11 @@ public override T GetMatchingContextRule(GlyphLine line) { /// true if given glyph line at the given position matches given rule protected internal virtual bool CheckIfLookaheadContextMatch(GlyphLine line, T rule, int startIdx) { OpenTableLookup.GlyphIndexer gidx = new OpenTableLookup.GlyphIndexer(); - gidx.line = line; - gidx.idx = startIdx; + gidx.SetLine(line); + gidx.SetIdx(startIdx); for (int j = 0; j < rule.GetLookaheadContextLength(); ++j) { gidx.NextGlyph(openReader, lookupFlag); - if (gidx.glyph == null || !rule.IsGlyphMatchesLookahead(gidx.glyph.GetCode(), j)) { + if (gidx.GetGlyph() == null || !rule.IsGlyphMatchesLookahead(gidx.GetGlyph().GetCode(), j)) { return false; } } @@ -71,11 +71,11 @@ protected internal virtual bool CheckIfLookaheadContextMatch(GlyphLine line, T r /// true if given glyph line matches given rule protected internal virtual bool CheckIfBacktrackContextMatch(GlyphLine line, T rule) { OpenTableLookup.GlyphIndexer gidx = new OpenTableLookup.GlyphIndexer(); - gidx.line = line; - gidx.idx = line.idx; + gidx.SetLine(line); + gidx.SetIdx(line.GetIdx()); for (int j = 0; j < rule.GetBacktrackContextLength(); ++j) { gidx.PreviousGlyph(openReader, lookupFlag); - if (gidx.glyph == null || !rule.IsGlyphMatchesBacktrack(gidx.glyph.GetCode(), j)) { + if (gidx.GetGlyph() == null || !rule.IsGlyphMatchesBacktrack(gidx.GetGlyph().GetCode(), j)) { return false; } } diff --git a/itext/itext.io/itext/io/font/otf/ContextualTable.cs b/itext/itext.io/itext/io/font/otf/ContextualTable.cs index d92c046869..09d5fe0bdf 100644 --- a/itext/itext.io/itext/io/font/otf/ContextualTable.cs +++ b/itext/itext.io/itext/io/font/otf/ContextualTable.cs @@ -46,16 +46,16 @@ protected internal ContextualTable(OpenTypeFontTableReader openReader, int looku /// a line, which is to be checked if it matches some context. /// matching context rule or null, if none was found. public virtual T GetMatchingContextRule(GlyphLine line) { - if (line.idx >= line.end) { + if (line.GetIdx() >= line.GetEnd()) { return null; } - Glyph g = line.Get(line.idx); + Glyph g = line.Get(line.GetIdx()); IList rules = GetSetOfRulesForStartGlyph(g.GetCode()); foreach (T rule in rules) { int lastGlyphIndex = CheckIfContextMatch(line, rule); if (lastGlyphIndex != -1) { - line.start = line.idx; - line.end = lastGlyphIndex + 1; + line.SetStart(line.GetIdx()); + line.SetEnd(lastGlyphIndex + 1); return rule; } } @@ -82,18 +82,18 @@ public virtual T GetMatchingContextRule(GlyphLine line) { protected internal virtual int CheckIfContextMatch(GlyphLine line, T rule) { int j; OpenTableLookup.GlyphIndexer gidx = new OpenTableLookup.GlyphIndexer(); - gidx.line = line; - gidx.idx = line.idx; + gidx.SetLine(line); + gidx.SetIdx(line.GetIdx()); //Note, that starting index shall be 1 for (j = 1; j < rule.GetContextLength(); ++j) { gidx.NextGlyph(openReader, lookupFlag); - if (gidx.glyph == null || !rule.IsGlyphMatchesInput(gidx.glyph.GetCode(), j)) { + if (gidx.GetGlyph() == null || !rule.IsGlyphMatchesInput(gidx.GetGlyph().GetCode(), j)) { break; } } bool isMatch = j == rule.GetContextLength(); if (isMatch) { - return gidx.idx; + return gidx.GetIdx(); } else { return -1; diff --git a/itext/itext.io/itext/io/font/otf/FeatureRecord.cs b/itext/itext.io/itext/io/font/otf/FeatureRecord.cs index 8be55423b8..ee3483ff2f 100644 --- a/itext/itext.io/itext/io/font/otf/FeatureRecord.cs +++ b/itext/itext.io/itext/io/font/otf/FeatureRecord.cs @@ -24,8 +24,32 @@ You should have received a copy of the GNU Affero General Public License namespace iText.IO.Font.Otf { public class FeatureRecord { - public String tag; + private String tag; - public int[] lookups; + private int[] lookups; + + /// Retrieves the tag of the feature record. + /// tag + public virtual String GetTag() { + return tag; + } + + /// Sets the tag of the feature record. + /// tag + public virtual void SetTag(String tag) { + this.tag = tag; + } + + /// Retrieves the lookups of the feature record. + /// lookups + public virtual int[] GetLookups() { + return lookups; + } + + /// Sets the lookups of the feature record. + /// lookups + public virtual void SetLookups(int[] lookups) { + this.lookups = lookups; + } } } diff --git a/itext/itext.io/itext/io/font/otf/GlyphLine.cs b/itext/itext.io/itext/io/font/otf/GlyphLine.cs index 10380b8c68..ee128c07c2 100644 --- a/itext/itext.io/itext/io/font/otf/GlyphLine.cs +++ b/itext/itext.io/itext/io/font/otf/GlyphLine.cs @@ -26,11 +26,11 @@ You should have received a copy of the GNU Affero General Public License namespace iText.IO.Font.Otf { public class GlyphLine { - public int start; + private int start; - public int end; + private int end; - public int idx; + private int idx; protected internal IList glyphs; @@ -93,6 +93,42 @@ public GlyphLine(iText.IO.Font.Otf.GlyphLine other, int start, int end) { this.idx = other.idx - start; } + /// Retrieves the start of the glyph line. + /// start of glyph line + public virtual int GetStart() { + return start; + } + + /// Sets the start of the glyph line. + /// start of glyph line + public virtual void SetStart(int start) { + this.start = start; + } + + /// Retrieves the end of the glyph line. + /// end of glyph line + public virtual int GetEnd() { + return end; + } + + /// Sets the end of the glyph line. + /// end of glyph line + public virtual void SetEnd(int end) { + this.end = end; + } + + /// Retrieves the idx of the glyph line. + /// idx of glyph line + public virtual int GetIdx() { + return idx; + } + + /// Sets the idx of the glyph line. + /// idx of glyph line + public virtual void SetIdx(int idx) { + this.idx = idx; + } + /// Get the unicode string representation of the GlyphLine slice. /// starting index of the slice /// terminating index of the slice @@ -102,11 +138,11 @@ public virtual String ToUnicodeString(int start, int end) { StringBuilder str = new StringBuilder(); while (iter.HasNext()) { GlyphLine.GlyphLinePart part = iter.Next(); - if (part.actualText != null) { - str.Append(part.actualText); + if (part.GetActualText() != null) { + str.Append(part.GetActualText()); } else { - for (int i = part.start; i < part.end; i++) { + for (int i = part.GetStart(); i < part.GetEnd(); i++) { str.Append(glyphs[i].GetUnicodeChars()); } } @@ -124,9 +160,9 @@ public override String ToString() { /// new GlyphLine containing the copied slice public virtual iText.IO.Font.Otf.GlyphLine Copy(int left, int right) { iText.IO.Font.Otf.GlyphLine glyphLine = new iText.IO.Font.Otf.GlyphLine(); - glyphLine.start = 0; - glyphLine.end = right - left; - glyphLine.glyphs = new List(glyphs.SubList(left, right)); + glyphLine.SetStart(0); + glyphLine.SetEnd(right - left); + glyphLine.SetGlyphs(new List(glyphs.SubList(left, right))); glyphLine.actualText = actualText == null ? null : new List(actualText.SubList(left, right)); return glyphLine; @@ -176,9 +212,9 @@ public virtual void Add(iText.IO.Font.Otf.GlyphLine other) { actualText.Add(null); } } - actualText.AddAll(other.actualText.SubList(other.start, other.end)); + actualText.AddAll(other.actualText.SubList(other.GetStart(), other.GetEnd())); } - glyphs.AddAll(other.glyphs.SubList(other.start, other.end)); + glyphs.AddAll(other.glyphs.SubList(other.GetStart(), other.GetEnd())); if (null != actualText) { while (actualText.Count < glyphs.Count) { actualText.Add(null); @@ -203,8 +239,8 @@ public virtual void ReplaceContent(iText.IO.Font.Otf.GlyphLine other) { else { actualText = null; } - start = other.start; - end = other.end; + start = other.GetStart(); + end = other.GetEnd(); } public virtual int Size() { @@ -214,8 +250,8 @@ public virtual int Size() { public virtual void SubstituteManyToOne(OpenTypeFontTableReader tableReader, int lookupFlag, int rightPartLen , int substitutionGlyphIndex) { OpenTableLookup.GlyphIndexer gidx = new OpenTableLookup.GlyphIndexer(); - gidx.line = this; - gidx.idx = idx; + gidx.SetLine(this); + gidx.SetIdx(idx); StringBuilder chars = new StringBuilder(); Glyph currentGlyph = glyphs[idx]; if (currentGlyph.GetChars() != null) { @@ -228,7 +264,7 @@ public virtual void SubstituteManyToOne(OpenTypeFontTableReader tableReader, int } for (int j = 0; j < rightPartLen; ++j) { gidx.NextGlyph(tableReader, lookupFlag); - currentGlyph = glyphs[gidx.idx]; + currentGlyph = glyphs[gidx.GetIdx()]; if (currentGlyph.GetChars() != null) { chars.Append(currentGlyph.GetChars()); } @@ -237,7 +273,8 @@ public virtual void SubstituteManyToOne(OpenTypeFontTableReader tableReader, int chars.Append(iText.IO.Util.TextUtil.ConvertFromUtf32(currentGlyph.GetUnicode())); } } - RemoveGlyph(gidx.idx--); + RemoveGlyph(gidx.GetIdx()); + gidx.SetIdx(gidx.GetIdx() - 1); } char[] newChars = new char[chars.Length]; chars.GetChars(0, chars.Length, newChars, 0); @@ -403,25 +440,87 @@ public interface IGlyphLineFilter { } public class GlyphLinePart { - public int start; + private int start; - public int end; + private int end; // Might be null if it's not necessary - public String actualText; + private String actualText; - public bool reversed; + private bool reversed; + /// Creates a glyph line part object with given start and end values. + /// + /// Creates a glyph line part object with given start and end values. + /// Actual text is set to null. + /// + /// start value of the glyph line part + /// end value of the glyph line part public GlyphLinePart(int start, int end) : this(start, end, null) { } + /// Creates a glyph line part object with given start, end and actual text values. + /// start value of the glyph line part + /// end value of the glyph line part + /// actual text public GlyphLinePart(int start, int end, String actualText) { this.start = start; this.end = end; this.actualText = actualText; } + /// Retrieves the start of the glyph line part. + /// start value of glyph line part + public virtual int GetStart() { + return start; + } + + /// Sets the start of the glyph line part. + /// start of the glyph line part + /// Altered glyph line part object + public virtual GlyphLine.GlyphLinePart SetStart(int start) { + this.start = start; + return this; + } + + /// Retrieves the end of the glyph line part. + /// end value of glyph line part + public virtual int GetEnd() { + return end; + } + + /// Sets the end of the glyph line part. + /// end value of glyph line part + /// Altered glyph line part object + public virtual GlyphLine.GlyphLinePart SetEnd(int end) { + this.end = end; + return this; + } + + /// Retrieves the actual text of the glyph line part. + /// Actual text of glyph line part + public virtual String GetActualText() { + return actualText; + } + + /// Sets the actual text of the glyph line part. + /// Actual text of glyph line part + /// Altered Glyph line part object + public virtual GlyphLine.GlyphLinePart SetActualText(String actualText) { + this.actualText = actualText; + return this; + } + + /// Retrieves whether the glyph line part is reversed. + /// True if it is reversed, false otherwise. + public virtual bool IsReversed() { + return reversed; + } + + /// Sets whether the glyph line part is reversed. + /// true if it should be reversed, false otherwise + /// Altered glyph line part object public virtual GlyphLine.GlyphLinePart SetReversed(bool reversed) { this.reversed = reversed; return this; @@ -429,12 +528,18 @@ public virtual GlyphLine.GlyphLinePart SetReversed(bool reversed) { } protected internal class ActualText { - public String value; + private readonly String value; public ActualText(String value) { this.value = value; } + /// Retrieves the value of the actual text. + /// actual text value + public virtual String GetValue() { + return value; + } + public override bool Equals(Object obj) { if (this == obj) { return true; @@ -443,7 +548,7 @@ public override bool Equals(Object obj) { return false; } GlyphLine.ActualText other = (GlyphLine.ActualText)obj; - return value == null && other.value == null || value.Equals(other.value); + return value == null && other.GetValue() == null || value.Equals(other.GetValue()); } public override int GetHashCode() { diff --git a/itext/itext.io/itext/io/font/otf/GposAnchor.cs b/itext/itext.io/itext/io/font/otf/GposAnchor.cs index dd1d8ea696..6a7ffb0824 100644 --- a/itext/itext.io/itext/io/font/otf/GposAnchor.cs +++ b/itext/itext.io/itext/io/font/otf/GposAnchor.cs @@ -22,16 +22,42 @@ You should have received a copy of the GNU Affero General Public License */ namespace iText.IO.Font.Otf { public class GposAnchor { - public int XCoordinate; + private int xCoordinate; - public int YCoordinate; + private int yCoordinate; public GposAnchor() { } + /// Creates a Gpos Anchor object based on a given Gpos Anchor object. + /// other Gpos Anchor object public GposAnchor(iText.IO.Font.Otf.GposAnchor other) { - this.XCoordinate = other.XCoordinate; - this.YCoordinate = other.YCoordinate; + this.xCoordinate = other.xCoordinate; + this.yCoordinate = other.yCoordinate; + } + + /// Retrieves the X coordinate of the Gpos Anchor. + /// X coordinate + public virtual int GetXCoordinate() { + return xCoordinate; + } + + /// Sets the x coordinate of the Gpos Anchor. + /// X coordinate + public virtual void SetXCoordinate(int xCoordinate) { + this.xCoordinate = xCoordinate; + } + + /// Retrieves the Y coordinate of the Gpos Anchor. + /// Y coordinate + public virtual int GetYCoordinate() { + return yCoordinate; + } + + /// Sets the Y coordinate of the Gpos Anchor. + /// Y coordinate + public virtual void SetYCoordinate(int yCoordinate) { + this.yCoordinate = yCoordinate; } } } diff --git a/itext/itext.io/itext/io/font/otf/GposLookupType1.cs b/itext/itext.io/itext/io/font/otf/GposLookupType1.cs index 74af241f5d..5ddfdbe21b 100644 --- a/itext/itext.io/itext/io/font/otf/GposLookupType1.cs +++ b/itext/itext.io/itext/io/font/otf/GposLookupType1.cs @@ -34,24 +34,24 @@ public GposLookupType1(OpenTypeFontTableReader openReader, int lookupFlag, int[] } public override bool TransformOne(GlyphLine line) { - if (line.idx >= line.end) { + if (line.GetIdx() >= line.GetEnd()) { return false; } - if (openReader.IsSkip(line.Get(line.idx).GetCode(), lookupFlag)) { - line.idx++; + if (openReader.IsSkip(line.Get(line.GetIdx()).GetCode(), lookupFlag)) { + line.SetIdx(line.GetIdx() + 1); return false; } - int glyphCode = line.Get(line.idx).GetCode(); + int glyphCode = line.Get(line.GetIdx()).GetCode(); bool positionApplied = false; GposValueRecord valueRecord = valueRecordMap.Get(glyphCode); if (valueRecord != null) { - Glyph newGlyph = new Glyph(line.Get(line.idx)); - newGlyph.SetXAdvance((short)(newGlyph.GetXAdvance() + valueRecord.XAdvance)); - newGlyph.SetYAdvance((short)(newGlyph.GetYAdvance() + valueRecord.YAdvance)); - line.Set(line.idx, newGlyph); + Glyph newGlyph = new Glyph(line.Get(line.GetIdx())); + newGlyph.SetXAdvance((short)(newGlyph.GetXAdvance() + valueRecord.GetXAdvance())); + newGlyph.SetYAdvance((short)(newGlyph.GetYAdvance() + valueRecord.GetYAdvance())); + line.Set(line.GetIdx(), newGlyph); positionApplied = true; } - line.idx++; + line.SetIdx(line.GetIdx() + 1); return positionApplied; } diff --git a/itext/itext.io/itext/io/font/otf/GposLookupType2.cs b/itext/itext.io/itext/io/font/otf/GposLookupType2.cs index 233b8a00cb..f70a45346e 100644 --- a/itext/itext.io/itext/io/font/otf/GposLookupType2.cs +++ b/itext/itext.io/itext/io/font/otf/GposLookupType2.cs @@ -36,11 +36,11 @@ public GposLookupType2(OpenTypeFontTableReader openReader, int lookupFlag, int[] } public override bool TransformOne(GlyphLine line) { - if (line.idx >= line.end) { + if (line.GetIdx() >= line.GetEnd()) { return false; } - if (openReader.IsSkip(line.Get(line.idx).GetCode(), lookupFlag)) { - line.idx++; + if (openReader.IsSkip(line.Get(line.GetIdx()).GetCode(), lookupFlag)) { + line.SetIdx(line.GetIdx() + 1); return false; } foreach (OpenTableLookup lookup in listRules) { @@ -48,7 +48,7 @@ public override bool TransformOne(GlyphLine line) { return true; } } - ++line.idx; + line.SetIdx(line.GetIdx() + 1); return false; } @@ -82,24 +82,24 @@ public PairPosAdjustmentFormat1(OpenTypeFontTableReader openReader, int lookupFl } public override bool TransformOne(GlyphLine line) { - if (line.idx >= line.end || line.idx < line.start) { + if (line.GetIdx() >= line.GetEnd() || line.GetIdx() < line.GetStart()) { return false; } bool changed = false; - Glyph g1 = line.Get(line.idx); + Glyph g1 = line.Get(line.GetIdx()); IDictionary m = gposMap.Get(g1.GetCode()); if (m != null) { OpenTableLookup.GlyphIndexer gi = new OpenTableLookup.GlyphIndexer(); - gi.line = line; - gi.idx = line.idx; + gi.SetLine(line); + gi.SetIdx(line.GetIdx()); gi.NextGlyph(openReader, lookupFlag); - if (gi.glyph != null) { - GposLookupType2.PairValueFormat pv = m.Get(gi.glyph.GetCode()); + if (gi.GetGlyph() != null) { + GposLookupType2.PairValueFormat pv = m.Get(gi.GetGlyph().GetCode()); if (pv != null) { - Glyph g2 = gi.glyph; - line.Set(line.idx, new Glyph(g1, 0, 0, pv.first.XAdvance, pv.first.YAdvance, 0)); - line.Set(gi.idx, new Glyph(g2, 0, 0, pv.second.XAdvance, pv.second.YAdvance, 0)); - line.idx = gi.idx; + Glyph g2 = gi.GetGlyph(); + line.Set(line.GetIdx(), new Glyph(g1, 0, 0, pv.GetFirst().GetXAdvance(), pv.GetFirst().GetYAdvance(), 0)); + line.Set(gi.GetIdx(), new Glyph(g2, 0, 0, pv.GetSecond().GetXAdvance(), pv.GetSecond().GetYAdvance(), 0)); + line.SetIdx(gi.GetIdx()); changed = true; } } @@ -123,8 +123,8 @@ protected internal virtual void ReadFormat(int subTableLocation) { for (int j = 0; j < pairValueCount; ++j) { int glyph2 = openReader.rf.ReadUnsignedShort(); GposLookupType2.PairValueFormat pair = new GposLookupType2.PairValueFormat(); - pair.first = OtfReadCommon.ReadGposValueRecord(openReader, valueFormat1); - pair.second = OtfReadCommon.ReadGposValueRecord(openReader, valueFormat2); + pair.SetFirst(OtfReadCommon.ReadGposValueRecord(openReader, valueFormat1)); + pair.SetSecond(OtfReadCommon.ReadGposValueRecord(openReader, valueFormat2)); pairs.Put(glyph2, pair); } } @@ -151,10 +151,10 @@ public PairPosAdjustmentFormat2(OpenTypeFontTableReader openReader, int lookupFl } public override bool TransformOne(GlyphLine line) { - if (line.idx >= line.end || line.idx < line.start) { + if (line.GetIdx() >= line.GetEnd() || line.GetIdx() < line.GetStart()) { return false; } - Glyph g1 = line.Get(line.idx); + Glyph g1 = line.Get(line.GetIdx()); if (!coverageSet.Contains(g1.GetCode())) { return false; } @@ -164,21 +164,21 @@ public override bool TransformOne(GlyphLine line) { return false; } OpenTableLookup.GlyphIndexer gi = new OpenTableLookup.GlyphIndexer(); - gi.line = line; - gi.idx = line.idx; + gi.SetLine(line); + gi.SetIdx(line.GetIdx()); gi.NextGlyph(openReader, lookupFlag); - if (gi.glyph == null) { + if (gi.GetGlyph() == null) { return false; } - Glyph g2 = gi.glyph; + Glyph g2 = gi.GetGlyph(); int c2 = classDef2.GetOtfClass(g2.GetCode()); if (c2 >= pvs.Length) { return false; } GposLookupType2.PairValueFormat pv = pvs[c2]; - line.Set(line.idx, new Glyph(g1, 0, 0, pv.first.XAdvance, pv.first.YAdvance, 0)); - line.Set(gi.idx, new Glyph(g2, 0, 0, pv.second.XAdvance, pv.second.YAdvance, 0)); - line.idx = gi.idx; + line.Set(line.GetIdx(), new Glyph(g1, 0, 0, pv.GetFirst().GetXAdvance(), pv.GetFirst().GetYAdvance(), 0)); + line.Set(gi.GetIdx(), new Glyph(g2, 0, 0, pv.GetSecond().GetXAdvance(), pv.GetSecond().GetYAdvance(), 0)); + line.SetIdx(gi.GetIdx()); return true; } @@ -195,8 +195,8 @@ protected internal virtual void ReadFormat(int subTableLocation) { posSubs.Put(k, pairs); for (int j = 0; j < class2Count; ++j) { GposLookupType2.PairValueFormat pair = new GposLookupType2.PairValueFormat(); - pair.first = OtfReadCommon.ReadGposValueRecord(openReader, valueFormat1); - pair.second = OtfReadCommon.ReadGposValueRecord(openReader, valueFormat2); + pair.SetFirst(OtfReadCommon.ReadGposValueRecord(openReader, valueFormat1)); + pair.SetSecond(OtfReadCommon.ReadGposValueRecord(openReader, valueFormat2)); pairs[j] = pair; } } @@ -211,9 +211,33 @@ protected internal override void ReadSubTable(int subTableLocation) { } private class PairValueFormat { - public GposValueRecord first; + private GposValueRecord first; - public GposValueRecord second; + private GposValueRecord second; + + /// Retrieves the first object of the pair. + /// first object + public virtual GposValueRecord GetFirst() { + return first; + } + + /// Sets the first object of the pair. + /// first object + public virtual void SetFirst(GposValueRecord first) { + this.first = first; + } + + /// Retrieves the second object of the pair. + /// second object + public virtual GposValueRecord GetSecond() { + return second; + } + + /// Sets the second object of the pair. + /// second object + public virtual void SetSecond(GposValueRecord second) { + this.second = second; + } } } } diff --git a/itext/itext.io/itext/io/font/otf/GposLookupType4.cs b/itext/itext.io/itext/io/font/otf/GposLookupType4.cs index 2a93f91b37..199bd00ab6 100644 --- a/itext/itext.io/itext/io/font/otf/GposLookupType4.cs +++ b/itext/itext.io/itext/io/font/otf/GposLookupType4.cs @@ -37,60 +37,61 @@ public GposLookupType4(OpenTypeFontTableReader openReader, int lookupFlag, int[] } public override bool TransformOne(GlyphLine line) { - if (line.idx >= line.end) { + if (line.GetIdx() >= line.GetEnd()) { return false; } - if (openReader.IsSkip(line.Get(line.idx).GetCode(), lookupFlag)) { - line.idx++; + if (openReader.IsSkip(line.Get(line.GetIdx()).GetCode(), lookupFlag)) { + line.SetIdx(line.GetIdx() + 1); return false; } bool changed = false; OpenTableLookup.GlyphIndexer gi = null; foreach (GposLookupType4.MarkToBase mb in marksbases) { - OtfMarkRecord omr = mb.marks.Get(line.Get(line.idx).GetCode()); + OtfMarkRecord omr = mb.marks.Get(line.Get(line.GetIdx()).GetCode()); if (omr == null) { continue; } if (gi == null) { gi = new OpenTableLookup.GlyphIndexer(); - gi.idx = line.idx; - gi.line = line; + gi.SetIdx(line.GetIdx()); + gi.SetLine(line); while (true) { gi.PreviousGlyph(openReader, lookupFlag); - if (gi.glyph == null) { + if (gi.GetGlyph() == null) { break; } // not mark => base glyph - if (openReader.GetGlyphClass(gi.glyph.GetCode()) != OtfClass.GLYPH_MARK) { + if (openReader.GetGlyphClass(gi.GetGlyph().GetCode()) != OtfClass.GLYPH_MARK) { break; } } - if (gi.glyph == null) { + if (gi.GetGlyph() == null) { break; } } - GposAnchor[] gpas = mb.bases.Get(gi.glyph.GetCode()); + GposAnchor[] gpas = mb.bases.Get(gi.GetGlyph().GetCode()); if (gpas == null) { continue; } - int markClass = omr.markClass; + int markClass = omr.GetMarkClass(); int xPlacement = 0; int yPlacement = 0; GposAnchor baseAnchor = gpas[markClass]; if (baseAnchor != null) { - xPlacement = baseAnchor.XCoordinate; - yPlacement = baseAnchor.YCoordinate; + xPlacement = baseAnchor.GetXCoordinate(); + yPlacement = baseAnchor.GetYCoordinate(); } - GposAnchor markAnchor = omr.anchor; + GposAnchor markAnchor = omr.GetAnchor(); if (markAnchor != null) { - xPlacement -= markAnchor.XCoordinate; - yPlacement -= markAnchor.YCoordinate; + xPlacement -= markAnchor.GetXCoordinate(); + yPlacement -= markAnchor.GetYCoordinate(); } - line.Set(line.idx, new Glyph(line.Get(line.idx), xPlacement, yPlacement, 0, 0, gi.idx - line.idx)); + line.Set(line.GetIdx(), new Glyph(line.Get(line.GetIdx()), xPlacement, yPlacement, 0, 0, gi.GetIdx() - line + .GetIdx())); changed = true; break; } - line.idx++; + line.SetIdx(line.GetIdx() + 1); return changed; } diff --git a/itext/itext.io/itext/io/font/otf/GposLookupType5.cs b/itext/itext.io/itext/io/font/otf/GposLookupType5.cs index be037e7a7c..925bed4d6e 100644 --- a/itext/itext.io/itext/io/font/otf/GposLookupType5.cs +++ b/itext/itext.io/itext/io/font/otf/GposLookupType5.cs @@ -37,43 +37,43 @@ public GposLookupType5(OpenTypeFontTableReader openReader, int lookupFlag, int[] } public override bool TransformOne(GlyphLine line) { - if (line.idx >= line.end) { + if (line.GetIdx() >= line.GetEnd()) { return false; } - if (openReader.IsSkip(line.Get(line.idx).GetCode(), lookupFlag)) { - line.idx++; + if (openReader.IsSkip(line.Get(line.GetIdx()).GetCode(), lookupFlag)) { + line.SetIdx(line.GetIdx() + 1); return false; } bool changed = false; OpenTableLookup.GlyphIndexer ligatureGlyphIndexer = null; foreach (GposLookupType5.MarkToLigature mb in marksligatures) { - OtfMarkRecord omr = mb.marks.Get(line.Get(line.idx).GetCode()); + OtfMarkRecord omr = mb.marks.Get(line.Get(line.GetIdx()).GetCode()); if (omr == null) { continue; } if (ligatureGlyphIndexer == null) { ligatureGlyphIndexer = new OpenTableLookup.GlyphIndexer(); - ligatureGlyphIndexer.idx = line.idx; - ligatureGlyphIndexer.line = line; + ligatureGlyphIndexer.SetIdx(line.GetIdx()); + ligatureGlyphIndexer.SetLine(line); while (true) { ligatureGlyphIndexer.PreviousGlyph(openReader, lookupFlag); - if (ligatureGlyphIndexer.glyph == null) { + if (ligatureGlyphIndexer.GetGlyph() == null) { break; } // not mark => ligature glyph - if (!mb.marks.ContainsKey(ligatureGlyphIndexer.glyph.GetCode())) { + if (!mb.marks.ContainsKey(ligatureGlyphIndexer.GetGlyph().GetCode())) { break; } } - if (ligatureGlyphIndexer.glyph == null) { + if (ligatureGlyphIndexer.GetGlyph() == null) { break; } } - IList componentAnchors = mb.ligatures.Get(ligatureGlyphIndexer.glyph.GetCode()); + IList componentAnchors = mb.ligatures.Get(ligatureGlyphIndexer.GetGlyph().GetCode()); if (componentAnchors == null) { continue; } - int markClass = omr.markClass; + int markClass = omr.GetMarkClass(); // TODO DEVSIX-3732 For complex cases like (glyph1, glyph2, mark, glyph3) and // (glyph1, mark, glyph2, glyph3) when the base glyphs compose a ligature and the mark // is attached to the ligature afterwards, mark should be placed in the corresponding anchor @@ -90,16 +90,17 @@ public override bool TransformOne(GlyphLine line) { for (int component = componentAnchors.Count - 1; component >= 0; component--) { if (componentAnchors[component][markClass] != null) { GposAnchor baseAnchor = componentAnchors[component][markClass]; - GposAnchor markAnchor = omr.anchor; - line.Set(line.idx, new Glyph(line.Get(line.idx), baseAnchor.XCoordinate - markAnchor.XCoordinate, baseAnchor - .YCoordinate - markAnchor.YCoordinate, 0, 0, ligatureGlyphIndexer.idx - line.idx)); + GposAnchor markAnchor = omr.GetAnchor(); + line.Set(line.GetIdx(), new Glyph(line.Get(line.GetIdx()), baseAnchor.GetXCoordinate() - markAnchor.GetXCoordinate + (), baseAnchor.GetYCoordinate() - markAnchor.GetYCoordinate(), 0, 0, ligatureGlyphIndexer.GetIdx() - line + .GetIdx())); changed = true; break; } } break; } - line.idx++; + line.SetIdx(line.GetIdx() + 1); return changed; } diff --git a/itext/itext.io/itext/io/font/otf/GposLookupType6.cs b/itext/itext.io/itext/io/font/otf/GposLookupType6.cs index b742391e83..7570908b12 100644 --- a/itext/itext.io/itext/io/font/otf/GposLookupType6.cs +++ b/itext/itext.io/itext/io/font/otf/GposLookupType6.cs @@ -37,31 +37,31 @@ public GposLookupType6(OpenTypeFontTableReader openReader, int lookupFlag, int[] } public override bool TransformOne(GlyphLine line) { - if (line.idx >= line.end) { + if (line.GetIdx() >= line.GetEnd()) { return false; } - if (openReader.IsSkip(line.Get(line.idx).GetCode(), lookupFlag)) { - line.idx++; + if (openReader.IsSkip(line.Get(line.GetIdx()).GetCode(), lookupFlag)) { + line.SetIdx(line.GetIdx() + 1); return false; } bool changed = false; OpenTableLookup.GlyphIndexer gi = null; foreach (GposLookupType6.MarkToBaseMark mb in marksbases) { - OtfMarkRecord omr = mb.marks.Get(line.Get(line.idx).GetCode()); + OtfMarkRecord omr = mb.marks.Get(line.Get(line.GetIdx()).GetCode()); if (omr == null) { continue; } if (gi == null) { gi = new OpenTableLookup.GlyphIndexer(); - gi.idx = line.idx; - gi.line = line; + gi.SetIdx(line.GetIdx()); + gi.SetLine(line); while (true) { - int prev = gi.idx; + int prev = gi.GetIdx(); // avoid attaching this mark glyph to another very distant mark glyph bool foundBaseGlyph = false; gi.PreviousGlyph(openReader, lookupFlag); - if (gi.idx != -1) { - for (int i = gi.idx; i < prev; i++) { + if (gi.GetIdx() != -1) { + for (int i = gi.GetIdx(); i < prev; i++) { if (openReader.GetGlyphClass(line.Get(i).GetCode()) == OtfClass.GLYPH_BASE) { foundBaseGlyph = true; break; @@ -69,33 +69,33 @@ public override bool TransformOne(GlyphLine line) { } } if (foundBaseGlyph) { - gi.glyph = null; + gi.SetGlyph(null); break; } - if (gi.glyph == null) { + if (gi.GetGlyph() == null) { break; } - if (mb.baseMarks.ContainsKey(gi.glyph.GetCode())) { + if (mb.baseMarks.ContainsKey(gi.GetGlyph().GetCode())) { break; } } - if (gi.glyph == null) { + if (gi.GetGlyph() == null) { break; } } - GposAnchor[] gpas = mb.baseMarks.Get(gi.glyph.GetCode()); + GposAnchor[] gpas = mb.baseMarks.Get(gi.GetGlyph().GetCode()); if (gpas == null) { continue; } - int markClass = omr.markClass; + int markClass = omr.GetMarkClass(); GposAnchor baseAnchor = gpas[markClass]; - GposAnchor markAnchor = omr.anchor; - line.Set(line.idx, new Glyph(line.Get(line.idx), -markAnchor.XCoordinate + baseAnchor.XCoordinate, -markAnchor - .YCoordinate + baseAnchor.YCoordinate, 0, 0, gi.idx - line.idx)); + GposAnchor markAnchor = omr.GetAnchor(); + line.Set(line.GetIdx(), new Glyph(line.Get(line.GetIdx()), -markAnchor.GetXCoordinate() + baseAnchor.GetXCoordinate + (), -markAnchor.GetYCoordinate() + baseAnchor.GetYCoordinate(), 0, 0, gi.GetIdx() - line.GetIdx())); changed = true; break; } - line.idx++; + line.SetIdx(line.GetIdx() + 1); return changed; } diff --git a/itext/itext.io/itext/io/font/otf/GposLookupType7.cs b/itext/itext.io/itext/io/font/otf/GposLookupType7.cs index 1c8f93648d..8e77cefca0 100644 --- a/itext/itext.io/itext/io/font/otf/GposLookupType7.cs +++ b/itext/itext.io/itext/io/font/otf/GposLookupType7.cs @@ -46,36 +46,36 @@ public GposLookupType7(OpenTypeFontTableReader openReader, int lookupFlag, int[] public override bool TransformOne(GlyphLine line) { bool changed = false; - int oldLineStart = line.start; - int oldLineEnd = line.end; - int initialLineIndex = line.idx; + int oldLineStart = line.GetStart(); + int oldLineEnd = line.GetEnd(); + int initialLineIndex = line.GetIdx(); foreach (ContextualTable subTable in subTables) { ContextualPositionRule contextRule = subTable.GetMatchingContextRule(line); if (contextRule == null) { continue; } - int lineEndBeforeTransformations = line.end; + int lineEndBeforeTransformations = line.GetEnd(); PosLookupRecord[] posLookupRecords = contextRule.GetPosLookupRecords(); OpenTableLookup.GlyphIndexer gidx = new OpenTableLookup.GlyphIndexer(); - gidx.line = line; + gidx.SetLine(line); foreach (PosLookupRecord posRecord in posLookupRecords) { // There could be some skipped glyphs inside the context sequence, therefore currently GlyphIndexer and // nextGlyph method are used to get to the glyph at "substRecord.sequenceIndex" index - gidx.idx = initialLineIndex; + gidx.SetIdx(initialLineIndex); for (int i = 0; i < posRecord.sequenceIndex; ++i) { gidx.NextGlyph(openReader, lookupFlag); } - line.idx = gidx.idx; + line.SetIdx(gidx.GetIdx()); OpenTableLookup lookupTable = openReader.GetLookupTable(posRecord.lookupListIndex); changed = lookupTable.TransformOne(line) || changed; } - line.idx = line.end; - line.start = oldLineStart; - int lenDelta = lineEndBeforeTransformations - line.end; - line.end = oldLineEnd - lenDelta; + line.SetIdx(line.GetEnd()); + line.SetStart(oldLineStart); + int lenDelta = lineEndBeforeTransformations - line.GetEnd(); + line.SetEnd(oldLineEnd - lenDelta); return changed; } - line.idx++; + line.SetIdx(line.GetIdx() + 1); return changed; } diff --git a/itext/itext.io/itext/io/font/otf/GposValueRecord.cs b/itext/itext.io/itext/io/font/otf/GposValueRecord.cs index b4244d8504..cb84269d27 100644 --- a/itext/itext.io/itext/io/font/otf/GposValueRecord.cs +++ b/itext/itext.io/itext/io/font/otf/GposValueRecord.cs @@ -22,12 +22,60 @@ You should have received a copy of the GNU Affero General Public License */ namespace iText.IO.Font.Otf { public class GposValueRecord { - public int XPlacement; + private int xPlacement; - public int YPlacement; + private int yPlacement; - public int XAdvance; + private int xAdvance; - public int YAdvance; + private int yAdvance; + + /// Retrieves the X placement of the Gpos value record. + /// X placement + public virtual int GetXPlacement() { + return xPlacement; + } + + /// Sets the X placement of the Gpos value record. + /// X placement + public virtual void SetXPlacement(int xPlacement) { + this.xPlacement = xPlacement; + } + + /// Retrieves the Y placement of the Gpos value record. + /// Y placement + public virtual int GetYPlacement() { + return yPlacement; + } + + /// Sets the Y placement of the Gpos value record. + /// Y placement + public virtual void SetYPlacement(int yPlacement) { + this.yPlacement = yPlacement; + } + + /// Retrieves the X advance of the Gpos value record. + /// x advance + public virtual int GetXAdvance() { + return xAdvance; + } + + /// Sets the X advance of the Gpos value record. + /// X advance + public virtual void SetXAdvance(int xAdvance) { + this.xAdvance = xAdvance; + } + + /// Retrieves the Y advance of the Gpos value record. + /// Y advance + public virtual int GetYAdvance() { + return yAdvance; + } + + /// Sets the Y advance of the Gpos value record. + /// Y advance + public virtual void SetYAdvance(int yAdvance) { + this.yAdvance = yAdvance; + } } } diff --git a/itext/itext.io/itext/io/font/otf/GsubLookupType1.cs b/itext/itext.io/itext/io/font/otf/GsubLookupType1.cs index b44d0b4040..795c25da95 100644 --- a/itext/itext.io/itext/io/font/otf/GsubLookupType1.cs +++ b/itext/itext.io/itext/io/font/otf/GsubLookupType1.cs @@ -35,10 +35,10 @@ public GsubLookupType1(OpenTypeFontTableReader openReader, int lookupFlag, int[] } public override bool TransformOne(GlyphLine line) { - if (line.idx >= line.end) { + if (line.GetIdx() >= line.GetEnd()) { return false; } - Glyph g = line.Get(line.idx); + Glyph g = line.Get(line.GetIdx()); bool changed = false; if (!openReader.IsSkip(g.GetCode(), lookupFlag)) { int substCode = substMap.Get(g.GetCode()); @@ -48,7 +48,7 @@ public override bool TransformOne(GlyphLine line) { changed = true; } } - line.idx++; + line.SetIdx(line.GetIdx() + 1); return changed; } diff --git a/itext/itext.io/itext/io/font/otf/GsubLookupType2.cs b/itext/itext.io/itext/io/font/otf/GsubLookupType2.cs index 72470dea84..4733c3b5c5 100644 --- a/itext/itext.io/itext/io/font/otf/GsubLookupType2.cs +++ b/itext/itext.io/itext/io/font/otf/GsubLookupType2.cs @@ -35,10 +35,10 @@ public GsubLookupType2(OpenTypeFontTableReader openReader, int lookupFlag, int[] } public override bool TransformOne(GlyphLine line) { - if (line.idx >= line.end) { + if (line.GetIdx() >= line.GetEnd()) { return false; } - Glyph g = line.Get(line.idx); + Glyph g = line.Get(line.GetIdx()); bool changed = false; if (!openReader.IsSkip(g.GetCode(), lookupFlag)) { int[] substSequence = substMap.Get(g.GetCode()); @@ -50,7 +50,7 @@ public override bool TransformOne(GlyphLine line) { } } } - line.idx++; + line.SetIdx(line.GetIdx() + 1); return changed; } diff --git a/itext/itext.io/itext/io/font/otf/GsubLookupType3.cs b/itext/itext.io/itext/io/font/otf/GsubLookupType3.cs index 3e56e0f64d..81c68acf9a 100644 --- a/itext/itext.io/itext/io/font/otf/GsubLookupType3.cs +++ b/itext/itext.io/itext/io/font/otf/GsubLookupType3.cs @@ -34,10 +34,10 @@ public GsubLookupType3(OpenTypeFontTableReader openReader, int lookupFlag, int[] } public override bool TransformOne(GlyphLine line) { - if (line.idx >= line.end) { + if (line.GetIdx() >= line.GetEnd()) { return false; } - Glyph g = line.Get(line.idx); + Glyph g = line.Get(line.GetIdx()); bool changed = false; if (!openReader.IsSkip(g.GetCode(), lookupFlag)) { int[] substCode = substMap.Get(g.GetCode()); @@ -47,7 +47,7 @@ public override bool TransformOne(GlyphLine line) { changed = true; } } - line.idx++; + line.SetIdx(line.GetIdx() + 1); return changed; } diff --git a/itext/itext.io/itext/io/font/otf/GsubLookupType4.cs b/itext/itext.io/itext/io/font/otf/GsubLookupType4.cs index 024d31d91f..aad802a410 100644 --- a/itext/itext.io/itext/io/font/otf/GsubLookupType4.cs +++ b/itext/itext.io/itext/io/font/otf/GsubLookupType4.cs @@ -39,22 +39,22 @@ public GsubLookupType4(OpenTypeFontTableReader openReader, int lookupFlag, int[] } public override bool TransformOne(GlyphLine line) { - if (line.idx >= line.end) { + if (line.GetIdx() >= line.GetEnd()) { return false; } bool changed = false; - Glyph g = line.Get(line.idx); + Glyph g = line.Get(line.GetIdx()); bool match = false; if (ligatures.ContainsKey(g.GetCode()) && !openReader.IsSkip(g.GetCode(), lookupFlag)) { OpenTableLookup.GlyphIndexer gidx = new OpenTableLookup.GlyphIndexer(); - gidx.line = line; + gidx.SetLine(line); IList ligs = ligatures.Get(g.GetCode()); foreach (int[] lig in ligs) { match = true; - gidx.idx = line.idx; + gidx.SetIdx(line.GetIdx()); for (int j = 1; j < lig.Length; ++j) { gidx.NextGlyph(openReader, lookupFlag); - if (gidx.glyph == null || gidx.glyph.GetCode() != lig[j]) { + if (gidx.GetGlyph() == null || gidx.GetGlyph().GetCode() != lig[j]) { match = false; break; } @@ -68,7 +68,7 @@ public override bool TransformOne(GlyphLine line) { if (match) { changed = true; } - line.idx++; + line.SetIdx(line.GetIdx() + 1); return changed; } diff --git a/itext/itext.io/itext/io/font/otf/GsubLookupType5.cs b/itext/itext.io/itext/io/font/otf/GsubLookupType5.cs index f461b1cad9..50bbd8e01e 100644 --- a/itext/itext.io/itext/io/font/otf/GsubLookupType5.cs +++ b/itext/itext.io/itext/io/font/otf/GsubLookupType5.cs @@ -38,36 +38,36 @@ protected internal GsubLookupType5(OpenTypeFontTableReader openReader, int looku public override bool TransformOne(GlyphLine line) { bool changed = false; - int oldLineStart = line.start; - int oldLineEnd = line.end; - int initialLineIndex = line.idx; + int oldLineStart = line.GetStart(); + int oldLineEnd = line.GetEnd(); + int initialLineIndex = line.GetIdx(); foreach (ContextualTable subTable in subTables) { ContextualSubstRule contextRule = subTable.GetMatchingContextRule(line); if (contextRule == null) { continue; } - int lineEndBeforeSubstitutions = line.end; + int lineEndBeforeSubstitutions = line.GetEnd(); SubstLookupRecord[] substLookupRecords = contextRule.GetSubstLookupRecords(); OpenTableLookup.GlyphIndexer gidx = new OpenTableLookup.GlyphIndexer(); - gidx.line = line; + gidx.SetLine(line); foreach (SubstLookupRecord substRecord in substLookupRecords) { // There could be some skipped glyphs inside the context sequence, therefore currently GlyphIndexer and // nextGlyph method are used to get to the glyph at "substRecord.sequenceIndex" index - gidx.idx = initialLineIndex; + gidx.SetIdx(initialLineIndex); for (int i = 0; i < substRecord.sequenceIndex; ++i) { gidx.NextGlyph(openReader, lookupFlag); } - line.idx = gidx.idx; + line.SetIdx(gidx.GetIdx()); OpenTableLookup lookupTable = openReader.GetLookupTable(substRecord.lookupListIndex); changed = lookupTable.TransformOne(line) || changed; } - line.idx = line.end; - line.start = oldLineStart; - int lenDelta = lineEndBeforeSubstitutions - line.end; - line.end = oldLineEnd - lenDelta; + line.SetIdx(line.GetEnd()); + line.SetStart(oldLineStart); + int lenDelta = lineEndBeforeSubstitutions - line.GetEnd(); + line.SetEnd(oldLineEnd - lenDelta); return changed; } - ++line.idx; + line.SetIdx(line.GetIdx() + 1); return changed; } diff --git a/itext/itext.io/itext/io/font/otf/LanguageRecord.cs b/itext/itext.io/itext/io/font/otf/LanguageRecord.cs index be96e2a259..4f1765919f 100644 --- a/itext/itext.io/itext/io/font/otf/LanguageRecord.cs +++ b/itext/itext.io/itext/io/font/otf/LanguageRecord.cs @@ -24,10 +24,46 @@ You should have received a copy of the GNU Affero General Public License namespace iText.IO.Font.Otf { public class LanguageRecord { - public String tag; + private String tag; - public int featureRequired; + private int featureRequired; - public int[] features; + private int[] features; + + /// Retrieves the tag of the language record. + /// tag of record + public virtual String GetTag() { + return tag; + } + + /// Sets the tag of the language record. + /// tag of record + public virtual void SetTag(String tag) { + this.tag = tag; + } + + /// Retrieves the feature required of the language record. + /// feature required + public virtual int GetFeatureRequired() { + return featureRequired; + } + + /// Sets the feature required of the language record. + /// feature required + public virtual void SetFeatureRequired(int featureRequired) { + this.featureRequired = featureRequired; + } + + /// Retrieves the features of the language record. + /// features + public virtual int[] GetFeatures() { + return features; + } + + /// Sets the features of the language record. + /// features + public virtual void SetFeatures(int[] features) { + this.features = features; + } } } diff --git a/itext/itext.io/itext/io/font/otf/OpenTableLookup.cs b/itext/itext.io/itext/io/font/otf/OpenTableLookup.cs index 094795aff2..db9864a1f4 100644 --- a/itext/itext.io/itext/io/font/otf/OpenTableLookup.cs +++ b/itext/itext.io/itext/io/font/otf/OpenTableLookup.cs @@ -43,8 +43,8 @@ public virtual int GetLookupFlag() { public virtual bool TransformLine(GlyphLine line) { bool changed = false; - line.idx = line.start; - while (line.idx < line.end && line.idx >= line.start) { + line.SetIdx(line.GetStart()); + while (line.GetIdx() < line.GetEnd() && line.GetIdx() >= line.GetStart()) { changed = TransformOne(line) || changed; } return changed; @@ -63,15 +63,51 @@ protected internal virtual void ReadSubTables() { protected internal abstract void ReadSubTable(int subTableLocation); public class GlyphIndexer { - public GlyphLine line; + private GlyphLine line; - public Glyph glyph; + private Glyph glyph; - public int idx; + private int idx; + + /// Retrieves the glyph line of the object. + /// glyph line + public virtual GlyphLine GetLine() { + return line; + } + + /// Sets the glyph line of the object. + /// glyph line + public virtual void SetLine(GlyphLine line) { + this.line = line; + } + + /// Retrieves the glyph of the object. + /// glyph + public virtual Glyph GetGlyph() { + return glyph; + } + + /// Sets the glyph of the object. + /// glyph + public virtual void SetGlyph(Glyph glyph) { + this.glyph = glyph; + } + + /// Retrieves the idx of the glyph indexer. + /// idx + public virtual int GetIdx() { + return idx; + } + + /// Sets the idx of the glyph indexer. + /// idx + public virtual void SetIdx(int idx) { + this.idx = idx; + } public virtual void NextGlyph(OpenTypeFontTableReader openReader, int lookupFlag) { glyph = null; - while (++idx < line.end) { + while (++idx < line.GetEnd()) { Glyph g = line.Get(idx); if (!openReader.IsSkip(g.GetCode(), lookupFlag)) { glyph = g; @@ -82,7 +118,7 @@ public virtual void NextGlyph(OpenTypeFontTableReader openReader, int lookupFlag public virtual void PreviousGlyph(OpenTypeFontTableReader openReader, int lookupFlag) { glyph = null; - while (--idx >= line.start) { + while (--idx >= line.GetStart()) { Glyph g = line.Get(idx); if (!openReader.IsSkip(g.GetCode(), lookupFlag)) { glyph = g; diff --git a/itext/itext.io/itext/io/font/otf/OpenTypeFeature.cs b/itext/itext.io/itext/io/font/otf/OpenTypeFeature.cs index 9c252ff3ac..7c5befbb76 100644 --- a/itext/itext.io/itext/io/font/otf/OpenTypeFeature.cs +++ b/itext/itext.io/itext/io/font/otf/OpenTypeFeature.cs @@ -35,11 +35,11 @@ public OpenTypeFeature(OpenTypeFontTableReader openTypeReader, int locationFeatu TagAndLocation[] tagsLocs = openTypeReader.ReadTagAndLocations(locationFeatureTable); foreach (TagAndLocation tagLoc in tagsLocs) { // +2 don't use FeatureParams - openTypeReader.rf.Seek(tagLoc.location + 2L); + openTypeReader.rf.Seek(tagLoc.GetLocation() + 2L); int lookupCount = openTypeReader.rf.ReadUnsignedShort(); FeatureRecord rec = new FeatureRecord(); - rec.tag = tagLoc.tag; - rec.lookups = openTypeReader.ReadUShortArray(lookupCount); + rec.SetTag(tagLoc.GetTag()); + rec.SetLookups(openTypeReader.ReadUShortArray(lookupCount)); records.Add(rec); } } diff --git a/itext/itext.io/itext/io/font/otf/OpenTypeFontTableReader.cs b/itext/itext.io/itext/io/font/otf/OpenTypeFontTableReader.cs index 5de2b09faf..9603cf9ccc 100644 --- a/itext/itext.io/itext/io/font/otf/OpenTypeFontTableReader.cs +++ b/itext/itext.io/itext/io/font/otf/OpenTypeFontTableReader.cs @@ -77,7 +77,7 @@ public virtual IList GetFeatures(String[] scripts, String languag return null; } IList ret = new List(); - foreach (int f in rec.features) { + foreach (int f in rec.GetFeatures()) { ret.Add(featuresType.GetRecord(f)); } return ret; @@ -94,7 +94,7 @@ public virtual IList GetSpecificFeatures(IList fea } IList recs = new List(); foreach (FeatureRecord rec in features) { - if (hs.Contains(rec.tag)) { + if (hs.Contains(rec.GetTag())) { recs.Add(rec); } } @@ -106,13 +106,13 @@ public virtual FeatureRecord GetRequiredFeature(String[] scripts, String languag if (rec == null) { return null; } - return featuresType.GetRecord(rec.featureRequired); + return featuresType.GetRecord(rec.GetFeatureRequired()); } public virtual IList GetLookups(FeatureRecord[] features) { IntHashtable hash = new IntHashtable(); foreach (FeatureRecord rec in features) { - foreach (int idx in rec.lookups) { + foreach (int idx in rec.GetLookups()) { hash.Put(idx, 1); } } @@ -124,8 +124,8 @@ public virtual IList GetLookups(FeatureRecord[] features) { } public virtual IList GetLookups(FeatureRecord feature) { - IList ret = new List(feature.lookups.Length); - foreach (int idx in feature.lookups) { + IList ret = new List(feature.GetLookups().Length); + foreach (int idx in feature.GetLookups()) { ret.Add(lookupList[idx]); } return ret; @@ -152,14 +152,14 @@ public virtual LanguageRecord GetLanguageRecord(String otfScriptTag, String lang return null; } foreach (ScriptRecord record in GetScriptRecords()) { - if (!otfScriptTag.Equals(record.tag)) { + if (!otfScriptTag.Equals(record.GetTag())) { continue; } if (langTag == null) { - return record.defaultLanguage; + return record.GetDefaultLanguage(); } - foreach (LanguageRecord lang in record.languages) { - if (langTag.Equals(lang.tag)) { + foreach (LanguageRecord lang in record.GetLanguages()) { + if (langTag.Equals(lang.GetTag())) { return lang; } } @@ -203,8 +203,8 @@ protected internal virtual TagAndLocation[] ReadTagAndLocations(int baseLocation TagAndLocation[] tagslLocs = new TagAndLocation[count]; for (int k = 0; k < count; ++k) { TagAndLocation tl = new TagAndLocation(); - tl.tag = rf.ReadString(4, "utf-8"); - tl.location = rf.ReadUnsignedShort() + baseLocation; + tl.SetTag(rf.ReadString(4, "utf-8")); + tl.SetLocation(rf.ReadUnsignedShort() + baseLocation); tagslLocs[k] = tl; } return tagslLocs; diff --git a/itext/itext.io/itext/io/font/otf/OpenTypeScript.cs b/itext/itext.io/itext/io/font/otf/OpenTypeScript.cs index 01a7cefed3..51d2a46feb 100644 --- a/itext/itext.io/itext/io/font/otf/OpenTypeScript.cs +++ b/itext/itext.io/itext/io/font/otf/OpenTypeScript.cs @@ -49,14 +49,14 @@ public virtual LanguageRecord GetLanguageRecord(String[] scripts, String languag ScriptRecord scriptFound = null; ScriptRecord scriptDefault = null; foreach (ScriptRecord sr in records) { - if (DEFAULT_SCRIPT.Equals(sr.tag)) { + if (DEFAULT_SCRIPT.Equals(sr.GetTag())) { scriptDefault = sr; break; } } foreach (String script in scripts) { foreach (ScriptRecord sr in records) { - if (sr.tag.Equals(script)) { + if (sr.GetTag().Equals(script)) { scriptFound = sr; break; } @@ -75,36 +75,38 @@ public virtual LanguageRecord GetLanguageRecord(String[] scripts, String languag return null; } LanguageRecord lang = null; - foreach (LanguageRecord lr in scriptFound.languages) { - if (lr.tag.Equals(language)) { + foreach (LanguageRecord lr in scriptFound.GetLanguages()) { + if (lr.GetTag().Equals(language)) { lang = lr; break; } } if (lang == null) { - lang = scriptFound.defaultLanguage; + lang = scriptFound.GetDefaultLanguage(); } return lang; } private void ReadScriptRecord(TagAndLocation tagLoc) { - openTypeReader.rf.Seek(tagLoc.location); + openTypeReader.rf.Seek(tagLoc.GetLocation()); int locationDefaultLanguage = openTypeReader.rf.ReadUnsignedShort(); if (locationDefaultLanguage > 0) { - locationDefaultLanguage += tagLoc.location; + locationDefaultLanguage += tagLoc.GetLocation(); } - TagAndLocation[] tagsLocs = openTypeReader.ReadTagAndLocations(tagLoc.location); + TagAndLocation[] tagsLocs = openTypeReader.ReadTagAndLocations(tagLoc.GetLocation()); ScriptRecord srec = new ScriptRecord(); - srec.tag = tagLoc.tag; - srec.languages = new LanguageRecord[tagsLocs.Length]; + srec.SetTag(tagLoc.GetTag()); + srec.SetLanguages(new LanguageRecord[tagsLocs.Length]); for (int k = 0; k < tagsLocs.Length; ++k) { - srec.languages[k] = ReadLanguageRecord(tagsLocs[k]); + LanguageRecord[] languages = srec.GetLanguages(); + languages[k] = ReadLanguageRecord(tagsLocs[k]); + srec.SetLanguages(languages); } if (locationDefaultLanguage > 0) { TagAndLocation t = new TagAndLocation(); - t.tag = ""; - t.location = locationDefaultLanguage; - srec.defaultLanguage = ReadLanguageRecord(t); + t.SetTag(""); + t.SetLocation(locationDefaultLanguage); + srec.SetDefaultLanguage(ReadLanguageRecord(t)); } records.Add(srec); } @@ -112,11 +114,11 @@ private void ReadScriptRecord(TagAndLocation tagLoc) { private LanguageRecord ReadLanguageRecord(TagAndLocation tagLoc) { LanguageRecord rec = new LanguageRecord(); //skip lookup order - openTypeReader.rf.Seek(tagLoc.location + 2); - rec.featureRequired = openTypeReader.rf.ReadUnsignedShort(); + openTypeReader.rf.Seek(tagLoc.GetLocation() + 2L); + rec.SetFeatureRequired(openTypeReader.rf.ReadUnsignedShort()); int count = openTypeReader.rf.ReadUnsignedShort(); - rec.features = openTypeReader.ReadUShortArray(count); - rec.tag = tagLoc.tag; + rec.SetFeatures(openTypeReader.ReadUShortArray(count)); + rec.SetTag(tagLoc.GetTag()); return rec; } } diff --git a/itext/itext.io/itext/io/font/otf/OtfMarkRecord.cs b/itext/itext.io/itext/io/font/otf/OtfMarkRecord.cs index c68aa08220..a8c2cb0003 100644 --- a/itext/itext.io/itext/io/font/otf/OtfMarkRecord.cs +++ b/itext/itext.io/itext/io/font/otf/OtfMarkRecord.cs @@ -22,8 +22,32 @@ You should have received a copy of the GNU Affero General Public License */ namespace iText.IO.Font.Otf { public class OtfMarkRecord { - public int markClass; + private int markClass; - public GposAnchor anchor; + private GposAnchor anchor; + + /// Retrieves the mark class of the OtfMarkRecord. + /// mark class + public virtual int GetMarkClass() { + return markClass; + } + + /// Sets the mark class of the OtfMarkRecord. + /// mark class + public virtual void SetMarkClass(int markClass) { + this.markClass = markClass; + } + + /// Retrieves the anchor of the OtfMarkRecord. + /// anchor + public virtual GposAnchor GetAnchor() { + return anchor; + } + + /// Sets the anchor of the OtfMarkRecord. + /// anchor + public virtual void SetAnchor(GposAnchor anchor) { + this.anchor = anchor; + } } } diff --git a/itext/itext.io/itext/io/font/otf/OtfReadCommon.cs b/itext/itext.io/itext/io/font/otf/OtfReadCommon.cs index 21e1035a59..2368ac1214 100644 --- a/itext/itext.io/itext/io/font/otf/OtfReadCommon.cs +++ b/itext/itext.io/itext/io/font/otf/OtfReadCommon.cs @@ -87,20 +87,20 @@ private static void ReadRangeRecord(RandomAccessFileOrArray rf, IList glyph public static GposValueRecord ReadGposValueRecord(OpenTypeFontTableReader tableReader, int mask) { GposValueRecord vr = new GposValueRecord(); if ((mask & 0x0001) != 0) { - vr.XPlacement = FontProgram.ConvertGlyphSpaceToTextSpace(tableReader.rf.ReadShort()) / tableReader.GetUnitsPerEm - (); + vr.SetXPlacement(FontProgram.ConvertGlyphSpaceToTextSpace(tableReader.rf.ReadShort()) / tableReader.GetUnitsPerEm + ()); } if ((mask & 0x0002) != 0) { - vr.YPlacement = FontProgram.ConvertGlyphSpaceToTextSpace(tableReader.rf.ReadShort()) / tableReader.GetUnitsPerEm - (); + vr.SetYPlacement(FontProgram.ConvertGlyphSpaceToTextSpace(tableReader.rf.ReadShort()) / tableReader.GetUnitsPerEm + ()); } if ((mask & 0x0004) != 0) { - vr.XAdvance = FontProgram.ConvertGlyphSpaceToTextSpace(tableReader.rf.ReadShort()) / tableReader.GetUnitsPerEm - (); + vr.SetXAdvance(FontProgram.ConvertGlyphSpaceToTextSpace(tableReader.rf.ReadShort()) / tableReader.GetUnitsPerEm + ()); } if ((mask & 0x0008) != 0) { - vr.YAdvance = FontProgram.ConvertGlyphSpaceToTextSpace(tableReader.rf.ReadShort()) / tableReader.GetUnitsPerEm - (); + vr.SetYAdvance(FontProgram.ConvertGlyphSpaceToTextSpace(tableReader.rf.ReadShort()) / tableReader.GetUnitsPerEm + ()); } if ((mask & 0x0010) != 0) { tableReader.rf.Skip(2); @@ -127,10 +127,10 @@ public static GposAnchor ReadGposAnchor(OpenTypeFontTableReader tableReader, int switch (format) { default: { t = new GposAnchor(); - t.XCoordinate = FontProgram.ConvertGlyphSpaceToTextSpace(tableReader.rf.ReadShort()) / tableReader.GetUnitsPerEm - (); - t.YCoordinate = FontProgram.ConvertGlyphSpaceToTextSpace(tableReader.rf.ReadShort()) / tableReader.GetUnitsPerEm - (); + t.SetXCoordinate(FontProgram.ConvertGlyphSpaceToTextSpace(tableReader.rf.ReadShort()) / tableReader.GetUnitsPerEm + ()); + t.SetYCoordinate(FontProgram.ConvertGlyphSpaceToTextSpace(tableReader.rf.ReadShort()) / tableReader.GetUnitsPerEm + ()); break; } } @@ -150,8 +150,8 @@ public static IList ReadMarkArray(OpenTypeFontTableReader tableRe IList marks = new List(); for (int k = 0; k < markCount; ++k) { OtfMarkRecord rec = new OtfMarkRecord(); - rec.markClass = classes[k]; - rec.anchor = ReadGposAnchor(tableReader, locations[k]); + rec.SetMarkClass(classes[k]); + rec.SetAnchor(ReadGposAnchor(tableReader, locations[k])); marks.Add(rec); } return marks; diff --git a/itext/itext.io/itext/io/font/otf/ScriptRecord.cs b/itext/itext.io/itext/io/font/otf/ScriptRecord.cs index 8af70bc8f9..226019200c 100644 --- a/itext/itext.io/itext/io/font/otf/ScriptRecord.cs +++ b/itext/itext.io/itext/io/font/otf/ScriptRecord.cs @@ -24,10 +24,46 @@ You should have received a copy of the GNU Affero General Public License namespace iText.IO.Font.Otf { public class ScriptRecord { - public String tag; + private String tag; - public LanguageRecord defaultLanguage; + private LanguageRecord defaultLanguage; - public LanguageRecord[] languages; + private LanguageRecord[] languages; + + /// Retrieves the tag of the Script Record. + /// tag of record + public virtual String GetTag() { + return tag; + } + + /// Sets the tag of the Script Record. + /// tag of record + public virtual void SetTag(String tag) { + this.tag = tag; + } + + /// Retrieves the default language of the Script Record. + /// default language + public virtual LanguageRecord GetDefaultLanguage() { + return defaultLanguage; + } + + /// Sets the default language of the Script Record. + /// default language + public virtual void SetDefaultLanguage(LanguageRecord defaultLanguage) { + this.defaultLanguage = defaultLanguage; + } + + /// Retrieves the languages of the Script Record. + /// languages + public virtual LanguageRecord[] GetLanguages() { + return languages; + } + + /// Sets the languages of the Script Record. + /// languages + public virtual void SetLanguages(LanguageRecord[] languages) { + this.languages = languages; + } } } diff --git a/itext/itext.io/itext/io/font/otf/TagAndLocation.cs b/itext/itext.io/itext/io/font/otf/TagAndLocation.cs index dc1af5a499..f68b704d5a 100644 --- a/itext/itext.io/itext/io/font/otf/TagAndLocation.cs +++ b/itext/itext.io/itext/io/font/otf/TagAndLocation.cs @@ -24,8 +24,32 @@ You should have received a copy of the GNU Affero General Public License namespace iText.IO.Font.Otf { public class TagAndLocation { - public String tag; + private String tag; - public int location; + private int location; + + /// Retrieves the tag of the object. + /// tag + public virtual String GetTag() { + return tag; + } + + /// Sets the tag of the object. + /// tag + public virtual void SetTag(String tag) { + this.tag = tag; + } + + /// Retrieves the location of the object. + /// location + public virtual int GetLocation() { + return location; + } + + /// Sets the location of the object. + /// location + public virtual void SetLocation(int location) { + this.location = location; + } } } diff --git a/itext/itext.io/itext/io/image/Jbig2ImageHelper.cs b/itext/itext.io/itext/io/image/Jbig2ImageHelper.cs index e7184b6997..806f5872b3 100644 --- a/itext/itext.io/itext/io/image/Jbig2ImageHelper.cs +++ b/itext/itext.io/itext/io/image/Jbig2ImageHelper.cs @@ -64,8 +64,8 @@ public static void ProcessImage(ImageData jbig2) { sr.Read(); Jbig2SegmentReader.Jbig2Page p = sr.GetPage(image.GetPage()); raf.Close(); - image.SetHeight(p.pageBitmapHeight); - image.SetWidth(p.pageBitmapWidth); + image.SetHeight(p.GetPageBitmapHeight()); + image.SetWidth(p.GetPageBitmapWidth()); image.SetBpc(1); image.SetColorEncodingComponentsNumber(1); byte[] globals = sr.GetGlobal(true); diff --git a/itext/itext.io/itext/io/image/Jpeg2000ImageData.cs b/itext/itext.io/itext/io/image/Jpeg2000ImageData.cs index d2ebfae3a7..5dd638aadb 100644 --- a/itext/itext.io/itext/io/image/Jpeg2000ImageData.cs +++ b/itext/itext.io/itext/io/image/Jpeg2000ImageData.cs @@ -28,15 +28,75 @@ You should have received a copy of the GNU Affero General Public License namespace iText.IO.Image { public class Jpeg2000ImageData : ImageData { public class Parameters { - public int numOfComps; + private int numOfComps; - public IList colorSpecBoxes = null; + private IList colorSpecBoxes = null; - public bool isJp2 = false; + private bool isJp2 = false; - public bool isJpxBaseline = false; + private bool isJpxBaseline = false; - public byte[] bpcBoxData; + private byte[] bpcBoxData; + + /// Retrieves number of components of the object. + /// number of components + public virtual int GetNumOfComps() { + return numOfComps; + } + + /// Sets number of components of the object. + /// number of components + public virtual void SetNumOfComps(int numOfComps) { + this.numOfComps = numOfComps; + } + + /// Retrieves the color spec boxes of the object. + /// color spec boxes + public virtual IList GetColorSpecBoxes() { + return colorSpecBoxes; + } + + /// Sets the color spec boxes of the object. + /// color spec boxes + public virtual void SetColorSpecBoxes(IList colorSpecBoxes) { + this.colorSpecBoxes = colorSpecBoxes; + } + + /// Retrieves whether the object is a Jp2. + /// true if it is a jp2, otherwise false + public virtual bool IsJp2() { + return isJp2; + } + + /// Sets whether the object is a jp2. + /// true is it is a jp2, otherwise false + public virtual void SetJp2(bool jp2) { + isJp2 = jp2; + } + + /// Retrieves whether jpx is baseline. + /// true if jpx is baseline, false otherwise + public virtual bool IsJpxBaseline() { + return isJpxBaseline; + } + + /// Sets whether jpx is baseline. + /// true if jpx is baseline, false otherwise + public virtual void SetJpxBaseline(bool jpxBaseline) { + isJpxBaseline = jpxBaseline; + } + + /// Retrieves the bits per component of the box data. + /// bits per component + public virtual byte[] GetBpcBoxData() { + return bpcBoxData; + } + + /// Sets the bits per component of the box data. + /// bits per component + public virtual void SetBpcBoxData(byte[] bpcBoxData) { + this.bpcBoxData = bpcBoxData; + } } public class ColorSpecBox : List { diff --git a/itext/itext.io/itext/io/image/Jpeg2000ImageHelper.cs b/itext/itext.io/itext/io/image/Jpeg2000ImageHelper.cs index 3ec2a12274..aeef16bc02 100644 --- a/itext/itext.io/itext/io/image/Jpeg2000ImageHelper.cs +++ b/itext/itext.io/itext/io/image/Jpeg2000ImageHelper.cs @@ -90,7 +90,7 @@ private static void ProcessParameters(Jpeg2000ImageData jp2) { Jpeg2000ImageHelper.Jpeg2000Box box = new Jpeg2000ImageHelper.Jpeg2000Box(); box.length = Cio_read(4, jpeg2000Stream); if (box.length == 0x0000000c) { - jp2.parameters.isJp2 = true; + jp2.parameters.SetJp2(true); box.type = Cio_read(4, jpeg2000Stream); if (JP2_JP != box.type) { throw new iText.IO.Exceptions.IOException(IoExceptionMessageConstant.EXPECTED_JP_MARKER); @@ -105,7 +105,7 @@ private static void ProcessParameters(Jpeg2000ImageData jp2) { StreamUtil.Skip(jpeg2000Stream, 8); for (int i = 4; i < box.length / 4; ++i) { if (Cio_read(4, jpeg2000Stream) == JPX_JPXB) { - jp2.parameters.isJpxBaseline = true; + jp2.parameters.SetJpxBaseline(true); } } Jp2_read_boxhdr(box, jpeg2000Stream); @@ -125,21 +125,23 @@ private static void ProcessParameters(Jpeg2000ImageData jp2) { } jp2.SetHeight(Cio_read(4, jpeg2000Stream)); jp2.SetWidth(Cio_read(4, jpeg2000Stream)); - jp2.parameters.numOfComps = Cio_read(2, jpeg2000Stream); + jp2.parameters.SetNumOfComps(Cio_read(2, jpeg2000Stream)); jp2.SetBpc(Cio_read(1, jpeg2000Stream)); StreamUtil.Skip(jpeg2000Stream, 3); Jp2_read_boxhdr(box, jpeg2000Stream); if (box.type == JP2_BPCC) { - jp2.parameters.bpcBoxData = new byte[box.length - 8]; - jpeg2000Stream.JRead(jp2.parameters.bpcBoxData, 0, box.length - 8); + jp2.parameters.SetBpcBoxData(new byte[box.length - 8]); + jpeg2000Stream.JRead(jp2.parameters.GetBpcBoxData(), 0, box.length - 8); } else { if (box.type == JP2_COLR) { do { - if (jp2.parameters.colorSpecBoxes == null) { - jp2.parameters.colorSpecBoxes = new List(); + if (jp2.parameters.GetColorSpecBoxes() == null) { + jp2.parameters.SetColorSpecBoxes(new List()); } - jp2.parameters.colorSpecBoxes.Add(Jp2_read_colr(box, jpeg2000Stream)); + IList colorSpecBoxes = jp2.parameters.GetColorSpecBoxes(); + colorSpecBoxes.Add(Jp2_read_colr(box, jpeg2000Stream)); + jp2.parameters.SetColorSpecBoxes(colorSpecBoxes); try { Jp2_read_boxhdr(box, jpeg2000Stream); } diff --git a/itext/itext.io/itext/io/logs/IoLogMessageConstant.cs b/itext/itext.io/itext/io/logs/IoLogMessageConstant.cs index 8674f1d709..4cded781ba 100644 --- a/itext/itext.io/itext/io/logs/IoLogMessageConstant.cs +++ b/itext/itext.io/itext/io/logs/IoLogMessageConstant.cs @@ -367,12 +367,10 @@ public const String IMAGE_HAS_INCORRECT_OR_UNSUPPORTED_BASE_COLOR_SPACE_IN_INDEX public const String XFDF_UNSUPPORTED_ANNOTATION_ATTRIBUTE = "Xfdf unsupported attribute type"; - [Obsolete] - public const String XOBJECT_HAS_NO_STRUCT_PARENTS = - // replaced by com.itextpdf.kernel.logs.KernelLogMessageConstant#XOBJECT_STRUCT_PARENT_INDEX_MISSED_AND_RECREATED - "XObject has no StructParents entry in its stream, no " + "entry in ParentTree will be created for the corresponding structure elements"; + public const String XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT = "Error occurred while " + "reading cross reference table. Cross reference table will be rebuilt. No additional information available"; - public const String XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT = "Error occurred while reading cross reference table. Cross reference table will be rebuilt."; + public const String XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE = "Error occurred while " + + "reading cross reference table. Cross reference table will be rebuilt. Reason: {0}"; private IoLogMessageConstant() { } diff --git a/itext/itext.io/itext/io/source/OutputStream.cs b/itext/itext.io/itext/io/source/HighPrecisionOutputStream.cs similarity index 96% rename from itext/itext.io/itext/io/source/OutputStream.cs rename to itext/itext.io/itext/io/source/HighPrecisionOutputStream.cs index 39d465429c..2db1cd39cf 100644 --- a/itext/itext.io/itext/io/source/OutputStream.cs +++ b/itext/itext.io/itext/io/source/HighPrecisionOutputStream.cs @@ -24,14 +24,14 @@ You should have received a copy of the GNU Affero General Public License using System.IO; namespace iText.IO.Source { - public class OutputStream : Stream + public class HighPrecisionOutputStream : Stream where T : Stream { private readonly ByteBuffer numBuffer = new ByteBuffer(32); private bool? localHighPrecision; - private Stream outputStream = null; + protected Stream outputStream = null; private long currentPos = 0; @@ -58,17 +58,17 @@ public void SetLocalHighPrecision(bool value) this.localHighPrecision = value; } - public OutputStream() + public HighPrecisionOutputStream() : base() { } - public OutputStream(Stream outputStream) + public HighPrecisionOutputStream(Stream outputStream) : base() { this.outputStream = outputStream; } - public OutputStream(Stream outputStream, bool localHighPrecision) + public HighPrecisionOutputStream(Stream outputStream, bool localHighPrecision) : base() { this.outputStream = outputStream; diff --git a/itext/itext.io/itext/io/source/PdfTokenizer.cs b/itext/itext.io/itext/io/source/PdfTokenizer.cs index cdb3eccd8c..751b79d67b 100644 --- a/itext/itext.io/itext/io/source/PdfTokenizer.cs +++ b/itext/itext.io/itext/io/source/PdfTokenizer.cs @@ -45,25 +45,6 @@ public enum TokenType { EndOfFile } - public static readonly bool[] delims = new bool[] { true, true, false, false, false, false, false, false, - false, false, true, true, false, true, true, false, false, false, false, false, false, false, false, false - , false, false, false, false, false, false, false, false, false, true, false, false, false, false, true - , false, false, true, true, false, false, false, false, false, true, false, false, false, false, false - , false, false, false, false, false, false, false, true, false, true, false, false, false, false, false - , false, false, false, false, false, false, false, false, false, false, false, false, false, false, false - , false, false, false, false, false, false, false, false, true, false, true, false, false, false, false - , false, false, false, false, false, false, false, false, false, false, false, false, false, false, false - , false, false, false, false, false, false, false, false, false, false, false, false, false, false, false - , false, false, false, false, false, false, false, false, false, false, false, false, false, false, false - , false, false, false, false, false, false, false, false, false, false, false, false, false, false, false - , false, false, false, false, false, false, false, false, false, false, false, false, false, false, false - , false, false, false, false, false, false, false, false, false, false, false, false, false, false, false - , false, false, false, false, false, false, false, false, false, false, false, false, false, false, false - , false, false, false, false, false, false, false, false, false, false, false, false, false, false, false - , false, false, false, false, false, false, false, false, false, false, false, false, false, false, false - , false, false, false, false, false, false, false, false, false, false, false, false, false, false, false - , false, false, false, false, false, false, false, false }; - public static readonly byte[] Obj = ByteUtils.GetIsoBytes("obj"); public static readonly byte[] R = ByteUtils.GetIsoBytes("R"); @@ -101,6 +82,25 @@ public enum TokenType { /// Streams are closed automatically. private bool closeStream = true; + private static readonly bool[] delims = new bool[] { true, true, false, false, false, false, false, false, + false, false, true, true, false, true, true, false, false, false, false, false, false, false, false, false + , false, false, false, false, false, false, false, false, false, true, false, false, false, false, true + , false, false, true, true, false, false, false, false, false, true, false, false, false, false, false + , false, false, false, false, false, false, false, true, false, true, false, false, false, false, false + , false, false, false, false, false, false, false, false, false, false, false, false, false, false, false + , false, false, false, false, false, false, false, false, true, false, true, false, false, false, false + , false, false, false, false, false, false, false, false, false, false, false, false, false, false, false + , false, false, false, false, false, false, false, false, false, false, false, false, false, false, false + , false, false, false, false, false, false, false, false, false, false, false, false, false, false, false + , false, false, false, false, false, false, false, false, false, false, false, false, false, false, false + , false, false, false, false, false, false, false, false, false, false, false, false, false, false, false + , false, false, false, false, false, false, false, false, false, false, false, false, false, false, false + , false, false, false, false, false, false, false, false, false, false, false, false, false, false, false + , false, false, false, false, false, false, false, false, false, false, false, false, false, false, false + , false, false, false, false, false, false, false, false, false, false, false, false, false, false, false + , false, false, false, false, false, false, false, false, false, false, false, false, false, false, false + , false, false, false, false, false, false, false, false }; + /// /// Creates a PdfTokenizer for the specified /// . @@ -143,6 +143,27 @@ public virtual int Read() { return file.Read(); } + /// Gets the next byte of pdf source without moving source position. + /// the byte, or -1 if EOF is reached + public virtual int Peek() { + return file.Peek(); + } + + /// + /// Gets the next + /// buffer.length + /// bytes of pdf source without moving source position. + /// + /// buffer to store read bytes + /// + /// the number of read bytes. If it is less than + /// buffer.length + /// it means EOF has been reached. + /// + public virtual int Peek(byte[] buffer) { + return file.Peek(buffer); + } + public virtual String ReadString(int size) { StringBuilder buf = new StringBuilder(); int ch; @@ -261,10 +282,23 @@ public virtual long GetNextEof() { do { long currentPosition = file.GetPosition(); str = ReadString(arrLength); - long eofPosition = str.IndexOf("%%EOF", StringComparison.Ordinal); + int eofPosition = str.IndexOf("%%EOF", StringComparison.Ordinal); if (eofPosition >= 0) { - // 6 stands for '%%EOF' length + 1 - return currentPosition + eofPosition + 6; + // Now we want to also include following EOL bytes. + file.Seek(currentPosition + eofPosition + 5); + // We only allow 4 next bytes to be EOL markers. + String remainingBytes = ReadString(4); + int eolCount = 0; + foreach (byte b in remainingBytes.GetBytes(System.Text.Encoding.UTF8)) { + if (b == '\n' || b == '\r') { + eolCount++; + } + else { + return currentPosition + eofPosition + eolCount + 5; + } + } + // 5 stands for '%%EOF' length + return currentPosition + eofPosition + eolCount + 5; } // Change current position to ensure '%%EOF' is not cut in half. file.Seek(file.GetPosition() - 4); diff --git a/itext/itext.io/itext/io/source/RandomAccessFileOrArray.cs b/itext/itext.io/itext/io/source/RandomAccessFileOrArray.cs index b9ba19f47c..ae444331cf 100644 --- a/itext/itext.io/itext/io/source/RandomAccessFileOrArray.cs +++ b/itext/itext.io/itext/io/source/RandomAccessFileOrArray.cs @@ -28,13 +28,6 @@ You should have received a copy of the GNU Affero General Public License namespace iText.IO.Source { /// Class that is used to unify reading from random access files and arrays. public class RandomAccessFileOrArray { - /// When true the file access is not done through a memory mapped file. - /// - /// When true the file access is not done through a memory mapped file. Use it if the file - /// is too big to be mapped in your address space. - /// - public static bool plainRandomAccess = false; - /// The source that backs this object private IRandomAccessSource byteSource; @@ -98,6 +91,44 @@ public virtual int Read() { return byteSource.Get(byteSourcePosition++); } + /// Gets the next byte without moving current position. + /// the next byte, or -1 if EOF is reached + public virtual int Peek() { + if (isBack) { + return back & 0xff; + } + return byteSource.Get(byteSourcePosition); + } + + /// + /// Gets the next + /// buffer.length + /// bytes without moving current position. + /// + /// buffer to store read bytes + /// + /// the number of read bytes. If it is less than + /// buffer.length + /// it means EOF has been reached. + /// + public virtual int Peek(byte[] buffer) { + int offset = 0; + int length = buffer.Length; + int count = 0; + if (isBack && length > 0) { + buffer[offset++] = back; + --length; + ++count; + } + if (length > 0) { + int byteSourceCount = byteSource.Get(byteSourcePosition, buffer, offset, length); + if (byteSourceCount > 0) { + count += byteSourceCount; + } + } + return count; + } + /// Reads the specified amount of bytes to the buffer applying the offset. /// destination buffer /// offset at which to start storing characters diff --git a/itext/itext.io/itext/io/util/GhostscriptHelper.cs b/itext/itext.io/itext/io/util/GhostscriptHelper.cs index a749c4cac4..e168afa2f4 100644 --- a/itext/itext.io/itext/io/util/GhostscriptHelper.cs +++ b/itext/itext.io/itext/io/util/GhostscriptHelper.cs @@ -43,11 +43,6 @@ public class GhostscriptHelper { /// The name of the environment variable with the command to execute Ghostscript operations. public const String GHOSTSCRIPT_ENVIRONMENT_VARIABLE = "ITEXT_GS_EXEC"; -//\cond DO_NOT_DOCUMENT - [Obsolete] - internal const String GHOSTSCRIPT_ENVIRONMENT_VARIABLE_LEGACY = "gsExec"; -//\endcond - //\cond DO_NOT_DOCUMENT internal const String GHOSTSCRIPT_KEYWORD = "GPL Ghostscript"; //\endcond @@ -82,9 +77,6 @@ public GhostscriptHelper(String newGsExec) { gsExec = newGsExec; if (gsExec == null) { gsExec = SystemUtil.GetEnvironmentVariable(GHOSTSCRIPT_ENVIRONMENT_VARIABLE); - if (gsExec == null) { - gsExec = SystemUtil.GetEnvironmentVariable(GHOSTSCRIPT_ENVIRONMENT_VARIABLE_LEGACY); - } } if (!CliCommandUtil.IsVersionCommandExecutable(gsExec, GHOSTSCRIPT_KEYWORD)) { throw new ArgumentException(IoExceptionMessageConstant.GS_ENVIRONMENT_VARIABLE_IS_NOT_SPECIFIED); diff --git a/itext/itext.io/itext/io/util/ImageMagickHelper.cs b/itext/itext.io/itext/io/util/ImageMagickHelper.cs index 08d2f5967d..92fd23080e 100644 --- a/itext/itext.io/itext/io/util/ImageMagickHelper.cs +++ b/itext/itext.io/itext/io/util/ImageMagickHelper.cs @@ -41,11 +41,6 @@ public class ImageMagickHelper { /// public const String MAGICK_COMPARE_ENVIRONMENT_VARIABLE = "ITEXT_MAGICK_COMPARE_EXEC"; -//\cond DO_NOT_DOCUMENT - [Obsolete] - internal const String MAGICK_COMPARE_ENVIRONMENT_VARIABLE_LEGACY = "compareExec"; -//\endcond - //\cond DO_NOT_DOCUMENT internal const String MAGICK_COMPARE_KEYWORD = "ImageMagick Studio LLC"; //\endcond @@ -75,9 +70,6 @@ public ImageMagickHelper(String newCompareExec) { compareExec = newCompareExec; if (compareExec == null) { compareExec = SystemUtil.GetEnvironmentVariable(MAGICK_COMPARE_ENVIRONMENT_VARIABLE); - if (compareExec == null) { - compareExec = SystemUtil.GetEnvironmentVariable(MAGICK_COMPARE_ENVIRONMENT_VARIABLE_LEGACY); - } } if (!CliCommandUtil.IsVersionCommandExecutable(compareExec, MAGICK_COMPARE_KEYWORD)) { throw new ArgumentException(IoExceptionMessageConstant.COMPARE_COMMAND_SPECIFIED_INCORRECTLY); diff --git a/itext/itext.io/itext/io/util/XmlUtil.cs b/itext/itext.io/itext/io/util/XmlUtil.cs index 2d08a4f4d2..51fcc3ffe2 100644 --- a/itext/itext.io/itext/io/util/XmlUtil.cs +++ b/itext/itext.io/itext/io/util/XmlUtil.cs @@ -25,7 +25,7 @@ You should have received a copy of the GNU Affero General Public License namespace iText.IO.Util { /// /// This file is a helper class for internal usage only. - /// Be aware that its API and functionality may be changed in future. + /// Be aware that its API and functionality may be changed in the future. /// public class XmlUtil { /// diff --git a/itext/itext.kernel/Properties/AssemblyInfo.cs b/itext/itext.kernel/Properties/AssemblyInfo.cs index 353e762c3f..b8c3480942 100644 --- a/itext/itext.kernel/Properties/AssemblyInfo.cs +++ b/itext/itext.kernel/Properties/AssemblyInfo.cs @@ -21,6 +21,6 @@ [assembly: Guid("be4c62cc-6495-47e1-ab00-05b1bfe331f6")] -[assembly: AssemblyVersion("8.0.5.0")] -[assembly: AssemblyFileVersion("8.0.5.0")] -[assembly: AssemblyInformationalVersion("8.0.5")] +[assembly: AssemblyVersion("9.0.0.0")] +[assembly: AssemblyFileVersion("9.0.0.0")] +[assembly: AssemblyInformationalVersion("9.0.0")] diff --git a/itext/itext.kernel/itext/kernel/actions/data/ITextCoreProductData.cs b/itext/itext.kernel/itext/kernel/actions/data/ITextCoreProductData.cs index b8805c93e3..2ddfc2f5d8 100644 --- a/itext/itext.kernel/itext/kernel/actions/data/ITextCoreProductData.cs +++ b/itext/itext.kernel/itext/kernel/actions/data/ITextCoreProductData.cs @@ -33,7 +33,7 @@ namespace iText.Kernel.Actions.Data { public sealed class ITextCoreProductData { private const String CORE_PUBLIC_PRODUCT_NAME = "Core"; - private const String CORE_VERSION = "8.0.5"; + private const String CORE_VERSION = "9.0.0"; private const int CORE_COPYRIGHT_SINCE = 2000; diff --git a/itext/itext.kernel/itext/kernel/actions/events/AddFingerPrintEvent.cs b/itext/itext.kernel/itext/kernel/actions/events/AddFingerPrintEvent.cs new file mode 100644 index 0000000000..224c7f6636 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/actions/events/AddFingerPrintEvent.cs @@ -0,0 +1,90 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using System.Collections.Generic; +using Microsoft.Extensions.Logging; +using iText.Commons; +using iText.Commons.Actions; +using iText.Commons.Actions.Data; +using iText.Commons.Actions.Processors; +using iText.Commons.Utils; +using iText.Kernel.Actions.Data; +using iText.Kernel.Logs; +using iText.Kernel.Pdf; + +namespace iText.Kernel.Actions.Events { + /// This class is responsible for adding a fingerprint. + public sealed class AddFingerPrintEvent : AbstractITextConfigurationEvent { + private readonly WeakReference document; + + private static readonly ILogger LOGGER = ITextLogManager.GetLogger(typeof(iText.Kernel.Actions.Events.AddFingerPrintEvent + )); + + private const String AGPL_MODE = "AGPL"; + + /// Creates a new instance of the AddFingerPrintEvent. + /// document in which the fingerprint will be added + public AddFingerPrintEvent(PdfDocument document) + : base() { + this.document = new WeakReference(document); + } + + /// Adds fingerprint to the document. + protected internal override void DoAction() { + PdfDocument pdfDocument = (PdfDocument)document.Target; + if (pdfDocument == null) { + return; + } + FingerPrint fingerPrint = pdfDocument.GetFingerPrint(); + ICollection products = fingerPrint.GetProducts(); + //if fingerprint is disabled and all licence types isn't AGPL then no actions required + if (!fingerPrint.IsFingerPrintEnabled()) { + bool nonAGPLMode = true; + foreach (ProductData productData in products) { + ITextProductEventProcessor processor = GetActiveProcessor(productData.GetProductName()); + if (processor == null) { + continue; + } + if (AGPL_MODE.Equals(processor.GetUsageType())) { + nonAGPLMode = false; + break; + } + } + if (nonAGPLMode) { + return; + } + LOGGER.LogWarning(KernelLogMessageConstant.FINGERPRINT_DISABLED_BUT_NO_REQUIRED_LICENCE); + } + PdfWriter writer = pdfDocument.GetWriter(); + if (products.IsEmpty()) { + writer.WriteString(MessageFormatUtil.Format("%iText-{0}-no-registered-products\n", ITextCoreProductData.GetInstance + ().GetVersion())); + return; + } + foreach (ProductData productData in products) { + writer.WriteString(MessageFormatUtil.Format("%iText-{0}-{1}\n", productData.GetPublicProductName(), productData + .GetVersion())); + } + } + } +} diff --git a/itext/itext.kernel/itext/kernel/colors/gradients/AbstractLinearGradientBuilder.cs b/itext/itext.kernel/itext/kernel/colors/gradients/AbstractLinearGradientBuilder.cs index 1e4ae1f61c..895da3e6ab 100644 --- a/itext/itext.kernel/itext/kernel/colors/gradients/AbstractLinearGradientBuilder.cs +++ b/itext/itext.kernel/itext/kernel/colors/gradients/AbstractLinearGradientBuilder.cs @@ -29,6 +29,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Kernel.Geom; using iText.Kernel.Pdf; using iText.Kernel.Pdf.Colorspace; +using iText.Kernel.Pdf.Colorspace.Shading; using iText.Kernel.Pdf.Function; namespace iText.Kernel.Colors.Gradients { @@ -158,7 +159,7 @@ public virtual Color BuildColor(Rectangle targetBoundingBox, AffineTransform con ); } } - PdfShading.Axial axial = CreateAxialShading(baseCoordinatesVector, this.stops, this.spreadMethod, targetBoundingBox + PdfAxialShading axial = CreateAxialShading(baseCoordinatesVector, this.stops, this.spreadMethod, targetBoundingBox ); if (axial == null) { return null; @@ -267,13 +268,13 @@ protected internal static Point[] CreateCoordinatesForNewDomain(double[] newDoma double xDiff = baseVector[1].GetX() - baseVector[0].GetX(); double yDiff = baseVector[1].GetY() - baseVector[0].GetY(); Point[] targetCoords = new Point[] { baseVector[0].GetLocation(), baseVector[1].GetLocation() }; - targetCoords[0].Translate(xDiff * newDomain[0], yDiff * newDomain[0]); - targetCoords[1].Translate(xDiff * (newDomain[1] - 1), yDiff * (newDomain[1] - 1)); + targetCoords[0].Move(xDiff * newDomain[0], yDiff * newDomain[0]); + targetCoords[1].Move(xDiff * (newDomain[1] - 1), yDiff * (newDomain[1] - 1)); return targetCoords; } - private static PdfShading.Axial CreateAxialShading(Point[] baseCoordinatesVector, IList - stops, GradientSpreadMethod spreadMethod, Rectangle targetBoundingBox) { + private static PdfAxialShading CreateAxialShading(Point[] baseCoordinatesVector, IList + stops, GradientSpreadMethod spreadMethod, Rectangle targetBoundingBox) { double baseVectorLength = baseCoordinatesVector[1].Distance(baseCoordinatesVector[0]); IList stopsToConstruct = NormalizeStops(stops, baseVectorLength); double[] coordinatesDomain = new double[] { 0, 1 }; @@ -313,7 +314,7 @@ private static PdfShading.Axial CreateAxialShading(Point[] baseCoordinatesVector System.Diagnostics.Debug.Assert(coordinatesDomain[0] <= coordinatesDomain[1]); actualCoordinates = CreateCoordinatesForNewDomain(coordinatesDomain, baseCoordinatesVector); } - return new PdfShading.Axial(new PdfDeviceCs.Rgb(), CreateCoordsPdfArray(actualCoordinates), new PdfArray(coordinatesDomain + return new PdfAxialShading(new PdfDeviceCs.Rgb(), CreateCoordsPdfArray(actualCoordinates), new PdfArray(coordinatesDomain ), ConstructFunction(stopsToConstruct)); } diff --git a/itext/itext.kernel/itext/kernel/crypto/AESGCMCipher.cs b/itext/itext.kernel/itext/kernel/crypto/AESGCMCipher.cs new file mode 100644 index 0000000000..48ba9147d4 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/crypto/AESGCMCipher.cs @@ -0,0 +1,118 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using iText.Bouncycastleconnector; +using iText.Commons.Bouncycastle; +using iText.Commons.Bouncycastle.Crypto.Modes; +using iText.Commons.Bouncycastle.Security; +using iText.Kernel.Exceptions; + +namespace iText.Kernel.Crypto { + /// Creates an Advanced Encryption Standard-Galois/Counter Mode (AES-GCM) Cipher. + public class AESGCMCipher { + public const int MAC_SIZE_BITS = 128; + + private static readonly IBouncyCastleFactory BOUNCY_CASTLE_FACTORY = BouncyCastleFactoryCreator.GetFactory + (); + + private readonly IGCMBlockCipher cipher; + + /// + /// Creates a new instance of + /// . + /// + /// + /// if true the cipher is initialised for + /// encryption, if false for decryption + /// + /// the key to be used in the cipher + /// initialization vector to be used in cipher + public AESGCMCipher(bool forEncryption, byte[] key, byte[] iv) { + try { + cipher = BOUNCY_CASTLE_FACTORY.CreateGCMBlockCipher(); + cipher.Init(forEncryption, key, MAC_SIZE_BITS, iv); + } + catch (AbstractGeneralSecurityException e) { + throw new PdfException(KernelExceptionMessageConstant.ERROR_WHILE_INITIALIZING_AES_CIPHER, e); + } + } + + /// + /// Continues a multiple-part encryption or decryption operation + /// (depending on how this cipher was initialized), processing another data + /// part. + /// + /// + /// Continues a multiple-part encryption or decryption operation + /// (depending on how this cipher was initialized), processing another data + /// part. + /// + /// The first + /// + /// bytes in the + /// + /// input buffer, starting at + /// + /// offset inclusive, + /// are processed, and the result is stored in a new buffer. + /// + /// the input buffer + /// + /// the offset in + /// + /// where the input starts + /// + /// the input length + /// the new buffer with the result + public virtual byte[] Update(byte[] b, int off, int len) { + byte[] cipherBuffer = new byte[cipher.GetUpdateOutputSize(len)]; + try { + cipher.ProcessBytes(b, off, len, cipherBuffer, 0); + } + catch (AbstractGeneralSecurityException e) { + throw new PdfException(KernelExceptionMessageConstant.PDF_ENCRYPTION, e); + } + return cipherBuffer; + } + + /// + /// Finishes a multiple-part encryption or decryption operation, depending on how this cipher was initialized + /// and resets underlying cipher object to the state it was in when previously + /// initialized via a call to init. + /// + /// final bytes array + public virtual byte[] DoFinal() { + byte[] cipherBuffer = new byte[cipher.GetOutputSize(0)]; + try { + cipher.DoFinal(cipherBuffer, 0); + return cipherBuffer; + } + catch (AbstractGeneralSecurityException e) { + throw new PdfException(KernelExceptionMessageConstant.PDF_ENCRYPTION, e); + } + catch (ArgumentException e) { + throw new PdfException(KernelExceptionMessageConstant.PDF_ENCRYPTION, e); + } + } + } +} diff --git a/itext/itext.kernel/itext/kernel/crypto/AesGcmDecryptor.cs b/itext/itext.kernel/itext/kernel/crypto/AesGcmDecryptor.cs new file mode 100644 index 0000000000..b0997f1b4f --- /dev/null +++ b/itext/itext.kernel/itext/kernel/crypto/AesGcmDecryptor.cs @@ -0,0 +1,87 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; + +namespace iText.Kernel.Crypto { + /// Class for decrypting aes-gcm encrypted bytes. + public class AesGcmDecryptor : IDecryptor { + private AESGCMCipher cipher; + + private readonly byte[] key; + + private bool initiated; + + private readonly byte[] iv = new byte[12]; + + private int ivptr; + + /// + /// Creates a new instance of + /// . + /// + /// the byte array containing the key for decryption + /// offset of the key in the byte array + /// the length of the key in the byte array + public AesGcmDecryptor(byte[] key, int off, int len) { + this.key = new byte[len]; + Array.Copy(key, off, this.key, 0, len); + } + + /// + /// Continues a multiple-part decryption operation, processing another data part and initializing aes-gcm cipher if + /// this method called for the first time. + /// + /// the input buffer + /// the offset in input where the input starts + /// the input length + /// decrypted bytes array + public virtual byte[] Update(byte[] b, int off, int len) { + if (!initiated) { + int left = Math.Min(iv.Length - ivptr, len); + Array.Copy(b, off, iv, ivptr, left); + off += left; + len -= left; + ivptr += left; + if (ivptr == iv.Length) { + cipher = new AESGCMCipher(false, key, iv); + initiated = true; + } + if (len == 0) { + return null; + } + } + return cipher.Update(b, off, len); + } + + /// Finishes a multiple-part decryption operation. + /// input data that may have been buffered during a previous update operation + public virtual byte[] Finish() { + if (cipher != null) { + return cipher.DoFinal(); + } + else { + return null; + } + } + } +} diff --git a/itext/itext.kernel/itext/kernel/crypto/CryptoUtil.cs b/itext/itext.kernel/itext/kernel/crypto/CryptoUtil.cs index 0c72988eea..47edaf308d 100644 --- a/itext/itext.kernel/itext/kernel/crypto/CryptoUtil.cs +++ b/itext/itext.kernel/itext/kernel/crypto/CryptoUtil.cs @@ -27,6 +27,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Asn1; using iText.Commons.Bouncycastle.Cert; using iText.Commons.Bouncycastle.Crypto; +using iText.Commons.Digest; using iText.Commons.Utils; using iText.Kernel.Exceptions; @@ -60,7 +61,9 @@ public static IDerOutputStream CreateAsn1OutputStream(Stream outputStream, Strin MessageFormatUtil.Format(KernelExceptionMessageConstant.UNSUPPORTED_ASN1_ENCODING, asn1Encoding) ); } - - + + internal static IMessageDigest GetMessageDigest(String hashAlgorithm) { + return FACTORY.CreateIDigest(hashAlgorithm); + } } } diff --git a/itext/itext.sign/itext/signatures/DigestAlgorithms.cs b/itext/itext.kernel/itext/kernel/crypto/DigestAlgorithms.cs similarity index 75% rename from itext/itext.sign/itext/signatures/DigestAlgorithms.cs rename to itext/itext.kernel/itext/kernel/crypto/DigestAlgorithms.cs index 7316c1f7ee..1b61046f46 100644 --- a/itext/itext.sign/itext/signatures/DigestAlgorithms.cs +++ b/itext/itext.kernel/itext/kernel/crypto/DigestAlgorithms.cs @@ -27,12 +27,11 @@ You should have received a copy of the GNU Affero General Public License using iText.Bouncycastleconnector; using iText.Commons; using iText.Commons.Bouncycastle; -using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Digest; -using iText.Signatures.Exceptions; -using iText.Signatures.Logs; +using iText.Kernel.Exceptions; +using iText.Kernel.Logs; -namespace iText.Signatures { +namespace iText.Kernel.Crypto { /// Class that contains a map with the different message digest algorithms. public class DigestAlgorithms { /// Algorithm available for signatures since PDF 1.3. @@ -101,10 +100,10 @@ static DigestAlgorithms() { digestNames.Put("1.2.840.113549.2.5", "MD5"); digestNames.Put("1.2.840.113549.2.2", "MD2"); digestNames.Put("1.3.14.3.2.26", "SHA1"); - digestNames.Put("2.16.840.1.101.3.4.2.4", "SHA224"); - digestNames.Put("2.16.840.1.101.3.4.2.1", "SHA256"); - digestNames.Put("2.16.840.1.101.3.4.2.2", "SHA384"); - digestNames.Put("2.16.840.1.101.3.4.2.3", "SHA512"); + digestNames.Put(OID.SHA_224, "SHA224"); + digestNames.Put(OID.SHA_256, "SHA256"); + digestNames.Put(OID.SHA_384, "SHA384"); + digestNames.Put(OID.SHA_512, "SHA512"); digestNames.Put("1.3.36.3.2.2", "RIPEMD128"); digestNames.Put("1.3.36.3.2.1", "RIPEMD160"); digestNames.Put("1.3.36.3.2.3", "RIPEMD256"); @@ -115,8 +114,6 @@ static DigestAlgorithms() { digestNames.Put("1.2.840.113549.1.1.11", "SHA256"); digestNames.Put("1.2.840.113549.1.1.12", "SHA384"); digestNames.Put("1.2.840.113549.1.1.13", "SHA512"); - digestNames.Put("1.2.840.113549.2.5", "MD5"); - digestNames.Put("1.2.840.113549.2.2", "MD2"); digestNames.Put("1.2.840.10040.4.3", "SHA1"); digestNames.Put("2.16.840.1.101.3.4.3.1", "SHA224"); digestNames.Put("2.16.840.1.101.3.4.3.2", "SHA256"); @@ -126,11 +123,11 @@ static DigestAlgorithms() { digestNames.Put("1.3.36.3.3.1.2", "RIPEMD160"); digestNames.Put("1.3.36.3.3.1.4", "RIPEMD256"); digestNames.Put("1.2.643.2.2.9", "GOST3411"); - digestNames.Put("2.16.840.1.101.3.4.2.7", "SHA3-224"); - digestNames.Put("2.16.840.1.101.3.4.2.8", "SHA3-256"); - digestNames.Put("2.16.840.1.101.3.4.2.9", "SHA3-384"); - digestNames.Put("2.16.840.1.101.3.4.2.10", "SHA3-512"); - digestNames.Put("2.16.840.1.101.3.4.2.12", "SHAKE256"); + digestNames.Put(OID.SHA3_224, "SHA3-224"); + digestNames.Put(OID.SHA3_256, "SHA3-256"); + digestNames.Put(OID.SHA3_384, "SHA3-384"); + digestNames.Put(OID.SHA3_512, "SHA3-512"); + digestNames.Put(OID.SHAKE_256, "SHAKE256"); fixNames.Put("SHA256", SHA256); fixNames.Put("SHA384", SHA384); fixNames.Put("SHA512", SHA512); @@ -140,14 +137,14 @@ static DigestAlgorithms() { allowedDigests.Put("MD-5", "1.2.840.113549.2.5"); allowedDigests.Put("SHA1", "1.3.14.3.2.26"); allowedDigests.Put("SHA-1", "1.3.14.3.2.26"); - allowedDigests.Put("SHA224", "2.16.840.1.101.3.4.2.4"); - allowedDigests.Put("SHA-224", "2.16.840.1.101.3.4.2.4"); - allowedDigests.Put("SHA256", "2.16.840.1.101.3.4.2.1"); - allowedDigests.Put("SHA-256", "2.16.840.1.101.3.4.2.1"); - allowedDigests.Put("SHA384", "2.16.840.1.101.3.4.2.2"); - allowedDigests.Put("SHA-384", "2.16.840.1.101.3.4.2.2"); - allowedDigests.Put("SHA512", "2.16.840.1.101.3.4.2.3"); - allowedDigests.Put("SHA-512", "2.16.840.1.101.3.4.2.3"); + allowedDigests.Put("SHA224", OID.SHA_224); + allowedDigests.Put("SHA-224", OID.SHA_224); + allowedDigests.Put("SHA256", OID.SHA_256); + allowedDigests.Put("SHA-256", OID.SHA_256); + allowedDigests.Put("SHA384", OID.SHA_384); + allowedDigests.Put("SHA-384", OID.SHA_384); + allowedDigests.Put("SHA512", OID.SHA_512); + allowedDigests.Put("SHA-512", OID.SHA_512); allowedDigests.Put("RIPEMD128", "1.3.36.3.2.2"); allowedDigests.Put("RIPEMD-128", "1.3.36.3.2.2"); allowedDigests.Put("RIPEMD160", "1.3.36.3.2.1"); @@ -155,11 +152,11 @@ static DigestAlgorithms() { allowedDigests.Put("RIPEMD256", "1.3.36.3.2.3"); allowedDigests.Put("RIPEMD-256", "1.3.36.3.2.3"); allowedDigests.Put("GOST3411", "1.2.643.2.2.9"); - allowedDigests.Put("SHA3-224", "2.16.840.1.101.3.4.2.7"); - allowedDigests.Put("SHA3-256", "2.16.840.1.101.3.4.2.8"); - allowedDigests.Put("SHA3-384", "2.16.840.1.101.3.4.2.9"); - allowedDigests.Put("SHA3-512", "2.16.840.1.101.3.4.2.10"); - allowedDigests.Put("SHAKE256", "2.16.840.1.101.3.4.2.12"); + allowedDigests.Put("SHA3-224", OID.SHA3_224); + allowedDigests.Put("SHA3-256", OID.SHA3_256); + allowedDigests.Put("SHA3-384", OID.SHA3_384); + allowedDigests.Put("SHA3-512", OID.SHA3_512); + allowedDigests.Put("SHAKE256", OID.SHAKE_256); bitLengths.Put("MD2", 128); bitLengths.Put("MD-2", 128); bitLengths.Put("MD5", 128); @@ -190,15 +187,15 @@ static DigestAlgorithms() { /// Get a digest algorithm. /// oid of the digest algorithm /// MessageDigest object - public static IDigest GetMessageDigestFromOid(String digestOid) { + public static IMessageDigest GetMessageDigestFromOid(String digestOid) { return GetMessageDigest(GetDigest(digestOid)); } /// Creates a MessageDigest object that can be used to create a hash. /// the algorithm you want to use to create a hash /// a MessageDigest object - public static IDigest GetMessageDigest(String hashAlgorithm) { - return (IDigest)SignUtils.GetMessageDigest(hashAlgorithm); + public static IMessageDigest GetMessageDigest(String hashAlgorithm) { + return CryptoUtil.GetMessageDigest(hashAlgorithm); } /// Creates a hash using a specific digest algorithm and a provider. @@ -206,15 +203,15 @@ public static IDigest GetMessageDigest(String hashAlgorithm) { /// the algorithm used to create the hash /// the hash public static byte[] Digest(Stream data, String hashAlgorithm) { - IDigest messageDigest = GetMessageDigest(hashAlgorithm); + IMessageDigest messageDigest = GetMessageDigest(hashAlgorithm); return Digest(data, messageDigest); } - /// Create a digest based on the inputstream. + /// Create a digest based on the input stream. /// data to be digested /// algorithm to be used /// digest of the data - public static byte[] Digest(Stream data, IDigest messageDigest) { + public static byte[] Digest(Stream data, IMessageDigest messageDigest) { byte[] buf = new byte[8192]; int n; while ((n = data.Read(buf)) > 0) { @@ -223,21 +220,6 @@ public static byte[] Digest(Stream data, IDigest messageDigest) { return messageDigest.Digest(); } - /// Create a digest based on the inputstream. - /// data to be digested - /// algorithm to be used - /// external digest to be used - /// digest of the data - public static byte[] Digest(Stream data, String hashAlgorithm, IExternalDigest externalDigest) { - byte[] buf = new byte[8192]; - int n; - IMessageDigest messageDigest = SignUtils.GetMessageDigest(hashAlgorithm, externalDigest); - while ((n = data.Read(buf)) > 0) { - messageDigest.Update(buf, 0, n); - } - return messageDigest.Digest(); - } - /// Gets the digest name for a certain id. /// an id (for instance "1.2.840.113549.2.5") /// a digest name (for instance "MD5") @@ -246,7 +228,7 @@ public static String GetDigest(String oid) { if (ret == null) { try { String digest = GetMessageDigest(oid).GetAlgorithmName(); - LOGGER.LogWarning(SignLogMessageConstant.ALGORITHM_NOT_FROM_SPEC); + LOGGER.LogWarning(KernelLogMessageConstant.ALGORITHM_NOT_FROM_SPEC); return digest; } catch (Exception) { @@ -262,11 +244,11 @@ public static String GetDigest(String oid) { /// Returns the id of a digest algorithms that is allowed in PDF, /// or null if it isn't allowed. /// - /// The name of the digest algorithm. - /// An oid. + /// the name of the digest algorithm + /// an oid public static String GetAllowedDigest(String name) { if (name == null) { - throw new ArgumentException(SignExceptionMessageConstant.THE_NAME_OF_THE_DIGEST_ALGORITHM_IS_NULL); + throw new ArgumentException(KernelExceptionMessageConstant.THE_NAME_OF_THE_DIGEST_ALGORITHM_IS_NULL); } String allowedDigest = allowedDigests.Get(name.ToUpperInvariant()); if (allowedDigest != null) { @@ -274,7 +256,7 @@ public static String GetAllowedDigest(String name) { } allowedDigest = BOUNCY_CASTLE_FACTORY.GetDigestAlgorithmOid(name.ToUpperInvariant()); if (allowedDigest != null) { - LOGGER.LogWarning(SignLogMessageConstant.ALGORITHM_NOT_FROM_SPEC); + LOGGER.LogWarning(KernelLogMessageConstant.ALGORITHM_NOT_FROM_SPEC); } return allowedDigest; } @@ -284,7 +266,7 @@ public static String GetAllowedDigest(String name) { /// the length of the output of the algorithm in bits public static int GetOutputBitLength(String name) { if (name == null) { - throw new ArgumentException(SignExceptionMessageConstant.THE_NAME_OF_THE_DIGEST_ALGORITHM_IS_NULL); + throw new ArgumentException(KernelExceptionMessageConstant.THE_NAME_OF_THE_DIGEST_ALGORITHM_IS_NULL); } return bitLengths.Get(name).Value; } diff --git a/itext/itext.sign/itext/signatures/OID.cs b/itext/itext.kernel/itext/kernel/crypto/OID.cs similarity index 74% rename from itext/itext.sign/itext/signatures/OID.cs rename to itext/itext.kernel/itext/kernel/crypto/OID.cs index fac2f1341b..7d841748e3 100644 --- a/itext/itext.sign/itext/signatures/OID.cs +++ b/itext/itext.kernel/itext/kernel/crypto/OID.cs @@ -24,9 +24,79 @@ You should have received a copy of the GNU Affero General Public License using System.Collections.Generic; using iText.Commons.Utils; -namespace iText.Signatures { +namespace iText.Kernel.Crypto { /// Class containing all the OID values used by iText. public sealed class OID { + public const String PKCS7_DATA = "1.2.840.113549.1.7.1"; + + public const String PKCS7_SIGNED_DATA = "1.2.840.113549.1.7.2"; + + public const String RSA = "1.2.840.113549.1.1.1"; + + public const String RSASSA_PSS = "1.2.840.113549.1.1.10"; + + public const String RSA_WITH_SHA256 = "1.2.840.113549.1.1.11"; + + public const String AA_SIGNING_CERTIFICATE_V1 = "1.2.840.113549.1.9.16.2.12"; + + public const String AA_SIGNING_CERTIFICATE_V2 = "1.2.840.113549.1.9.16.2.47"; + + public const String MGF1 = "1.2.840.113549.1.1.8"; + + public const String AA_TIME_STAMP_TOKEN = "1.2.840.113549.1.9.16.2.14"; + + public const String AUTHENTICATED_DATA = "1.2.840.113549.1.9.16.1.2"; + + public const String CONTENT_TYPE = "1.2.840.113549.1.9.3"; + + public const String MESSAGE_DIGEST = "1.2.840.113549.1.9.4"; + + public const String SIGNING_TIME = "1.2.840.113549.1.9.5"; + + public const String CMS_ALGORITHM_PROTECTION = "1.2.840.113549.1.9.52"; + + public const String DSA = "1.2.840.10040.4.1"; + + public const String ECDSA = "1.2.840.10045.2.1"; + + public const String ADBE_REVOCATION = "1.2.840.113583.1.1.8"; + + public const String TSA = "1.2.840.113583.1.1.9.1"; + + public const String RSA_WITH_SHA3_512 = "2.16.840.1.101.3.4.3.16"; + + public const String SHA_224 = "2.16.840.1.101.3.4.2.4"; + + public const String SHA_256 = "2.16.840.1.101.3.4.2.1"; + + public const String SHA_384 = "2.16.840.1.101.3.4.2.2"; + + public const String SHA_512 = "2.16.840.1.101.3.4.2.3"; + + public const String SHA3_224 = "2.16.840.1.101.3.4.2.7"; + + public const String SHA3_256 = "2.16.840.1.101.3.4.2.8"; + + public const String SHA3_384 = "2.16.840.1.101.3.4.2.9"; + + public const String SHA3_512 = "2.16.840.1.101.3.4.2.10"; + + public const String SHAKE_256 = "2.16.840.1.101.3.4.2.12"; + + public const String ED25519 = "1.3.101.112"; + + public const String ED448 = "1.3.101.113"; + + public const String OCSP = "1.3.6.1.5.5.7.48.1"; + + public const String CA_ISSUERS = "1.3.6.1.5.5.7.48.2"; + + public const String RI_OCSP_RESPONSE = "1.3.6.1.5.5.7.16.2"; + + public const String KDF_PDF_MAC_WRAP_KDF = "1.0.32004.1.1"; + + public const String CT_PDF_MAC_INTEGRITY_INFO = "1.0.32004.1.0"; + private OID() { } @@ -130,6 +200,10 @@ public sealed class X509Extensions { /// Extension for certificates from ETSI EN 319 412-1 V1.4.4. public const String VALIDITY_ASSURED_SHORT_TERM = "0.4.0.194121.2.1"; + /// Extension for certificates from RFC 9608 which indicates that no revocation information is available. + /// + public const String NO_REV_AVAILABLE = "2.5.29.56"; + /// According to https://tools.ietf.org/html/rfc5280 4.2. /// /// According to https://tools.ietf.org/html/rfc5280 4.2. "Certificate Extensions": diff --git a/itext/itext.kernel/itext/kernel/crypto/OutputStreamAesGcmEncryption.cs b/itext/itext.kernel/itext/kernel/crypto/OutputStreamAesGcmEncryption.cs new file mode 100644 index 0000000000..d0519fb847 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/crypto/OutputStreamAesGcmEncryption.cs @@ -0,0 +1,147 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using System.IO; +using System.Security.Cryptography; +using iText.Kernel.Exceptions; + +namespace iText.Kernel.Crypto { + /// + /// An output stream accepts output bytes and sends them to underlying + /// + /// instance. + /// + public class OutputStreamAesGcmEncryption : OutputStreamEncryption { + private readonly AESGCMCipher cipher; + + private bool finished; + + private static readonly RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); + + /// + /// Creates a new instance of + /// . + /// + /// + /// the + /// + /// instance to be used as the destination for the encrypted content + /// + /// the byte array containing the key for encryption + /// a 7 byte nonce + public OutputStreamAesGcmEncryption(Stream @out, byte[] key, byte[] noncePart) + : base(@out) { + byte[] iv = new byte[12]; + byte[] randomPart = new byte[5]; + lock (rng) { + rng.GetBytes(randomPart); + } + Array.Copy(randomPart, 0, iv, 0, 5); + Array.Copy(noncePart, 0, iv, 5, 7); + cipher = new AESGCMCipher(true, key, iv); + try { + @out.Write(iv); + } + catch (System.IO.IOException e) { + throw new PdfException(KernelExceptionMessageConstant.PDF_ENCRYPTION, e); + } + } + + /// + /// Writes + /// + /// bytes from the specified byte array + /// starting at offset + /// + /// to this output stream. + /// + /// + /// Writes + /// + /// bytes from the specified byte array + /// starting at offset + /// + /// to this output stream. + /// The general contract for + /// write(b, off, len) + /// is that + /// some bytes in the array + /// + /// are written to the + /// output stream in order; element + /// b[off] + /// is the first + /// byte written and + /// b[off+len-1] + /// is the last byte written + /// by this operation. + /// + /// The + /// write + /// method of + /// OutputStream + /// calls + /// the write method of one argument on each of the bytes to be + /// written out. Subclasses are encouraged to override this method and + /// provide a more efficient implementation. + /// + /// If + /// + /// is negative, or + /// + /// is negative, or + /// off+len + /// is greater than the length of the array + /// + /// , then an IndexOutOfBoundsException is thrown. + /// + /// the data + /// the start offset in the data + /// the number of bytes to write + public override void Write(byte[] b, int off, int len) { + byte[] cipherBuffer = cipher.Update(b, off, len); + if (cipherBuffer.Length != 0) { + @out.Write(cipherBuffer, 0, cipherBuffer.Length); + } + } + + /// Finishes and dispose all resources used for writing in encrypted stream. + /// + /// Finishes and dispose all resources used for writing in encrypted stream. + /// Input data that may have been buffered during a previous update operation is processed, + /// with padding (if requested) being applied and authentication tag is appended. + /// + public override void Finish() { + if (!finished) { + finished = true; + byte[] cipherBuffer = cipher.DoFinal(); + try { + @out.Write(cipherBuffer, 0, cipherBuffer.Length); + } + catch (System.IO.IOException e) { + throw new PdfException(KernelExceptionMessageConstant.PDF_ENCRYPTION, e); + } + } + } + } +} diff --git a/itext/itext.kernel/itext/kernel/crypto/securityhandler/PubKeySecurityHandler.cs b/itext/itext.kernel/itext/kernel/crypto/securityhandler/PubKeySecurityHandler.cs index 9344d8eabf..9f8f16cbcf 100644 --- a/itext/itext.kernel/itext/kernel/crypto/securityhandler/PubKeySecurityHandler.cs +++ b/itext/itext.kernel/itext/kernel/crypto/securityhandler/PubKeySecurityHandler.cs @@ -177,14 +177,11 @@ private byte[] GetEncodedRecipient(int index) { //constants permissions: PdfWriter.AllowCopy | PdfWriter.AllowPrinting | PdfWriter.AllowScreenReaders | // PdfWriter.AllowAssembly; int permission = recipient.GetPermission(); - // NOTE! Added while porting to itext - // Previous strange code was: - // int revision = 3; - // permission |= revision == 3 ? 0xfffff0c0 : 0xffffffc0; - // revision value never changed, so code have been replaced to this: - permission |= unchecked((int)(0xfffff0c0)); - permission &= unchecked((int)(0xfffffffc)); - permission += 1; + // Force set 1 to 1, 7, 8 bits and all bits above 13. + // Basically to all not used bits. + // Bit 13 we do not touch. It's handled separately in PdfEncryption. + // Not sure about bit 1. But we always set it to 1 so let's not change for now. + permission |= unchecked((int)(0xffffe0c1)); byte[] pkcs7input = new byte[24]; byte one = (byte)permission; byte two = (byte)(permission >> 8); diff --git a/itext/itext.kernel/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAes128.cs b/itext/itext.kernel/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAes128.cs index 1557df8067..6bf6c5bee4 100644 --- a/itext/itext.kernel/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAes128.cs +++ b/itext/itext.kernel/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAes128.cs @@ -80,7 +80,6 @@ protected internal override void SetPubSecSpecificHandlerDicEntries(PdfDictionar encryptMetadata, bool embeddedFilesOnly) { encryptionDictionary.Put(PdfName.Filter, PdfName.Adobe_PubSec); encryptionDictionary.Put(PdfName.SubFilter, PdfName.Adbe_pkcs7_s5); - encryptionDictionary.Put(PdfName.R, new PdfNumber(4)); encryptionDictionary.Put(PdfName.V, new PdfNumber(4)); PdfArray recipients = CreateRecipientsArray(); PdfDictionary stdcf = new PdfDictionary(); diff --git a/itext/itext.kernel/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAes256.cs b/itext/itext.kernel/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAes256.cs index 5c356e8728..6f77bf566a 100644 --- a/itext/itext.kernel/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAes256.cs +++ b/itext/itext.kernel/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAes256.cs @@ -52,17 +52,24 @@ protected internal override void InitKey(byte[] globalKey, int keyLength) { protected internal override void SetPubSecSpecificHandlerDicEntries(PdfDictionary encryptionDictionary, bool encryptMetadata, bool embeddedFilesOnly) { + int version = 5; + PdfName filter = PdfName.AESV3; + SetEncryptionDictEntries(encryptionDictionary, encryptMetadata, embeddedFilesOnly, version, filter); + } + +//\cond DO_NOT_DOCUMENT + internal virtual void SetEncryptionDictEntries(PdfDictionary encryptionDictionary, bool encryptMetadata, bool + embeddedFilesOnly, int version, PdfName cryptFilter) { encryptionDictionary.Put(PdfName.Filter, PdfName.Adobe_PubSec); encryptionDictionary.Put(PdfName.SubFilter, PdfName.Adbe_pkcs7_s5); - encryptionDictionary.Put(PdfName.R, new PdfNumber(5)); - encryptionDictionary.Put(PdfName.V, new PdfNumber(5)); + encryptionDictionary.Put(PdfName.V, new PdfNumber(version)); PdfArray recipients = CreateRecipientsArray(); PdfDictionary stdcf = new PdfDictionary(); stdcf.Put(PdfName.Recipients, recipients); if (!encryptMetadata) { stdcf.Put(PdfName.EncryptMetadata, PdfBoolean.FALSE); } - stdcf.Put(PdfName.CFM, PdfName.AESV3); + stdcf.Put(PdfName.CFM, cryptFilter); stdcf.Put(PdfName.Length, new PdfNumber(256)); PdfDictionary cf = new PdfDictionary(); cf.Put(PdfName.DefaultCryptFilter, stdcf); @@ -77,5 +84,6 @@ protected internal override void SetPubSecSpecificHandlerDicEntries(PdfDictionar encryptionDictionary.Put(PdfName.StmF, PdfName.DefaultCryptFilter); } } +//\endcond } } diff --git a/itext/itext.kernel/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcm.cs b/itext/itext.kernel/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcm.cs new file mode 100644 index 0000000000..4c70abd255 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/crypto/securityhandler/PubSecHandlerUsingAesGcm.cs @@ -0,0 +1,111 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System.IO; +using iText.Commons.Bouncycastle.Cert; +using iText.Commons.Bouncycastle.Crypto; +using iText.Kernel.Crypto; +using iText.Kernel.Pdf; + +namespace iText.Kernel.Crypto.Securityhandler { + /// Public-key security handler with Advanced Encryption Standard-Galois/Counter Mode (AES-GCM) encryption algorithm. + /// + public class PubSecHandlerUsingAesGcm : PubSecHandlerUsingAes256 { + protected internal byte[] noncePart = null; + + protected internal int inObjectNonceCounter = 0; + + /// + /// Creates new + /// + /// instance for encryption. + /// + /// document's encryption dictionary + /// recipients' X.509 public key certificates + /// access permissions provided to each recipient + /// indicates whether the document-level metadata stream shall be encrypted + /// indicates whether embedded files shall be encrypted in an otherwise unencrypted document + /// + public PubSecHandlerUsingAesGcm(PdfDictionary encryptionDictionary, IX509Certificate[] certs, int[] permissions + , bool encryptMetadata, bool embeddedFilesOnly) + : base(encryptionDictionary, certs, permissions, encryptMetadata, embeddedFilesOnly) { + } + + /// + /// Creates new + /// + /// instance for decryption. + /// + /// document's encryption dictionary + /// + /// the recipient private + /// + /// to the certificate + /// + /// + /// the recipient + /// + /// , serves as recipient identifier + /// + /// + /// the certificate key provider id + /// for + /// + /// + /// the external decryption process to be used + /// indicates whether the document-level metadata stream shall be encrypted + public PubSecHandlerUsingAesGcm(PdfDictionary encryptionDictionary, IPrivateKey certificateKey, IX509Certificate + certificate, bool encryptMetadata) + : base(encryptionDictionary, certificateKey, certificate, encryptMetadata) { + } + + public override void SetHashKeyForNextObject(int objNumber, int objGeneration) { + // Make sure the same IV is never used twice in the same file. We do this by turning the objId/objGen into a + // 5-byte nonce (with generation restricted to 1 byte instead of 2) plus an in-object 2-byte counter that + // increments each time a new string is encrypted within the same object. The remaining 5 bytes will be + // generated randomly using a strong PRNG. + // This is very different from the situation with AES-CBC, where randomness is paramount. + // GCM uses a variation of counter mode, so making sure the IV is unique is more important than randomness. + this.inObjectNonceCounter = 0; + this.noncePart = new byte[] { 0, 0, (byte)(objGeneration), (byte)((int)(((uint)objNumber) >> 24)), (byte)( + (int)(((uint)objNumber) >> 16)), (byte)((int)(((uint)objNumber) >> 8)), (byte)(objNumber) }; + } + + public override OutputStreamEncryption GetEncryptionStream(Stream os) { + int ctr = inObjectNonceCounter; + noncePart[0] = (byte)((int)(((uint)ctr) >> 8)); + noncePart[1] = (byte)ctr; + return new OutputStreamAesGcmEncryption(os, nextObjectKey, noncePart); + } + + public override IDecryptor GetDecryptor() { + return new AesGcmDecryptor(nextObjectKey, 0, nextObjectKeySize); + } + + protected internal override void SetPubSecSpecificHandlerDicEntries(PdfDictionary encryptionDictionary, bool + encryptMetadata, bool embeddedFilesOnly) { + int version = 6; + PdfName filter = PdfName.AESV4; + SetEncryptionDictEntries(encryptionDictionary, encryptMetadata, embeddedFilesOnly, version, filter); + } + } +} diff --git a/itext/itext.kernel/itext/kernel/crypto/securityhandler/PubSecHandlerUsingStandard128.cs b/itext/itext.kernel/itext/kernel/crypto/securityhandler/PubSecHandlerUsingStandard128.cs index 4c1bac6fe4..ee6228522d 100644 --- a/itext/itext.kernel/itext/kernel/crypto/securityhandler/PubSecHandlerUsingStandard128.cs +++ b/itext/itext.kernel/itext/kernel/crypto/securityhandler/PubSecHandlerUsingStandard128.cs @@ -41,13 +41,11 @@ protected internal override void SetPubSecSpecificHandlerDicEntries(PdfDictionar encryptionDictionary.Put(PdfName.Filter, PdfName.Adobe_PubSec); PdfArray recipients = CreateRecipientsArray(); if (encryptMetadata) { - encryptionDictionary.Put(PdfName.R, new PdfNumber(3)); encryptionDictionary.Put(PdfName.V, new PdfNumber(2)); encryptionDictionary.Put(PdfName.SubFilter, PdfName.Adbe_pkcs7_s4); encryptionDictionary.Put(PdfName.Recipients, recipients); } else { - encryptionDictionary.Put(PdfName.R, new PdfNumber(4)); encryptionDictionary.Put(PdfName.V, new PdfNumber(4)); encryptionDictionary.Put(PdfName.SubFilter, PdfName.Adbe_pkcs7_s5); PdfDictionary stdcf = new PdfDictionary(); diff --git a/itext/itext.kernel/itext/kernel/crypto/securityhandler/PubSecHandlerUsingStandard40.cs b/itext/itext.kernel/itext/kernel/crypto/securityhandler/PubSecHandlerUsingStandard40.cs index a6aa3988ae..9cccd0a070 100644 --- a/itext/itext.kernel/itext/kernel/crypto/securityhandler/PubSecHandlerUsingStandard40.cs +++ b/itext/itext.kernel/itext/kernel/crypto/securityhandler/PubSecHandlerUsingStandard40.cs @@ -59,7 +59,6 @@ protected internal override void InitKey(byte[] globalKey, int keyLength) { protected internal override void SetPubSecSpecificHandlerDicEntries(PdfDictionary encryptionDictionary, bool encryptMetadata, bool embeddedFilesOnly) { encryptionDictionary.Put(PdfName.Filter, PdfName.Adobe_PubSec); - encryptionDictionary.Put(PdfName.R, new PdfNumber(2)); PdfArray recipients = CreateRecipientsArray(); encryptionDictionary.Put(PdfName.V, new PdfNumber(1)); encryptionDictionary.Put(PdfName.SubFilter, PdfName.Adbe_pkcs7_s4); diff --git a/itext/itext.kernel/itext/kernel/crypto/securityhandler/SecurityHandler.cs b/itext/itext.kernel/itext/kernel/crypto/securityhandler/SecurityHandler.cs index 2eb4a8cc7b..a8c7b91695 100644 --- a/itext/itext.kernel/itext/kernel/crypto/securityhandler/SecurityHandler.cs +++ b/itext/itext.kernel/itext/kernel/crypto/securityhandler/SecurityHandler.cs @@ -26,7 +26,9 @@ You should have received a copy of the GNU Affero General Public License using iText.Bouncycastleconnector; using iText.Commons; using iText.Commons.Bouncycastle; -using iText.Commons.Bouncycastle.Crypto; +using iText.Commons.Digest; +using iText.Commons.Utils; +using iText.Kernel.Crypto; using iText.Kernel.Exceptions; using iText.Kernel.Logs; @@ -59,7 +61,7 @@ public abstract class SecurityHandler { /// protected internal int nextObjectKeySize; - protected internal IDigest md5; + protected internal IMessageDigest md5; /// Work area to prepare the object/generation bytes protected internal byte[] extra = new byte[5]; @@ -91,10 +93,38 @@ public virtual void SetHashKeyForNextObject(int objNumber, int objGeneration) { } } + /// Gets a stream wrapper, responsible for encryption. + /// + /// + /// + /// to be wrapped + /// + /// + /// + /// + /// , responsible for encryption. + /// public abstract OutputStreamEncryption GetEncryptionStream(Stream os); + /// Gets decryptor object. + /// + /// + /// + /// public abstract IDecryptor GetDecryptor(); + /// Gets encryption key for a particular object/generation. + /// encryption key for a particular object/generation. + public virtual byte[] GetNextObjectKey() { + return JavaUtil.ArraysCopyOf(nextObjectKey, nextObjectKey.Length); + } + + /// Gets global encryption key. + /// global encryption key. + public virtual byte[] GetMkey() { + return JavaUtil.ArraysCopyOf(mkey, mkey.Length); + } + private void SafeInitMessageDigest() { try { md5 = iText.Bouncycastleconnector.BouncyCastleFactoryCreator.GetFactory().CreateIDigest("MD5"); diff --git a/itext/itext.kernel/itext/kernel/crypto/securityhandler/StandardHandlerUsingAes256.cs b/itext/itext.kernel/itext/kernel/crypto/securityhandler/StandardHandlerUsingAes256.cs index 51143e15e2..504c045148 100644 --- a/itext/itext.kernel/itext/kernel/crypto/securityhandler/StandardHandlerUsingAes256.cs +++ b/itext/itext.kernel/itext/kernel/crypto/securityhandler/StandardHandlerUsingAes256.cs @@ -40,10 +40,10 @@ public class StandardHandlerUsingAes256 : StandardSecurityHandler { private const int SALT_LENGTH = 8; - private bool isPdf2; - protected internal bool encryptMetadata; + private bool isPdf2; + public StandardHandlerUsingAes256(PdfDictionary encryptionDictionary, byte[] userPassword, byte[] ownerPassword , int permissions, bool encryptMetadata, bool embeddedFilesOnly, PdfVersion version) { isPdf2 = version != null && version.CompareTo(PdfVersion.PDF_2_0) >= 0; @@ -55,6 +55,14 @@ public StandardHandlerUsingAes256(PdfDictionary encryptionDictionary, byte[] pas InitKeyAndReadDictionary(encryptionDictionary, password); } + /// Checks whether the document-level metadata stream will be encrypted. + /// + /// + /// + /// if the document-level metadata stream shall be encrypted, + /// + /// otherwise + /// public virtual bool IsEncryptMetadata() { return encryptMetadata; } @@ -71,6 +79,64 @@ public override IDecryptor GetDecryptor() { return new AesDecryptor(nextObjectKey, 0, nextObjectKeySize); } + /// + public override void SetPermissions(int permissions, PdfDictionary encryptionDictionary) { + base.SetPermissions(permissions, encryptionDictionary); + byte[] aes256Perms = GetAes256Perms(permissions, IsEncryptMetadata()); + encryptionDictionary.Put(PdfName.Perms, new PdfLiteral(StreamUtil.CreateEscapedString(aes256Perms))); + } + +//\cond DO_NOT_DOCUMENT + internal virtual void SetAES256DicEntries(PdfDictionary encryptionDictionary, byte[] oeKey, byte[] ueKey, + byte[] aes256Perms, bool encryptMetadata, bool embeddedFilesOnly) { + int version = 5; + int rAes256 = 5; + int rAes256Pdf2 = 6; + int revision = isPdf2 ? rAes256Pdf2 : rAes256; + PdfName cryptoFilter = PdfName.AESV3; + SetEncryptionDictionaryEntries(encryptionDictionary, oeKey, ueKey, aes256Perms, encryptMetadata, embeddedFilesOnly + , version, revision, cryptoFilter); + } +//\endcond + +//\cond DO_NOT_DOCUMENT + internal virtual void SetEncryptionDictionaryEntries(PdfDictionary encryptionDictionary, byte[] oeKey, byte + [] ueKey, byte[] aes256Perms, bool encryptMetadata, bool embeddedFilesOnly, int version, int revision, + PdfName cryptoFilter) { + encryptionDictionary.Put(PdfName.OE, new PdfLiteral(StreamUtil.CreateEscapedString(oeKey))); + encryptionDictionary.Put(PdfName.UE, new PdfLiteral(StreamUtil.CreateEscapedString(ueKey))); + encryptionDictionary.Put(PdfName.Perms, new PdfLiteral(StreamUtil.CreateEscapedString(aes256Perms))); + encryptionDictionary.Put(PdfName.R, new PdfNumber(revision)); + encryptionDictionary.Put(PdfName.V, new PdfNumber(version)); + PdfDictionary stdcf = new PdfDictionary(); + stdcf.Put(PdfName.Length, new PdfNumber(32)); + if (!encryptMetadata) { + encryptionDictionary.Put(PdfName.EncryptMetadata, PdfBoolean.FALSE); + } + if (embeddedFilesOnly) { + stdcf.Put(PdfName.AuthEvent, PdfName.EFOpen); + encryptionDictionary.Put(PdfName.EFF, PdfName.StdCF); + encryptionDictionary.Put(PdfName.StrF, PdfName.Identity); + encryptionDictionary.Put(PdfName.StmF, PdfName.Identity); + } + else { + stdcf.Put(PdfName.AuthEvent, PdfName.DocOpen); + encryptionDictionary.Put(PdfName.StrF, PdfName.StdCF); + encryptionDictionary.Put(PdfName.StmF, PdfName.StdCF); + } + stdcf.Put(PdfName.CFM, cryptoFilter); + PdfDictionary cf = new PdfDictionary(); + cf.Put(PdfName.StdCF, stdcf); + encryptionDictionary.Put(PdfName.CF, cf); + } +//\endcond + +//\cond DO_NOT_DOCUMENT + internal virtual bool IsPdf2(PdfDictionary encryptionDictionary) { + return encryptionDictionary.GetAsNumber(PdfName.R).GetValue() == 6; + } +//\endcond + private void InitKeyAndFillDictionary(PdfDictionary encryptionDictionary, byte[] userPassword, byte[] ownerPassword , int permissions, bool encryptMetadata, bool embeddedFilesOnly) { ownerPassword = GenerateOwnerPasswordIfNullOrEmpty(ownerPassword); @@ -116,21 +182,7 @@ private void InitKeyAndFillDictionary(PdfDictionary encryptionDictionary, byte[] ac = new AESCipherCBCnoPad(true, hash); oeKey = ac.ProcessBlock(nextObjectKey, 0, nextObjectKey.Length); // Algorithm 10 - byte[] permsp = IVGenerator.GetIV(16); - permsp[0] = (byte)permissions; - permsp[1] = (byte)(permissions >> 8); - permsp[2] = (byte)(permissions >> 16); - permsp[3] = (byte)(permissions >> 24); - permsp[4] = (byte)(255); - permsp[5] = (byte)(255); - permsp[6] = (byte)(255); - permsp[7] = (byte)(255); - permsp[8] = encryptMetadata ? (byte)'T' : (byte)'F'; - permsp[9] = (byte)'a'; - permsp[10] = (byte)'d'; - permsp[11] = (byte)'b'; - ac = new AESCipherCBCnoPad(true, nextObjectKey); - aes256Perms = ac.ProcessBlock(permsp, 0, permsp.Length); + aes256Perms = GetAes256Perms(permissions, encryptMetadata); this.permissions = permissions; this.encryptMetadata = encryptMetadata; SetStandardHandlerDicEntries(encryptionDictionary, userKey, ownerKey); @@ -141,36 +193,25 @@ private void InitKeyAndFillDictionary(PdfDictionary encryptionDictionary, byte[] } } - private void SetAES256DicEntries(PdfDictionary encryptionDictionary, byte[] oeKey, byte[] ueKey, byte[] aes256Perms - , bool encryptMetadata, bool embeddedFilesOnly) { - int vAes256 = 5; - int rAes256 = 5; - int rAes256Pdf2 = 6; - encryptionDictionary.Put(PdfName.OE, new PdfLiteral(StreamUtil.CreateEscapedString(oeKey))); - encryptionDictionary.Put(PdfName.UE, new PdfLiteral(StreamUtil.CreateEscapedString(ueKey))); - encryptionDictionary.Put(PdfName.Perms, new PdfLiteral(StreamUtil.CreateEscapedString(aes256Perms))); - encryptionDictionary.Put(PdfName.R, new PdfNumber(isPdf2 ? rAes256Pdf2 : rAes256)); - encryptionDictionary.Put(PdfName.V, new PdfNumber(vAes256)); - PdfDictionary stdcf = new PdfDictionary(); - stdcf.Put(PdfName.Length, new PdfNumber(32)); - if (!encryptMetadata) { - encryptionDictionary.Put(PdfName.EncryptMetadata, PdfBoolean.FALSE); - } - if (embeddedFilesOnly) { - stdcf.Put(PdfName.AuthEvent, PdfName.EFOpen); - encryptionDictionary.Put(PdfName.EFF, PdfName.StdCF); - encryptionDictionary.Put(PdfName.StrF, PdfName.Identity); - encryptionDictionary.Put(PdfName.StmF, PdfName.Identity); - } - else { - stdcf.Put(PdfName.AuthEvent, PdfName.DocOpen); - encryptionDictionary.Put(PdfName.StrF, PdfName.StdCF); - encryptionDictionary.Put(PdfName.StmF, PdfName.StdCF); - } - stdcf.Put(PdfName.CFM, PdfName.AESV3); - PdfDictionary cf = new PdfDictionary(); - cf.Put(PdfName.StdCF, stdcf); - encryptionDictionary.Put(PdfName.CF, cf); + private byte[] GetAes256Perms(int permissions, bool encryptMetadata) { + byte[] aes256Perms; + AESCipherCBCnoPad ac; + byte[] permsp = IVGenerator.GetIV(16); + permsp[0] = (byte)permissions; + permsp[1] = (byte)(permissions >> 8); + permsp[2] = (byte)(permissions >> 16); + permsp[3] = (byte)(permissions >> 24); + permsp[4] = (byte)(255); + permsp[5] = (byte)(255); + permsp[6] = (byte)(255); + permsp[7] = (byte)(255); + permsp[8] = encryptMetadata ? (byte)'T' : (byte)'F'; + permsp[9] = (byte)'a'; + permsp[10] = (byte)'d'; + permsp[11] = (byte)'b'; + ac = new AESCipherCBCnoPad(true, nextObjectKey); + aes256Perms = ac.ProcessBlock(permsp, 0, permsp.Length); + return aes256Perms; } private void InitKeyAndReadDictionary(PdfDictionary encryptionDictionary, byte[] password) { @@ -183,19 +224,19 @@ private void InitKeyAndReadDictionary(PdfDictionary encryptionDictionary, byte[] password = JavaUtil.ArraysCopyOf(password, 127); } } - isPdf2 = encryptionDictionary.GetAsNumber(PdfName.R).GetValue() == 6; - //truncate user and owner passwords to 48 bytes where the first 32 bytes - //are a hash value, next 8 bytes are validation salt and final 8 bytes are the key salt + isPdf2 = IsPdf2(encryptionDictionary); + // Truncate user and owner passwords to 48 bytes where the first 32 bytes + // are a hash value, next 8 bytes are validation salt and final 8 bytes are the key salt byte[] oValue = TruncateArray(GetIsoBytes(encryptionDictionary.GetAsString(PdfName.O))); byte[] uValue = TruncateArray(GetIsoBytes(encryptionDictionary.GetAsString(PdfName.U))); byte[] oeValue = GetIsoBytes(encryptionDictionary.GetAsString(PdfName.OE)); byte[] ueValue = GetIsoBytes(encryptionDictionary.GetAsString(PdfName.UE)); byte[] perms = GetIsoBytes(encryptionDictionary.GetAsString(PdfName.Perms)); PdfNumber pValue = (PdfNumber)encryptionDictionary.Get(PdfName.P); - this.permissions = pValue.LongValue(); + this.permissions = pValue.IntValue(); byte[] hash; hash = ComputeHash(password, oValue, VALIDATION_SALT_OFFSET, SALT_LENGTH, uValue); - usedOwnerPassword = CompareArray(hash, oValue, 32); + usedOwnerPassword = EqualsArray(hash, oValue, 32); if (usedOwnerPassword) { hash = ComputeHash(password, oValue, KEY_SALT_OFFSET, SALT_LENGTH, uValue); AESCipherCBCnoPad ac = new AESCipherCBCnoPad(false, hash); @@ -203,7 +244,7 @@ private void InitKeyAndReadDictionary(PdfDictionary encryptionDictionary, byte[] } else { hash = ComputeHash(password, uValue, VALIDATION_SALT_OFFSET, SALT_LENGTH); - if (!CompareArray(hash, uValue, 32)) { + if (!EqualsArray(hash, uValue, 32)) { throw new BadPasswordException(KernelExceptionMessageConstant.BAD_USER_PASSWORD); } hash = ComputeHash(password, uValue, KEY_SALT_OFFSET, SALT_LENGTH); @@ -301,6 +342,7 @@ private byte[] ComputeHash(byte[] password, byte[] salt, int saltOffset, int sal } } // d) + System.Diagnostics.Debug.Assert(md != null); k = md.Digest(e); ++roundNum; if (roundNum > 63) { @@ -317,15 +359,6 @@ private byte[] ComputeHash(byte[] password, byte[] salt, int saltOffset, int sal return k; } - private static bool CompareArray(byte[] a, byte[] b, int len) { - for (int k = 0; k < len; ++k) { - if (a[k] != b[k]) { - return false; - } - } - return true; - } - private byte[] TruncateArray(byte[] array) { if (array.Length == 48) { return array; diff --git a/itext/itext.kernel/itext/kernel/crypto/securityhandler/StandardHandlerUsingAesGcm.cs b/itext/itext.kernel/itext/kernel/crypto/securityhandler/StandardHandlerUsingAesGcm.cs new file mode 100644 index 0000000000..21b62f5a4d --- /dev/null +++ b/itext/itext.kernel/itext/kernel/crypto/securityhandler/StandardHandlerUsingAesGcm.cs @@ -0,0 +1,104 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System.IO; +using iText.Kernel.Crypto; +using iText.Kernel.Pdf; + +namespace iText.Kernel.Crypto.Securityhandler { + /// Standard security handler with Advanced Encryption Standard-Galois/Counter Mode (AES-GCM) encryption algorithm. + /// + public class StandardHandlerUsingAesGcm : StandardHandlerUsingAes256 { + protected internal byte[] noncePart = null; + + protected internal int inObjectNonceCounter = 0; + + /// + /// Creates new + /// + /// instance for encryption. + /// + /// document's encryption dictionary + /// user password + /// owner password + /// access permissions + /// indicates whether the document-level metadata stream shall be encrypted + /// indicates whether embedded files shall be encrypted in an otherwise unencrypted document + /// + public StandardHandlerUsingAesGcm(PdfDictionary encryptionDictionary, byte[] userPassword, byte[] ownerPassword + , int permissions, bool encryptMetadata, bool embeddedFilesOnly) + : base(encryptionDictionary, userPassword, ownerPassword, permissions, encryptMetadata, embeddedFilesOnly, + PdfVersion.PDF_2_0) { + } + + /// + /// Creates new + /// + /// instance for decryption. + /// + /// document's encryption dictionary + /// owner or user password to decrypt the document + public StandardHandlerUsingAesGcm(PdfDictionary encryptionDictionary, byte[] password) + : base(encryptionDictionary, password) { + } + + public override void SetHashKeyForNextObject(int objNumber, int objGeneration) { + // Make sure the same IV is never used twice in the same file. We do this by turning the objId/objGen into a + // 5-byte nonce (with generation restricted to 1 byte instead of 2) plus an in-object 2-byte counter that + // increments each time a new string is encrypted within the same object. The remaining 5 bytes will be + // generated randomly using a strong PRNG. + // This is very different from the situation with AES-CBC, where randomness is paramount. GCM uses a variation + // of counter mode, so making sure the IV is unique is more important than randomness. + this.inObjectNonceCounter = 0; + this.noncePart = new byte[] { 0, 0, (byte)(objGeneration), (byte)((int)(((uint)objNumber) >> 24)), (byte)( + (int)(((uint)objNumber) >> 16)), (byte)((int)(((uint)objNumber) >> 8)), (byte)(objNumber) }; + } + + public override OutputStreamEncryption GetEncryptionStream(Stream os) { + int ctr = inObjectNonceCounter; + noncePart[0] = (byte)((int)(((uint)ctr) >> 8)); + noncePart[1] = (byte)ctr; + return new OutputStreamAesGcmEncryption(os, nextObjectKey, noncePart); + } + + public override IDecryptor GetDecryptor() { + return new AesGcmDecryptor(nextObjectKey, 0, nextObjectKeySize); + } + +//\cond DO_NOT_DOCUMENT + internal override void SetAES256DicEntries(PdfDictionary encryptionDictionary, byte[] oeKey, byte[] ueKey, + byte[] aes256Perms, bool encryptMetadata, bool embeddedFilesOnly) { + int version = 6; + int revision = 7; + PdfName cryptoFilter = PdfName.AESV4; + SetEncryptionDictionaryEntries(encryptionDictionary, oeKey, ueKey, aes256Perms, encryptMetadata, embeddedFilesOnly + , version, revision, cryptoFilter); + } +//\endcond + +//\cond DO_NOT_DOCUMENT + internal override bool IsPdf2(PdfDictionary encryptionDictionary) { + return true; + } +//\endcond + } +} diff --git a/itext/itext.kernel/itext/kernel/crypto/securityhandler/StandardHandlerUsingStandard40.cs b/itext/itext.kernel/itext/kernel/crypto/securityhandler/StandardHandlerUsingStandard40.cs index 4aae761362..4380cc21a7 100644 --- a/itext/itext.kernel/itext/kernel/crypto/securityhandler/StandardHandlerUsingStandard40.cs +++ b/itext/itext.kernel/itext/kernel/crypto/securityhandler/StandardHandlerUsingStandard40.cs @@ -163,7 +163,7 @@ private void InitKeyAndReadDictionary(PdfDictionary encryptionDictionary, byte[] byte[] uValue = GetIsoBytes(encryptionDictionary.GetAsString(PdfName.U)); byte[] oValue = GetIsoBytes(encryptionDictionary.GetAsString(PdfName.O)); PdfNumber pValue = (PdfNumber)encryptionDictionary.Get(PdfName.P); - this.permissions = pValue.LongValue(); + this.permissions = pValue.IntValue(); this.documentId = documentId; keyLength = GetKeyLength(encryptionDictionary); byte[] paddedPassword = PadPassword(password); diff --git a/itext/itext.kernel/itext/kernel/crypto/securityhandler/StandardSecurityHandler.cs b/itext/itext.kernel/itext/kernel/crypto/securityhandler/StandardSecurityHandler.cs index 28f9129517..4b03dbf8a1 100644 --- a/itext/itext.kernel/itext/kernel/crypto/securityhandler/StandardSecurityHandler.cs +++ b/itext/itext.kernel/itext/kernel/crypto/securityhandler/StandardSecurityHandler.cs @@ -28,18 +28,26 @@ namespace iText.Kernel.Crypto.Securityhandler { public abstract class StandardSecurityHandler : SecurityHandler { protected internal const int PERMS_MASK_1_FOR_REVISION_2 = unchecked((int)(0xffffffc0)); - protected internal const int PERMS_MASK_1_FOR_REVISION_3_OR_GREATER = unchecked((int)(0xfffff0c0)); + protected internal const int PERMS_MASK_1_FOR_REVISION_3_OR_GREATER = unchecked((int)(0xffffe0c0)); protected internal const int PERMS_MASK_2 = unchecked((int)(0xfffffffc)); - protected internal long permissions; + protected internal int permissions; protected internal bool usedOwnerPassword = true; - public virtual long GetPermissions() { + public virtual int GetPermissions() { return permissions; } + /// Updates encryption dictionary with the security permissions provided. + /// new permissions to set + /// encryption dictionary to update + public virtual void SetPermissions(int permissions, PdfDictionary encryptionDictionary) { + this.permissions = permissions; + encryptionDictionary.Put(PdfName.P, new PdfNumber(permissions)); + } + public virtual bool IsUsedOwnerPassword() { return usedOwnerPassword; } diff --git a/itext/itext.kernel/itext/kernel/di/pagetree/DefaultPageTreeListFactory.cs b/itext/itext.kernel/itext/kernel/di/pagetree/DefaultPageTreeListFactory.cs new file mode 100644 index 0000000000..5da2f56473 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/di/pagetree/DefaultPageTreeListFactory.cs @@ -0,0 +1,86 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Commons.Datastructures; +using iText.Kernel.Pdf; + +namespace iText.Kernel.DI.Pagetree { + /// + /// This class is a default implementation of + /// + /// that is used as a default. + /// + /// + /// This class is a default implementation of + /// + /// that is used as a default. + /// + /// This class will create an arraylist when in creation mode. + /// In reading and editing mode, it will create a NullUnlimitedList if the count is greater than the + /// maxEntriesBeforeSwitchingToNullUnlimitedList. This is to prevent potential OOM exceptions when loading a document + /// with a large number of pages where only a few pages are needed. + /// + public class DefaultPageTreeListFactory : IPageTreeListFactory { + private readonly int maxEntriesBeforeSwitchingToNullUnlimitedList; + + /// Creates a new instance of DefaultPageTreeListFactory. + /// + /// the maximum number of entries before switching to + /// a NullUnlimitedList. + /// + public DefaultPageTreeListFactory(int maxEntriesBeforeSwitchingToNullUnlimitedList) { + this.maxEntriesBeforeSwitchingToNullUnlimitedList = maxEntriesBeforeSwitchingToNullUnlimitedList; + } + + /// Creates a list based on the count value in the pages dictionary. + /// + /// Creates a list based on the count value in the pages dictionary. If the count value is greater than the + /// maxEntriesBeforeSwitchingToNullUnlimitedList, a NullUnlimitedList is created. This is to optimize memory usage + /// when loading a document with a large number of pages where only a few pages are needed. + /// + /// The pages dictionary + /// The type of the list + /// The list + public virtual ISimpleList CreateList(PdfDictionary pagesDictionary) { + //If dictionary is null, it means we are dealing with document creation. + if (pagesDictionary == null) { + return new SimpleArrayList(); + } + PdfNumber count = pagesDictionary.GetAsNumber(PdfName.Count); + if (count == null) { + //If count is null, it means we are dealing with a possible corrupted document. + //In this case we use NullUnlimitedList to avoid creating a huge list. + return new NullUnlimitedList(); + } + int countValue = count.IntValue(); + if (countValue > maxEntriesBeforeSwitchingToNullUnlimitedList) { + return new NullUnlimitedList(); + } + if (countValue < 0) { + //If count is negative, it means we are dealing with a possible corrupted document. + return new NullUnlimitedList(); + } + //Initial capacity is set to count value to avoid resizing of the list. + return new SimpleArrayList(countValue); + } + } +} diff --git a/itext/itext.kernel/itext/kernel/di/pagetree/IPageTreeListFactory.cs b/itext/itext.kernel/itext/kernel/di/pagetree/IPageTreeListFactory.cs new file mode 100644 index 0000000000..880790ac7c --- /dev/null +++ b/itext/itext.kernel/itext/kernel/di/pagetree/IPageTreeListFactory.cs @@ -0,0 +1,40 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Commons.Datastructures; +using iText.Kernel.Pdf; + +namespace iText.Kernel.DI.Pagetree { + /// This interface is used to create a list of pages from a pages dictionary. + public interface IPageTreeListFactory { + /// Creates a list based on the value of the pages dictionary. + /// + /// Creates a list based on the value of the pages dictionary. + /// If null, it means we are dealing with document creation. In other cases the pdf document pages + /// dictionary will be passed. + /// + /// The pages dictionary + /// The type of the list + /// The list + ISimpleList CreateList(PdfDictionary pagesDictionary); + } +} diff --git a/itext/itext.kernel/itext/kernel/events/EventDispatcher.cs b/itext/itext.kernel/itext/kernel/events/EventDispatcher.cs deleted file mode 100644 index ebea2532ee..0000000000 --- a/itext/itext.kernel/itext/kernel/events/EventDispatcher.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* -This file is part of the iText (R) project. -Copyright (c) 1998-2024 Apryse Group NV -Authors: Apryse Software. - -This program is offered under a commercial and under the AGPL license. -For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. - -AGPL licensing: -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . -*/ -using System; -using System.Collections.Generic; - -namespace iText.Kernel.Events { - /// - /// IEventDispatcher implementation that forwards Events to registered - /// - /// implementations. - /// - public class EventDispatcher : IEventDispatcher { - protected internal IDictionary> eventHandlers = new Dictionary - >(); - - public virtual void AddEventHandler(String type, iText.Kernel.Events.IEventHandler handler) { - RemoveEventHandler(type, handler); - IList handlers = eventHandlers.Get(type); - if (handlers == null) { - handlers = new List(); - eventHandlers.Put(type, handlers); - } - handlers.Add(handler); - } - - public virtual void DispatchEvent(Event @event) { - DispatchEvent(@event, false); - } - - public virtual void DispatchEvent(Event @event, bool delayed) { - IList handlers = eventHandlers.Get(@event.GetEventType()); - if (handlers != null) { - foreach (iText.Kernel.Events.IEventHandler handler in handlers) { - handler.HandleEvent(@event); - } - } - } - - public virtual bool HasEventHandler(String type) { - return eventHandlers.ContainsKey(type); - } - - public virtual void RemoveEventHandler(String type, iText.Kernel.Events.IEventHandler handler) { - IList handlers = eventHandlers.Get(type); - if (handlers == null) { - return; - } - handlers.Remove(handler); - if (handlers.Count == 0) { - eventHandlers.JRemove(type); - } - } - - public virtual void RemoveAllHandlers() { - eventHandlers.Clear(); - } - } -} diff --git a/itext/itext.kernel/itext/kernel/events/IEventDispatcher.cs b/itext/itext.kernel/itext/kernel/events/IEventDispatcher.cs deleted file mode 100644 index bc8bc3911f..0000000000 --- a/itext/itext.kernel/itext/kernel/events/IEventDispatcher.cs +++ /dev/null @@ -1,81 +0,0 @@ -/* -This file is part of the iText (R) project. -Copyright (c) 1998-2024 Apryse Group NV -Authors: Apryse Software. - -This program is offered under a commercial and under the AGPL license. -For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. - -AGPL licensing: -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . -*/ -using System; - -namespace iText.Kernel.Events { - /// Event dispatcher interface. - public interface IEventDispatcher { - /// Adds new event handler. - /// a type of event to be handled - /// event handler - void AddEventHandler(String type, iText.Kernel.Events.IEventHandler handler); - - /// Dispatches an event. - /// - /// the - /// - /// to be dispatched - /// - void DispatchEvent(Event @event); - - /// Dispatches a delayed event. - /// - /// Dispatches a delayed event. - /// Sometimes event cannot be handled immediately because event handler has not been set yet. - /// In this case event is placed into event ques of dispatcher and is waiting until handler is assigned. - /// - /// - /// the - /// - /// to be dispatched - /// - /// - /// flag whether - /// - /// delayed or not - /// - void DispatchEvent(Event @event, bool delayed); - - /// Checks if event dispatcher as an event handler assigned for a certain event type. - /// - /// a type of the - /// - /// - /// true if event dispatcher as an event handler assigned for a certain event type - bool HasEventHandler(String type); - - /// Removes event handler. - /// - /// a type of the - /// - /// - /// - /// event handler - /// - /// - void RemoveEventHandler(String type, iText.Kernel.Events.IEventHandler handler); - - /// Remove all event handlers. - void RemoveAllHandlers(); - } -} diff --git a/itext/itext.kernel/itext/kernel/exceptions/KernelExceptionMessageConstant.cs b/itext/itext.kernel/itext/kernel/exceptions/KernelExceptionMessageConstant.cs index 1d3298e591..b61ae47368 100644 --- a/itext/itext.kernel/itext/kernel/exceptions/KernelExceptionMessageConstant.cs +++ b/itext/itext.kernel/itext/kernel/exceptions/KernelExceptionMessageConstant.cs @@ -97,6 +97,8 @@ public sealed class KernelExceptionMessageConstant { public const String CANNOT_FIND_IMAGE_DATA_OR_EI = "Cannot find image data or EI."; + public const String UNSUPPORTED_ENCODING_FOR_INLINE_IMAGE = "Cannot parse inline image: {0} encoding is unsupported."; + public const String CANNOT_FLUSH_DOCUMENT_ROOT_TAG_BEFORE_DOCUMENT_IS_CLOSED = "Cannot flush document root " + "tag before document is closed."; @@ -162,6 +164,12 @@ public sealed class KernelExceptionMessageConstant { public const String COLOR_SPACE_NOT_FOUND = "ColorSpace not found."; + public const String CONTAINER_EMBEDDING_EXCEPTION = "IOException occurred while trying to embed MAC container into document output stream."; + + public const String CONTAINER_GENERATION_EXCEPTION = "Exception occurred during MAC container generation."; + + public const String CONTAINER_PARSING_EXCEPTION = "Exception occurred during MAC container parsing."; + public const String CONTENT_STREAM_MUST_NOT_INVOKE_OPERATORS_THAT_SPECIFY_COLORS_OR_OTHER_COLOR_RELATED_PARAMETERS = "Content stream must not invoke operators that specify colors or other color related parameters in " + "the graphics state."; @@ -181,6 +189,8 @@ public const String CONTENT_STREAM_MUST_NOT_INVOKE_OPERATORS_THAT_SPECIFY_COLORS public const String THIS_DICTIONARY_KEY_IS_NOT_A_NAME = "Dictionary key {0} is not a name."; + public const String DIGEST_NOT_SUPPORTED = "This digest algorithm is not supported for MAC integrity protection."; + public const String DICTIONARY_DOES_NOT_HAVE_SUPPORTED_FONT_DATA = "Dictionary doesn't have supported font " + "data."; @@ -282,7 +292,7 @@ public const String CONTENT_STREAM_MUST_NOT_INVOKE_OPERATORS_THAT_SPECIFY_COLORS public const String INVALID_CROSS_REFERENCE_ENTRY_IN_THIS_XREF_SUBSECTION = "Invalid cross reference entry " + "in this xref subsection."; - public const String INVALID_INDIRECT_REFERENCE = "Invalid indirect reference {0}."; + public const String INVALID_INDIRECT_REFERENCE = "Invalid indirect reference {0} {1} R."; public const String INVALID_INPUT_FOR_TYPE_2_FUNCTION = "Invalid input value for PDF Type 2 Function, value should be a single number."; @@ -344,6 +354,28 @@ public const String CONTENT_STREAM_MUST_NOT_INVOKE_OPERATORS_THAT_SPECIFY_COLORS public const String LZW_FLAVOUR_NOT_SUPPORTED = "LZW flavour not supported."; + public const String MAC_ALGORITHM_NOT_SUPPORTED = "This MAC algorithm is not supported."; + + public const String MAC_ATTRIBUTE_NOT_SPECIFIED = "Signature doesn't contain unsigned MAC attribute, which is required in \"attached to signature\" mode."; + + public const String MAC_EXTRACTION_EXCEPTION = "Exception occurred during signature parsing. It is not possible to extract MAC."; + + public const String MAC_LOCATION_NOT_SPECIFIED = "AuthCode dictionary doesn't contain MACLocation entry."; + + public const String MAC_NOT_SPECIFIED = "AuthCode dictionary doesn't contain MAC entry, which is required in standalone mode."; + + public const String MAC_FOR_ENCRYPTION_5 = "MAC integrity protection is only supported for encryption algorithms of version 5 or higher."; + + public const String MAC_FOR_PDF_2 = "MAC integrity protection is only supported for PDF 2.0 or higher."; + + public const String MAC_PERMS_WITHOUT_MAC = "Permissions bit 13 is set to zero, " + "which indicates that MAC integrity protection is enabled. However MAC container wasn't found."; + + public const String MAC_VALIDATION_EXCEPTION = "Unexpected exception occurred during MAC token validation."; + + public const String MAC_VALIDATION_FAILED = "MAC integrity protection was compromised. Document content was modified."; + + public const String MAC_VALIDATION_NO_SALT = "MAC token validation failed. Salt is not found."; + public const String MISSING_REQUIRED_FIELD_IN_FONT_DICTIONARY = "Missing required field {0} in font dictionary."; public const String MUST_BE_A_TAGGED_DOCUMENT = "Must be a tagged document."; @@ -443,6 +475,8 @@ public const String CONTENT_STREAM_MUST_NOT_INVOKE_OPERATORS_THAT_SPECIFY_COLORS public const String SHADING_TYPE_NOT_FOUND = "Shading type not found."; + public const String SIG_OBJ_REF_NOT_SPECIFIED = "AuthCode dictionary doesn't contain SigObjRef entry, which is required in signature mode."; + public const String STDCF_NOT_FOUND_ENCRYPTION = "/StdCF not found (encryption)"; public const String STREAM_SHALL_END_WITH_ENDSTREAM = "Stream shall end with endstream keyword."; @@ -479,6 +513,8 @@ public const String CONTENT_STREAM_MUST_NOT_INVOKE_OPERATORS_THAT_SPECIFY_COLORS public const String THERE_IS_NO_ASSOCIATE_PDF_WRITER_FOR_MAKING_INDIRECTS = "There is no associate " + "PdfWriter for making indirects."; + public const String THE_NAME_OF_THE_DIGEST_ALGORITHM_IS_NULL = "The name of the digest algorithm is null."; + public const String THIS_DECODE_PARAMETER_TYPE_IS_NOT_SUPPORTED = "Decode parameter type {0} is not " + "supported."; public const String THIS_FILTER_IS_NOT_SUPPORTED = "Filter {0} is not supported."; @@ -500,8 +536,6 @@ public const String CONTENT_STREAM_MUST_NOT_INVOKE_OPERATORS_THAT_SPECIFY_COLORS public const String UNBALANCED_SAVE_RESTORE_STATE_OPERATORS = "Unbalanced save restore state operators."; - public const String UNEXPECTED_CHARACTER_FOUND_AFTER_ID_IN_INLINE_IMAGE = "Unexpected character {0} " + "found after ID in inline image."; - public const String UNEXPECTED_COLOR_SPACE = "Unexpected ColorSpace: {0}."; public const String UNEXPECTED_END_OF_FILE = "Unexpected end of file."; @@ -531,6 +565,8 @@ public const String WHEN_ADDING_OBJECT_REFERENCE_TO_THE_TAG_TREE_IT_MUST_BE_CONN public const String WMF_IMAGE_EXCEPTION = "WMF image exception."; + public const String WRAP_ALGORITHM_NOT_SUPPORTED = "This wrapping algorithm is not supported."; + public const String WRONG_MEDIA_BOX_SIZE_TOO_FEW_ARGUMENTS = "Wrong media box size: {0}. Need at least 4 " + "arguments"; @@ -619,6 +655,16 @@ public const String WHEN_ADDING_OBJECT_REFERENCE_TO_THE_TAG_TREE_IT_MUST_BE_CONN public const String INVALID_OBJECT_STREAM_NUMBER = "Unable to read object {0} with object stream " + "number {1} and index {2} from object stream."; + //TODO DEVSIX-8490 remove this exception message when implemented + public const String UNABLE_TO_ADD_SECOND_PARENT_LAYER = "Unable to add second parent layer to " + "{0} ocg layer"; + + //TODO DEVSIX-8490 remove this exception message when implemented + public const String UNABLE_TO_REMOVE_DUPLICATE_LAYER = "Unable to remove duplicated layer {0} " + "because it has child layers."; + + public const String TYPE_SHOULD_NOT_BE_NULL = "ClassArgument type should not be null"; + + public const String INSTANCE_SHOULD_NOT_BE_NULL = "Instance should not be null"; + private KernelExceptionMessageConstant() { } } diff --git a/itext/itext.kernel/itext/kernel/font/FontUtil.cs b/itext/itext.kernel/itext/kernel/font/FontUtil.cs index 1ca1e19d96..5701f5f47a 100644 --- a/itext/itext.kernel/itext/kernel/font/FontUtil.cs +++ b/itext/itext.kernel/itext/kernel/font/FontUtil.cs @@ -67,7 +67,7 @@ internal static CMapToUnicode ProcessToUnicode(PdfObject toUnicode) { } catch (Exception e) { LOGGER.LogError(e, iText.IO.Logs.IoLogMessageConstant.UNKNOWN_ERROR_WHILE_PROCESSING_CMAP); - cMapToUnicode = CMapToUnicode.EmptyCMapToUnicodeMap; + cMapToUnicode = CMapToUnicode.EMPTY_CMAP; } } else { diff --git a/itext/itext.kernel/itext/kernel/font/PdfSimpleFont.cs b/itext/itext.kernel/itext/kernel/font/PdfSimpleFont.cs index fc779c1ac1..43c362a015 100644 --- a/itext/itext.kernel/itext/kernel/font/PdfSimpleFont.cs +++ b/itext/itext.kernel/itext/kernel/font/PdfSimpleFont.cs @@ -292,7 +292,7 @@ public override bool AppendDecodedCodesToGlyphsList(IList list, PdfString public override float GetContentWidth(PdfString content) { float width = 0; GlyphLine glyphLine = DecodeIntoGlyphLine(content); - for (int i = glyphLine.start; i < glyphLine.end; i++) { + for (int i = glyphLine.GetStart(); i < glyphLine.GetEnd(); i++) { width += glyphLine.Get(i).GetWidth(); } return width; @@ -464,9 +464,9 @@ protected internal override PdfDictionary GetFontDescriptor(String fontName) { AddFontStream(fontDescriptor); int flags = fontProgram.GetPdfFontFlags(); // reset both flags - flags &= ~(FontDescriptorFlags.Symbolic | FontDescriptorFlags.Nonsymbolic); + flags &= ~(FontDescriptorFlags.SYMBOLIC | FontDescriptorFlags.NONSYMBOLIC); // set fontSpecific based on font encoding - flags |= fontEncoding.IsFontSpecific() ? FontDescriptorFlags.Symbolic : FontDescriptorFlags.Nonsymbolic; + flags |= fontEncoding.IsFontSpecific() ? FontDescriptorFlags.SYMBOLIC : FontDescriptorFlags.NONSYMBOLIC; fontDescriptor.Put(PdfName.Flags, new PdfNumber(flags)); return fontDescriptor; } diff --git a/itext/itext.kernel/itext/kernel/font/PdfType0Font.cs b/itext/itext.kernel/itext/kernel/font/PdfType0Font.cs index 2ee225f9e6..9447ccf003 100644 --- a/itext/itext.kernel/itext/kernel/font/PdfType0Font.cs +++ b/itext/itext.kernel/itext/kernel/font/PdfType0Font.cs @@ -363,13 +363,13 @@ public override byte[] ConvertToBytes(GlyphLine glyphLine) { CMapCharsetEncoder encoder = StandardCMapCharsets.GetEncoder(cmapEncoding.GetCmapName()); if (encoder == null) { int totalByteCount = 0; - for (int i = glyphLine.start; i < glyphLine.end; i++) { + for (int i = glyphLine.GetStart(); i < glyphLine.GetEnd(); i++) { totalByteCount += cmapEncoding.GetCmapBytesLength(glyphLine.Get(i).GetCode()); } // perform actual conversion byte[] bytes = new byte[totalByteCount]; int offset = 0; - for (int i = glyphLine.start; i < glyphLine.end; i++) { + for (int i = glyphLine.GetStart(); i < glyphLine.GetEnd(); i++) { usedGlyphs.Add(glyphLine.Get(i).GetCode()); offset = cmapEncoding.FillCmapBytes(glyphLine.Get(i).GetCode(), bytes, offset); } @@ -377,7 +377,7 @@ public override byte[] ConvertToBytes(GlyphLine glyphLine) { } else { MemoryStream baos = new MemoryStream(); - for (int i = glyphLine.start; i < glyphLine.end; i++) { + for (int i = glyphLine.GetStart(); i < glyphLine.GetEnd(); i++) { Glyph g = glyphLine.Get(i); usedGlyphs.Add(g.GetCode()); byte[] encodedBit = encoder.EncodeUnicodeCodePoint(g.GetUnicode()); @@ -683,7 +683,7 @@ public override bool AppendDecodedCodesToGlyphsList(IList list, PdfString public override float GetContentWidth(PdfString content) { float width = 0; GlyphLine glyphLine = DecodeIntoGlyphLine(content); - for (int i = glyphLine.start; i < glyphLine.end; i++) { + for (int i = glyphLine.GetStart(); i < glyphLine.GetEnd(); i++) { width += glyphLine.Get(i).GetWidth(); } return width; @@ -920,7 +920,8 @@ protected internal virtual PdfDictionary GetCidFont(PdfDictionary fontDescriptor private PdfObject GenerateWidthsArray() { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - OutputStream stream = new OutputStream(bytes); + HighPrecisionOutputStream stream = new HighPrecisionOutputStream(bytes); stream.WriteByte('['); int lastNumber = -10; bool firstTime = true; @@ -953,8 +954,8 @@ private PdfObject GenerateWidthsArray() { /// Creates a ToUnicode CMap to allow copy and paste from Acrobat. /// the stream representing this CMap or null public virtual PdfStream GetToUnicode() { - OutputStream stream = new OutputStream(new ByteArrayOutputStream - ()); + HighPrecisionOutputStream stream = new HighPrecisionOutputStream(new ByteArrayOutputStream()); stream.WriteString("/CIDInit /ProcSet findresource begin\n" + "12 dict begin\n" + "begincmap\n" + "/CIDSystemInfo\n" + "<< /Registry (Adobe)\n" + "/Ordering (UCS)\n" + "/Supplement 0\n" + ">> def\n" + "/CMapName /Adobe-Identity-UCS def\n" + "/CMapType 2 def\n" + "1 begincodespacerange\n" + "<0000>\n" + "endcodespacerange\n"); @@ -979,7 +980,8 @@ public virtual PdfStream GetToUnicode() { return new PdfStream(((ByteArrayOutputStream)stream.GetOutputStream()).ToArray()); } - private int WriteBfrange(OutputStream stream, IList range) { + private static int WriteBfrange(HighPrecisionOutputStream stream, IList range + ) { if (range.IsEmpty()) { return 0; } diff --git a/itext/itext.kernel/itext/kernel/font/PdfType3Font.cs b/itext/itext.kernel/itext/kernel/font/PdfType3Font.cs index 86ead183e4..ae6b3bf81f 100644 --- a/itext/itext.kernel/itext/kernel/font/PdfType3Font.cs +++ b/itext/itext.kernel/itext/kernel/font/PdfType3Font.cs @@ -334,9 +334,9 @@ protected internal override PdfDictionary GetFontDescriptor(String fontName) { } int flags = fontProgram.GetPdfFontFlags(); // reset both flags - flags &= ~(FontDescriptorFlags.Symbolic | FontDescriptorFlags.Nonsymbolic); + flags &= ~(FontDescriptorFlags.SYMBOLIC | FontDescriptorFlags.NONSYMBOLIC); // set fontSpecific based on font encoding - flags |= fontEncoding.IsFontSpecific() ? FontDescriptorFlags.Symbolic : FontDescriptorFlags.Nonsymbolic; + flags |= fontEncoding.IsFontSpecific() ? FontDescriptorFlags.SYMBOLIC : FontDescriptorFlags.NONSYMBOLIC; fontDescriptor.Put(PdfName.Flags, new PdfNumber(flags)); return fontDescriptor; } diff --git a/itext/itext.kernel/itext/kernel/geom/AffineTransform.cs b/itext/itext.kernel/itext/kernel/geom/AffineTransform.cs index ee1f457829..55b27c5b13 100644 --- a/itext/itext.kernel/itext/kernel/geom/AffineTransform.cs +++ b/itext/itext.kernel/itext/kernel/geom/AffineTransform.cs @@ -24,6 +24,13 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Utils; namespace iText.Kernel.Geom { + /// + /// The + /// + /// class represents an affine transformation, + /// which is a combination of linear transformations such as translation, + /// scaling, rotation, and shearing which allows preservation of the straightness of lines. + /// public class AffineTransform { /// The type of affine transformation. /// @@ -136,12 +143,32 @@ public class AffineTransform { internal int type; //\endcond + /// + /// Create an empty + /// + /// instance. + /// + /// + /// Create an empty + /// + /// instance. + /// The default type is for the transformation is + /// TYPE_IDENTITY + /// public AffineTransform() { type = TYPE_IDENTITY; m00 = m11 = 1; m10 = m01 = m02 = m12 = 0; } + /// + /// Will create a new + /// + /// instance with the values provided from the original + /// + /// instance. + /// + /// The AffineTransform class to be used. public AffineTransform(iText.Kernel.Geom.AffineTransform t) { this.type = t.type; this.m00 = t.m00; @@ -152,6 +179,24 @@ public AffineTransform(iText.Kernel.Geom.AffineTransform t) { this.m12 = t.m12; } + /// + /// Create an + /// + /// instance with the values provided. + /// + /// + /// Create an + /// + /// instance with the values provided. + /// The default type is for the transformation is + /// TYPE_UNKNOWN + /// + /// The value of the first row and first column of the matrix. + /// The value of the second row and first column of the matrix. + /// The value of the first row and second column of the matrix. + /// The value of the second row and second column of the matrix. + /// The value of the first row and third column of the matrix. + /// The value of the second row and third column of the matrix. public AffineTransform(double m00, double m10, double m01, double m11, double m02, double m12) { this.type = TYPE_UNKNOWN; this.m00 = m00; @@ -162,6 +207,19 @@ public AffineTransform(double m00, double m10, double m01, double m11, double m0 this.m12 = m12; } + /// + /// Create an + /// + /// instance with the values provided. + /// + /// + /// Create an + /// + /// instance with the values provided. + /// The default type is for the transformation is + /// TYPE_UNKNOWN + /// + /// The array of values to be used for the transformation matrix. public AffineTransform(float[] matrix) { this.type = TYPE_UNKNOWN; m00 = matrix[0]; @@ -174,6 +232,19 @@ public AffineTransform(float[] matrix) { } } + /// + /// Create an + /// + /// instance with the values provided. + /// + /// + /// Create an + /// + /// instance with the values provided. + /// The default type is for the transformation is + /// TYPE_UNKNOWN + /// + /// The array of values to be used for the transformation matrix. public AffineTransform(double[] matrix) { this.type = TYPE_UNKNOWN; m00 = matrix[0]; @@ -275,34 +346,70 @@ public virtual int GetTransformType() { return type; } + /// Gets the scale factor of the x-axis. + /// the scale factor of the x-axis. public virtual double GetScaleX() { return m00; } + /// Gets the scale factor of the y-axis. + /// the scale factor of the y-axis. public virtual double GetScaleY() { return m11; } + /// Gets the shear factor of the x-axis. + /// the shear factor of the x-axis. public virtual double GetShearX() { return m01; } + /// Gets the shear factor of the y-axis. + /// the shear factor of the y-axis. public virtual double GetShearY() { return m10; } + /// Gets translation factor of the x-axis. + /// the translation factor of the x-axis. public virtual double GetTranslateX() { return m02; } + /// Gets translation factor of the y-axis. + /// the translation factor of the y-axis. public virtual double GetTranslateY() { return m12; } + /// + /// Gets whether this + /// + /// is an identity transformation. + /// + /// + /// + /// + /// if this + /// + /// is an identity transformation, + /// + /// otherwise. + /// public virtual bool IsIdentity() { return GetTransformType() == TYPE_IDENTITY; } + /// + /// Fills the matrix parameter with the values of this + /// + /// instance. + /// + /// + /// the array to be filled with the values of this + /// + /// instance. + /// public virtual void GetMatrix(float[] matrix) { matrix[0] = (float)m00; matrix[1] = (float)m10; @@ -314,6 +421,16 @@ public virtual void GetMatrix(float[] matrix) { } } + /// + /// Fills the matrix parameter with the values of this + /// + /// instance. + /// + /// + /// the array to be filled with the values of this + /// + /// instance. + /// public virtual void GetMatrix(double[] matrix) { matrix[0] = m00; matrix[1] = m10; @@ -325,10 +442,36 @@ public virtual void GetMatrix(double[] matrix) { } } + /// + /// Gets the determinant of the matrix representation of this + /// . + /// + /// + /// the determinant of the matrix representation of this + /// . + /// public virtual double GetDeterminant() { return m00 * m11 - m01 * m10; } + /// + /// Sets the values of this + /// + /// instance to the values provided. + /// + /// + /// Sets the values of this + /// + /// instance to the values provided. + /// The type of the transformation is set to + /// TYPE_UNKNOWN. + /// + /// The value of the first row and first column of the matrix. + /// The value of the second row and first column of the matrix. + /// The value of the first row and second column of the matrix. + /// The value of the second row and second column of the matrix. + /// The value of the first row and third column of the matrix. + /// The value of the second row and third column of the matrix. public virtual void SetTransform(float m00, float m10, float m01, float m11, float m02, float m12) { this.type = TYPE_UNKNOWN; this.m00 = m00; @@ -339,6 +482,24 @@ public virtual void SetTransform(float m00, float m10, float m01, float m11, flo this.m12 = m12; } + /// + /// Sets the values of this + /// + /// instance to the values provided. + /// + /// + /// Sets the values of this + /// + /// instance to the values provided. + /// The type of the transformation is set to + /// TYPE_UNKNOWN. + /// + /// The value of the first row and first column of the matrix. + /// The value of the second row and first column of the matrix. + /// The value of the first row and second column of the matrix. + /// The value of the second row and second column of the matrix. + /// The value of the first row and third column of the matrix. + /// The value of the second row and third column of the matrix. public virtual void SetTransform(double m00, double m10, double m01, double m11, double m02, double m12) { this.type = TYPE_UNKNOWN; this.m00 = m00; @@ -349,17 +510,39 @@ public virtual void SetTransform(double m00, double m10, double m01, double m11, this.m12 = m12; } + /// + /// Sets the values of this + /// + /// instance to the values provided. + /// + /// + /// The + /// + /// instance to be used. + /// public virtual void SetTransform(iText.Kernel.Geom.AffineTransform t) { type = t.type; SetTransform(t.m00, t.m10, t.m01, t.m11, t.m02, t.m12); } + /// + /// Sets this + /// + /// to the identity transformation. + /// public virtual void SetToIdentity() { type = TYPE_IDENTITY; m00 = m11 = 1; m10 = m01 = m02 = m12 = 0; } + /// + /// Sets this + /// + /// to represent a translation transformation. + /// + /// The value of the translation on the x-axis. + /// The value of the translation on the y-axis. public virtual void SetToTranslation(double mx, double my) { m00 = m11 = 1; m01 = m10 = 0; @@ -373,6 +556,13 @@ public virtual void SetToTranslation(double mx, double my) { } } + /// + /// Sets this + /// + /// to represent a scale transformation. + /// + /// The value of the scale factor on the x-axis. + /// The value of the scale factor on the y-axis. public virtual void SetToScale(double scx, double scy) { m00 = scx; m11 = scy; @@ -385,6 +575,13 @@ public virtual void SetToScale(double scx, double scy) { } } + /// + /// Sets this + /// + /// to represent a shear transformation. + /// + /// The value of the shear factor on the x-axis. + /// The value of the shear factor on the y-axis. public virtual void SetToShear(double shx, double shy) { m00 = m11 = 1; m02 = m12 = 0; @@ -434,18 +631,54 @@ public virtual void SetToRotation(double angle, double px, double py) { type = TYPE_UNKNOWN; } + /// + /// Get a new + /// + /// instance representing a translation over the passed values + /// + /// x-coordinate of translation + /// y-coordinate of translation + /// + /// + /// + /// representing the translation + /// public static iText.Kernel.Geom.AffineTransform GetTranslateInstance(double mx, double my) { iText.Kernel.Geom.AffineTransform t = new iText.Kernel.Geom.AffineTransform(); t.SetToTranslation(mx, my); return t; } + /// + /// Get a new + /// + /// instance representing a scale over the passed values + /// + /// scale factor on the x-axis + /// scale factor on the y-axis + /// + /// + /// + /// representing the scale + /// public static iText.Kernel.Geom.AffineTransform GetScaleInstance(double scx, double scY) { iText.Kernel.Geom.AffineTransform t = new iText.Kernel.Geom.AffineTransform(); t.SetToScale(scx, scY); return t; } + /// + /// Get a new + /// + /// instance representing a shear over the passed values + /// + /// shear factor on the x-axis + /// shear factor on the y-axis + /// + /// + /// + /// representing the shear + /// public static iText.Kernel.Geom.AffineTransform GetShearInstance(double shx, double shy) { iText.Kernel.Geom.AffineTransform m = new iText.Kernel.Geom.AffineTransform(); m.SetToShear(shx, shy); @@ -514,8 +747,8 @@ public virtual void Rotate(double angle, double px, double py) { //\cond DO_NOT_DOCUMENT /// Multiply matrix of two AffineTransform objects - /// - the AffineTransform object is a multiplicand - /// - the AffineTransform object is a multiplier + /// - the AffineTransform object is a multiplicand. + /// - the AffineTransform object is a multiplier. /// an AffineTransform object that is a result of t1 multiplied by matrix t2. internal virtual iText.Kernel.Geom.AffineTransform Multiply(iText.Kernel.Geom.AffineTransform t1, iText.Kernel.Geom.AffineTransform t2) { @@ -525,14 +758,32 @@ internal virtual iText.Kernel.Geom.AffineTransform Multiply(iText.Kernel.Geom.Af } //\endcond + /// Multiply matrix of two AffineTransform objects + /// - the AffineTransform object is a multiplier. public virtual void Concatenate(iText.Kernel.Geom.AffineTransform t) { SetTransform(Multiply(t, this)); } + /// Multiply matrix of two AffineTransform objects + /// - the AffineTransform object is a multiplicand. public virtual void PreConcatenate(iText.Kernel.Geom.AffineTransform t) { SetTransform(Multiply(this, t)); } + /// + /// Creates a new + /// + /// object that is invert of this + /// + /// object. + /// + /// + /// a new + /// + /// object that is invert of this + /// + /// object. + /// public virtual iText.Kernel.Geom.AffineTransform CreateInverse() { double det = GetDeterminant(); if (Math.Abs(det) < ZERO) { @@ -545,6 +796,14 @@ public virtual iText.Kernel.Geom.AffineTransform CreateInverse() { * m02) / det, (m10 * m02 - m00 * m12) / det); } + /// + /// Transform the point according to the values of this + /// + /// object. + /// + /// The point to be transformed. + /// The point that will hold the result of the transformation. + /// The point that holds the result of the transformation. public virtual Point Transform(Point src, Point dst) { if (dst == null) { dst = new Point(); @@ -555,6 +814,16 @@ public virtual Point Transform(Point src, Point dst) { return dst; } + /// + /// Transform the array of points according to the values of this + /// + /// object. + /// + /// The array of points to be transformed. + /// The offset of the first point in the array. + /// The array of points that will hold the result of the transformation. + /// The offset of the first point in the destination array. + /// The number of points to be transformed. public virtual void Transform(Point[] src, int srcOff, Point[] dst, int dstOff, int length) { while (--length >= 0) { Point srcPoint = src[srcOff++]; @@ -569,6 +838,16 @@ public virtual void Transform(Point[] src, int srcOff, Point[] dst, int dstOff, } } + /// + /// Transform the array of points according to the values of this + /// + /// object. + /// + /// The array of points to be transformed. + /// The offset of the first point in the array. + /// The array of points that will hold the result of the transformation. + /// The offset of the first point in the destination array. + /// The number of points to be transformed. public virtual void Transform(double[] src, int srcOff, double[] dst, int dstOff, int length) { int step = 2; if (src == dst && srcOff < dstOff && dstOff < srcOff + length * 2) { @@ -586,6 +865,16 @@ public virtual void Transform(double[] src, int srcOff, double[] dst, int dstOff } } + /// + /// Transform the array of points according to the values of this + /// + /// object. + /// + /// The array of points to be transformed. + /// The offset of the first point in the array. + /// The array of points that will hold the result of the transformation. + /// The offset of the first point in the destination array. + /// The number of points to be transformed. public virtual void Transform(float[] src, int srcOff, float[] dst, int dstOff, int length) { int step = 2; if (src == dst && srcOff < dstOff && dstOff < srcOff + length * 2) { @@ -603,6 +892,16 @@ public virtual void Transform(float[] src, int srcOff, float[] dst, int dstOff, } } + /// + /// Transform the array of points according to the values of this + /// + /// object. + /// + /// The array of points to be transformed. + /// The offset of the first point in the array. + /// The array of points that will hold the result of the transformation. + /// The offset of the first point in the destination array. + /// The number of points to be transformed. public virtual void Transform(float[] src, int srcOff, double[] dst, int dstOff, int length) { while (--length >= 0) { float x = src[srcOff++]; @@ -612,6 +911,16 @@ public virtual void Transform(float[] src, int srcOff, double[] dst, int dstOff, } } + /// + /// Transform the array of points according to the values of this + /// + /// object. + /// + /// The array of points to be transformed. + /// The offset of the first point in the array. + /// The array of points that will hold the result of the transformation. + /// The offset of the first point in the destination array. + /// The number of points to be transformed. public virtual void Transform(double[] src, int srcOff, float[] dst, int dstOff, int length) { while (--length >= 0) { double x = src[srcOff++]; @@ -621,6 +930,10 @@ public virtual void Transform(double[] src, int srcOff, float[] dst, int dstOff, } } + /// Performs the transformation on the source point and stores the result in the destination point. + /// The source point to be transformed. + /// The destination point that will hold the result of the transformation. + /// The modified destination point. public virtual Point DeltaTransform(Point src, Point dst) { if (dst == null) { dst = new Point(); @@ -631,6 +944,15 @@ public virtual Point DeltaTransform(Point src, Point dst) { return dst; } + /// + /// Performs the delta transformation on the source array of points and stores the result in + /// the destination array of points. + /// + /// The source array of data to be transformed. + /// The offset of the first point in the source array. + /// The destination array of data that will hold the result of the transformation. + /// The offset of the first point in the destination array. + /// The number of points to be transformed. public virtual void DeltaTransform(double[] src, int srcOff, double[] dst, int dstOff, int length) { while (--length >= 0) { double x = src[srcOff++]; @@ -640,6 +962,11 @@ public virtual void DeltaTransform(double[] src, int srcOff, double[] dst, int d } } + /// Performs the inverse transformation on the source point and stores the result in the destination point. + /// + /// The source point to be transformed. + /// The destination point that will hold the result of the transformation. + /// The modified destination point. public virtual Point InverseTransform(Point src, Point dst) { double det = GetDeterminant(); if (Math.Abs(det) < ZERO) { @@ -657,6 +984,15 @@ public virtual Point InverseTransform(Point src, Point dst) { return dst; } + /// + /// Performs the inverse transformation on the source array of points and stores the result + /// in the destination array of points. + /// + /// The source array of data to be transformed. + /// The offset of the first point in the source array. + /// The destination array of data that will hold the result of the transformation. + /// The offset of the first point in the destination array. + /// The number of points to be transformed. public virtual void InverseTransform(double[] src, int srcOff, double[] dst, int dstOff, int length) { double det = GetDeterminant(); if (Math.Abs(det) < ZERO) { @@ -673,6 +1009,15 @@ public virtual void InverseTransform(double[] src, int srcOff, double[] dst, int } } + /// + /// Performs the inverse transformation on the source array of points and stores the result + /// in the destination array of points. + /// + /// The source array of data to be transformed. + /// The offset of the first point in the source array. + /// The destination array of data that will hold the result of the transformation. + /// The offset of the first point in the destination array. + /// The number of points to be transformed. public virtual void InverseTransform(float[] src, int srcOff, float[] dst, int dstOff, int length) { float det = (float)GetDeterminant(); if (Math.Abs(det) < ZERO) { @@ -698,6 +1043,21 @@ public virtual iText.Kernel.Geom.AffineTransform Clone() { return (iText.Kernel.Geom.AffineTransform) MemberwiseClone(); } + /// Compares this AffineTransform with the specified Object. + /// + /// Compares this AffineTransform with the specified Object. + /// If the object is the same as this AffineTransform, this method returns true. + /// Otherwise, this method checks if the Object is an instance of AffineTransform and if the values of the two + /// AffineTransforms are equal. + /// + /// The object to compare this AffineTransform with. + /// + /// + /// + /// if the object is the same as this AffineTransform, + /// + /// otherwise. + /// public override bool Equals(Object o) { if (this == o) { return true; @@ -711,6 +1071,8 @@ public override bool Equals(Object o) { m02) == 0 && JavaUtil.DoubleCompare(that.m12, m12) == 0; } + /// Returns a hash code value for the object. + /// a hash code value for this object. public override int GetHashCode() { return JavaUtil.ArraysHashCode(m00, m10, m01, m11, m02, m12); } diff --git a/itext/itext.kernel/itext/kernel/geom/Point.cs b/itext/itext.kernel/itext/kernel/geom/Point.cs index 71e417f76f..0a73eb44bb 100644 --- a/itext/itext.kernel/itext/kernel/geom/Point.cs +++ b/itext/itext.kernel/itext/kernel/geom/Point.cs @@ -23,116 +23,116 @@ using iText.IO.Util; namespace iText.Kernel.Geom { + /// Class that represent point object with x and y coordinates. public class Point #if !NETSTANDARD2_0 : ICloneable #endif { - public double x; + private double x; - public double y; + private double y; + /// + /// Instantiates a new + /// + /// instance with 0 x and y. + /// public Point() { SetLocation(0, 0); } - public Point(int x, int y) { - SetLocation(x, y); - } - + /// + /// Instantiates a new + /// + /// instance based on passed x and y. + /// + /// the x coordinates of the point + /// the y coordinates of the point public Point(double x, double y) { SetLocation(x, y); } - public Point(iText.Kernel.Geom.Point p) { - SetLocation(p.x, p.y); - } - - public override bool Equals(Object obj) { - if (obj == this) { - return true; - } - if (obj is iText.Kernel.Geom.Point) { - iText.Kernel.Geom.Point p = (iText.Kernel.Geom.Point)obj; - return x == p.x && y == p.y; - } - return false; - } - - public override String ToString() { - //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - return MessageFormatUtil.Format("Point: [x={0},y={1}]", x, y); - } - + /// Gets x coordinate of the point. + /// the x coordinate public virtual double GetX() { return x; } + /// Gets y coordinate of the point. + /// the y coordinate public virtual double GetY() { return y; } + /// Gets location of point by creating a new copy. + /// the copy of this point public virtual iText.Kernel.Geom.Point GetLocation() { return new iText.Kernel.Geom.Point(x, y); } - public virtual void SetLocation(iText.Kernel.Geom.Point p) { - SetLocation(p.x, p.y); - } - - public virtual void SetLocation(int x, int y) { - SetLocation((double)x, (double)y); - } - + /// Sets x and y double coordinates of the point. + /// the x coordinate + /// the y coordinate public virtual void SetLocation(double x, double y) { this.x = x; this.y = y; } - public virtual void Move(double x, double y) { - SetLocation(x, y); - } - - public virtual void Translate(double dx, double dy) { + /// Moves the point by the specified offset. + /// the x-axis offset + /// the y-axis offset + public virtual void Move(double dx, double dy) { x += dx; y += dy; } - public override int GetHashCode() { - HashCode hash = new HashCode(); - hash.Append(GetX()); - hash.Append(GetY()); - return hash.GetHashCode(); - } - - public static double DistanceSq(double x1, double y1, double x2, double y2) { - x2 -= x1; - y2 -= y1; - return x2 * x2 + y2 * y2; - } - - public virtual double DistanceSq(double px, double py) { - return DistanceSq(GetX(), GetY(), px, py); + /// The distance between this point and the second point which is defined by passed x and y coordinates. + /// + /// the x coordinate of the second point + /// the y coordinate of the second point + /// the distance between points + public virtual double Distance(double px, double py) { + return Math.Sqrt(DistanceSq(GetX(), GetY(), px, py)); } - public virtual double DistanceSq(iText.Kernel.Geom.Point p) { - return DistanceSq(GetX(), GetY(), p.GetX(), p.GetY()); + /// The distance between this point and the second point. + /// the second point to calculate distance + /// the distance between points + public virtual double Distance(iText.Kernel.Geom.Point p) { + return Distance(p.GetX(), p.GetY()); } - public static double Distance(double x1, double y1, double x2, double y2) { - return Math.Sqrt(DistanceSq(x1, y1, x2, y2)); + public override bool Equals(Object obj) { + if (obj == this) { + return true; + } + if (obj is iText.Kernel.Geom.Point) { + iText.Kernel.Geom.Point p = (iText.Kernel.Geom.Point)obj; + return x == p.x && y == p.y; + } + return false; } - public virtual double Distance(double px, double py) { - return Math.Sqrt(DistanceSq(px, py)); + public override String ToString() { + return MessageFormatUtil.Format("Point: [x={0},y={1}]", x, y); } - public virtual double Distance(iText.Kernel.Geom.Point p) { - return Math.Sqrt(DistanceSq(p)); + public override int GetHashCode() { + HashCode hash = new HashCode(); + hash.Append(GetX()); + hash.Append(GetY()); + return hash.GetHashCode(); } public virtual Object Clone() { return new iText.Kernel.Geom.Point(x, y); } + + private static double DistanceSq(double x1, double y1, double x2, double y2) { + x2 -= x1; + y2 -= y1; + return x2 * x2 + y2 * y2; + } } } diff --git a/itext/itext.kernel/itext/kernel/logs/KernelLogMessageConstant.cs b/itext/itext.kernel/itext/kernel/logs/KernelLogMessageConstant.cs index 3ed81a33f3..b5f35fe1c1 100644 --- a/itext/itext.kernel/itext/kernel/logs/KernelLogMessageConstant.cs +++ b/itext/itext.kernel/itext/kernel/logs/KernelLogMessageConstant.cs @@ -90,6 +90,16 @@ public sealed class KernelLogMessageConstant { public const String XOBJECT_STRUCT_PARENT_INDEX_MISSED_AND_RECREATED = "XObject has no StructParents index in its stream, so index is recreated"; + //TODO DEVSIX-8490 remove this log message when implemented + public const String DUPLICATE_ENTRIES_IN_ORDER_ARRAY_REMOVED = "Duplicated entries in order array are " + + "removed"; + + public const String FINGERPRINT_DISABLED_BUT_NO_REQUIRED_LICENCE = "Fingerprint disabling is only " + "available in non AGPL mode. Fingerprint will be added at the end of the document."; + + public const String ALGORITHM_NOT_FROM_SPEC = "Requested algorithm might not be supported by the pdf specification."; + + public const String MEMORYLIMITAWAREHANDLER_OVERRIDE_CREATENEWINSTANCE_METHOD = "MemoryLimitsAwareHandler#createNewInstance method must be overriden."; + private KernelLogMessageConstant() { } //Private constructor will prevent the instantiation of this class directly diff --git a/itext/itext.kernel/itext/kernel/mac/AbstractMacIntegrityProtector.cs b/itext/itext.kernel/itext/kernel/mac/AbstractMacIntegrityProtector.cs new file mode 100644 index 0000000000..9159989953 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/mac/AbstractMacIntegrityProtector.cs @@ -0,0 +1,413 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using System.IO; +using iText.Bouncycastleconnector; +using iText.Commons.Bouncycastle; +using iText.Commons.Bouncycastle.Asn1; +using iText.Commons.Digest; +using iText.Commons.Utils; +using iText.IO.Source; +using iText.Kernel.Crypto; +using iText.Kernel.Exceptions; +using iText.Kernel.Pdf; + +namespace iText.Kernel.Mac { + /// Class responsible for integrity protection in encrypted documents, which uses MAC container. + public abstract class AbstractMacIntegrityProtector { + private static readonly IBouncyCastleFactory BC_FACTORY = BouncyCastleFactoryCreator.GetFactory(); + + private const String PDF_MAC = "PDFMAC"; + + protected internal readonly PdfDocument document; + + protected internal readonly MacProperties macProperties; + + protected internal byte[] kdfSalt = null; + + protected internal byte[] fileEncryptionKey = new byte[0]; + + private readonly MacContainerReader macContainerReader; + + /// + /// Creates + /// + /// instance from the provided + /// . + /// + /// + /// + /// + /// for which integrity protection is required + /// + /// + /// + /// + /// used to provide MAC algorithm properties + /// + protected internal AbstractMacIntegrityProtector(PdfDocument document, MacProperties macProperties) { + this.document = document; + this.macContainerReader = null; + this.macProperties = macProperties; + } + + /// + /// Creates + /// + /// instance from the Auth dictionary. + /// + /// + /// + /// + /// for which integrity protection is required + /// + /// + /// + /// + /// representing Auth dictionary in which MAC container is stored + /// + protected internal AbstractMacIntegrityProtector(PdfDocument document, PdfDictionary authDictionary) { + this.document = document; + this.macContainerReader = MacContainerReader.GetInstance(authDictionary); + this.macProperties = new MacProperties(GetMacDigestAlgorithm(macContainerReader.ParseDigestAlgorithm())); + } + + /// Sets file encryption key to be used during MAC calculation. + /// + /// + /// byte[] + /// file encryption key bytes + /// + public virtual void SetFileEncryptionKey(byte[] fileEncryptionKey) { + this.fileEncryptionKey = fileEncryptionKey; + } + + /// Gets KDF salt bytes, which are used during MAC key encryption. + /// + /// + /// byte[] + /// KDF salt bytes. + /// + public virtual byte[] GetKdfSalt() { + if (kdfSalt == null) { + kdfSalt = GenerateRandomBytes(32); + } + return JavaUtil.ArraysCopyOf(kdfSalt, kdfSalt.Length); + } + + /// Sets KDF salt bytes, to be used during MAC key encryption. + /// + /// + /// byte[] + /// KDF salt bytes. + /// + public virtual void SetKdfSalt(byte[] kdfSalt) { + this.kdfSalt = JavaUtil.ArraysCopyOf(kdfSalt, kdfSalt.Length); + } + + /// Validates MAC container integrity. + /// + /// Validates MAC container integrity. This method throws + /// + /// in case of any modifications, + /// introduced to the document in question, after MAC container is integrated. + /// + public virtual void ValidateMacToken() { + if (kdfSalt == null) { + throw new MacValidationException(KernelExceptionMessageConstant.MAC_VALIDATION_NO_SALT); + } + try { + byte[] macKey = GenerateDecryptedKey(macContainerReader.ParseMacKey()); + long[] byteRange = macContainerReader.GetByteRange(); + byte[] dataDigest; + IRandomAccessSource randomAccessSource = document.GetReader().GetSafeFile().CreateSourceView(); + using (Stream rg = new RASInputStream(new RandomAccessSourceFactory().CreateRanged(randomAccessSource, byteRange + ))) { + dataDigest = DigestBytes(rg); + } + byte[] expectedData = macContainerReader.ParseAuthAttributes().GetEncoded(); + byte[] expectedMac = GenerateMac(macKey, expectedData); + byte[] signatureDigest = DigestBytes(macContainerReader.GetSignature()); + byte[] expectedMessageDigest = CreateMessageDigestSequence(CreatePdfMacIntegrityInfo(dataDigest, signatureDigest + )).GetEncoded(); + byte[] actualMessageDigest = macContainerReader.ParseMessageDigest().GetEncoded(); + byte[] actualMac = macContainerReader.ParseMac(); + if (!JavaUtil.ArraysEquals(expectedMac, actualMac) || !JavaUtil.ArraysEquals(expectedMessageDigest, actualMessageDigest + )) { + throw new MacValidationException(KernelExceptionMessageConstant.MAC_VALIDATION_FAILED); + } + } + catch (PdfException e) { + throw; + } + catch (Exception e) { + throw new MacValidationException(KernelExceptionMessageConstant.MAC_VALIDATION_EXCEPTION, e); + } + } + + /// Digests provided bytes based on hash algorithm, specified for this class instance. + /// + /// + /// byte[] + /// to be digested + /// + /// digested bytes. + protected internal virtual byte[] DigestBytes(byte[] bytes) { + return bytes == null ? null : DigestBytes(new MemoryStream(bytes)); + } + + /// Digests provided input stream based on hash algorithm, specified for this class instance. + /// + /// + /// + /// to be digested + /// + /// digested bytes. + protected internal virtual byte[] DigestBytes(Stream inputStream) { + if (inputStream == null) { + return null; + } + String algorithm = MacProperties.MacDigestAlgorithmToString(macProperties.GetMacDigestAlgorithm()); + IMessageDigest digest = DigestAlgorithms.GetMessageDigest(algorithm); + byte[] buf = new byte[8192]; + int rd; + while ((rd = inputStream.JRead(buf, 0, buf.Length)) > 0) { + digest.Update(buf, 0, rd); + } + return digest.Digest(); + } + + /// Creates MAC container as ASN1 object based on data digest, MAC key and signature parameters. + /// + /// data digest as + /// byte[] + /// to be used during MAC container creation + /// + /// + /// MAC key as + /// byte[] + /// to be used during MAC container creation + /// + /// + /// signature value as + /// byte[] + /// to be used during MAC container creation + /// + /// + /// MAC container as + /// . + /// + protected internal virtual IDerSequence CreateMacContainer(byte[] dataDigest, byte[] macKey, byte[] signature + ) { + IAsn1EncodableVector contentInfoV = BC_FACTORY.CreateASN1EncodableVector(); + contentInfoV.Add(BC_FACTORY.CreateASN1ObjectIdentifier(OID.AUTHENTICATED_DATA)); + // Recipient info + IAsn1EncodableVector recInfoV = BC_FACTORY.CreateASN1EncodableVector(); + recInfoV.Add(BC_FACTORY.CreateASN1Integer(0)); + // version + recInfoV.Add(BC_FACTORY.CreateDERTaggedObject(0, BC_FACTORY.CreateASN1ObjectIdentifier(OID.KDF_PDF_MAC_WRAP_KDF + ))); + recInfoV.Add(BC_FACTORY.CreateDERSequence(BC_FACTORY.CreateASN1ObjectIdentifier(GetKeyWrappingAlgorithmOid + ()))); + ////////////////////// KEK + byte[] macKek = BC_FACTORY.GenerateHKDF(fileEncryptionKey, kdfSalt, PDF_MAC.GetBytes(System.Text.Encoding. + UTF8)); + byte[] encryptedKey = GenerateEncryptedKey(macKey, macKek); + recInfoV.Add(BC_FACTORY.CreateDEROctetString(encryptedKey)); + // Digest info + byte[] messageBytes = CreatePdfMacIntegrityInfo(dataDigest, signature == null ? null : DigestBytes(signature + )); + // Encapsulated content info + IAsn1EncodableVector encapContentInfoV = BC_FACTORY.CreateASN1EncodableVector(); + encapContentInfoV.Add(BC_FACTORY.CreateASN1ObjectIdentifier(OID.CT_PDF_MAC_INTEGRITY_INFO)); + encapContentInfoV.Add(BC_FACTORY.CreateDERTaggedObject(0, BC_FACTORY.CreateDEROctetString(messageBytes))); + IDerSet authAttrs = CreateAuthAttributes(messageBytes); + // Create mac + byte[] data = authAttrs.GetEncoded(); + byte[] mac = GenerateMac(macKey, data); + // Auth data + IAsn1EncodableVector authDataV = BC_FACTORY.CreateASN1EncodableVector(); + authDataV.Add(BC_FACTORY.CreateASN1Integer(0)); + // version + authDataV.Add(BC_FACTORY.CreateDERSet(BC_FACTORY.CreateDERTaggedObject(false, 3, BC_FACTORY.CreateDERSequence + (recInfoV)))); + authDataV.Add(BC_FACTORY.CreateDERSequence(BC_FACTORY.CreateASN1ObjectIdentifier(GetMacAlgorithmOid()))); + String algorithm = MacProperties.MacDigestAlgorithmToString(macProperties.GetMacDigestAlgorithm()); + String macDigestOid = DigestAlgorithms.GetAllowedDigest(algorithm); + authDataV.Add(BC_FACTORY.CreateDERTaggedObject(false, 1, BC_FACTORY.CreateDERSequence(BC_FACTORY.CreateASN1ObjectIdentifier + (macDigestOid)))); + authDataV.Add(BC_FACTORY.CreateDERSequence(encapContentInfoV)); + authDataV.Add(BC_FACTORY.CreateDERTaggedObject(false, 2, authAttrs)); + authDataV.Add(BC_FACTORY.CreateDEROctetString(mac)); + contentInfoV.Add(BC_FACTORY.CreateDERTaggedObject(0, BC_FACTORY.CreateDERSequence(authDataV))); + return BC_FACTORY.CreateDERSequence(contentInfoV); + } + + private byte[] GenerateMac(byte[] macKey, byte[] data) { + switch (macProperties.GetMacAlgorithm()) { + case MacProperties.MacAlgorithm.HMAC_WITH_SHA_256: { + return BC_FACTORY.GenerateHMACSHA256Token(macKey, data); + } + + default: { + throw new PdfException(KernelExceptionMessageConstant.MAC_ALGORITHM_NOT_SUPPORTED); + } + } + } + + private byte[] GenerateEncryptedKey(byte[] macKey, byte[] macKek) { + switch (macProperties.GetKeyWrappingAlgorithm()) { + case MacProperties.KeyWrappingAlgorithm.AES_256_NO_PADD: { + return BC_FACTORY.GenerateEncryptedKeyWithAES256NoPad(macKey, macKek); + } + + default: { + throw new PdfException(KernelExceptionMessageConstant.WRAP_ALGORITHM_NOT_SUPPORTED); + } + } + } + + private byte[] GenerateDecryptedKey(byte[] encryptedMacKey) { + byte[] macKek = BC_FACTORY.GenerateHKDF(fileEncryptionKey, kdfSalt, PDF_MAC.GetBytes(System.Text.Encoding. + UTF8)); + switch (macProperties.GetKeyWrappingAlgorithm()) { + case MacProperties.KeyWrappingAlgorithm.AES_256_NO_PADD: { + return BC_FACTORY.GenerateDecryptedKeyWithAES256NoPad(encryptedMacKey, macKek); + } + + default: { + throw new PdfException(KernelExceptionMessageConstant.WRAP_ALGORITHM_NOT_SUPPORTED); + } + } + } + + private String GetMacAlgorithmOid() { + switch (macProperties.GetMacAlgorithm()) { + case MacProperties.MacAlgorithm.HMAC_WITH_SHA_256: { + return "1.2.840.113549.2.9"; + } + + default: { + throw new PdfException(KernelExceptionMessageConstant.MAC_ALGORITHM_NOT_SUPPORTED); + } + } + } + + private String GetKeyWrappingAlgorithmOid() { + switch (macProperties.GetKeyWrappingAlgorithm()) { + case MacProperties.KeyWrappingAlgorithm.AES_256_NO_PADD: { + return "2.16.840.1.101.3.4.1.45"; + } + + default: { + throw new PdfException(KernelExceptionMessageConstant.WRAP_ALGORITHM_NOT_SUPPORTED); + } + } + } + + private IDerSequence CreateMessageDigestSequence(byte[] messageBytes) { + String algorithm = MacProperties.MacDigestAlgorithmToString(macProperties.GetMacDigestAlgorithm()); + // Hash messageBytes to get messageDigest attribute + IMessageDigest digest = DigestAlgorithms.GetMessageDigest(algorithm); + digest.Update(messageBytes); + byte[] messageDigest = DigestBytes(messageBytes); + // Message digest + IAsn1EncodableVector messageDigestV = BC_FACTORY.CreateASN1EncodableVector(); + messageDigestV.Add(BC_FACTORY.CreateASN1ObjectIdentifier(OID.MESSAGE_DIGEST)); + messageDigestV.Add(BC_FACTORY.CreateDERSet(BC_FACTORY.CreateDEROctetString(messageDigest))); + return BC_FACTORY.CreateDERSequence(messageDigestV); + } + + private IDerSet CreateAuthAttributes(byte[] messageBytes) { + // Content type - mac integrity info + IAsn1EncodableVector contentTypeInfoV = BC_FACTORY.CreateASN1EncodableVector(); + contentTypeInfoV.Add(BC_FACTORY.CreateASN1ObjectIdentifier(OID.CONTENT_TYPE)); + contentTypeInfoV.Add(BC_FACTORY.CreateDERSet(BC_FACTORY.CreateASN1ObjectIdentifier(OID.CT_PDF_MAC_INTEGRITY_INFO + ))); + IAsn1EncodableVector algorithmsInfoV = BC_FACTORY.CreateASN1EncodableVector(); + String algorithm = MacProperties.MacDigestAlgorithmToString(macProperties.GetMacDigestAlgorithm()); + String macDigestOid = DigestAlgorithms.GetAllowedDigest(algorithm); + algorithmsInfoV.Add(BC_FACTORY.CreateDERSequence(BC_FACTORY.CreateASN1ObjectIdentifier(macDigestOid))); + algorithmsInfoV.Add(BC_FACTORY.CreateDERTaggedObject(2, BC_FACTORY.CreateASN1ObjectIdentifier(GetMacAlgorithmOid + ()))); + // CMS algorithm protection + IAsn1EncodableVector algoProtectionInfoV = BC_FACTORY.CreateASN1EncodableVector(); + algoProtectionInfoV.Add(BC_FACTORY.CreateASN1ObjectIdentifier(OID.CMS_ALGORITHM_PROTECTION)); + algoProtectionInfoV.Add(BC_FACTORY.CreateDERSet(BC_FACTORY.CreateDERSequence(algorithmsInfoV))); + IAsn1EncodableVector authAttrsV = BC_FACTORY.CreateASN1EncodableVector(); + authAttrsV.Add(BC_FACTORY.CreateDERSequence(contentTypeInfoV)); + authAttrsV.Add(BC_FACTORY.CreateDERSequence(algoProtectionInfoV)); + authAttrsV.Add(CreateMessageDigestSequence(messageBytes)); + return BC_FACTORY.CreateDERSet(authAttrsV); + } + + private static byte[] CreatePdfMacIntegrityInfo(byte[] dataDigest, byte[] signatureDigest) { + IAsn1EncodableVector digestInfoV = BC_FACTORY.CreateASN1EncodableVector(); + digestInfoV.Add(BC_FACTORY.CreateASN1Integer(0)); + digestInfoV.Add(BC_FACTORY.CreateDEROctetString(dataDigest)); + if (signatureDigest != null) { + digestInfoV.Add(BC_FACTORY.CreateDERTaggedObject(false, 0, BC_FACTORY.CreateDEROctetString(signatureDigest + ))); + } + return BC_FACTORY.CreateDERSequence(digestInfoV).GetEncoded(); + } + + protected internal static byte[] GenerateRandomBytes(int length) { + byte[] randomBytes = new byte[length]; + BC_FACTORY.GetSecureRandom().GetBytes(randomBytes); + return randomBytes; + } + + private static MacProperties.MacDigestAlgorithm GetMacDigestAlgorithm(String oid) { + switch (oid) { + case OID.SHA_256: { + return MacProperties.MacDigestAlgorithm.SHA_256; + } + + case OID.SHA_384: { + return MacProperties.MacDigestAlgorithm.SHA_384; + } + + case OID.SHA_512: { + return MacProperties.MacDigestAlgorithm.SHA_512; + } + + case OID.SHA3_256: { + return MacProperties.MacDigestAlgorithm.SHA3_256; + } + + case OID.SHA3_384: { + return MacProperties.MacDigestAlgorithm.SHA3_384; + } + + case OID.SHA3_512: { + return MacProperties.MacDigestAlgorithm.SHA3_512; + } + + default: { + throw new PdfException(KernelExceptionMessageConstant.DIGEST_NOT_SUPPORTED); + } + } + } + } +} diff --git a/itext/itext.kernel/itext/kernel/mac/IMacContainerLocator.cs b/itext/itext.kernel/itext/kernel/mac/IMacContainerLocator.cs new file mode 100644 index 0000000000..d739dad5f3 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/mac/IMacContainerLocator.cs @@ -0,0 +1,115 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Pdf; + +namespace iText.Kernel.Mac { + /// + /// Strategy interface, which is responsible for + /// + /// container location. + /// + /// + /// Strategy interface, which is responsible for + /// + /// container location. + /// Expected to be used in + /// . + /// + public interface IMacContainerLocator { + /// + /// Locates + /// + /// container. + /// + /// + /// + /// + /// container to be located + /// + void LocateMacContainer(AbstractMacIntegrityProtector macIntegrityProtector); + + /// Indicates, if MAC container was already located. + /// + /// + /// + /// if MAC container was already located, + /// + /// otherwise + /// + bool IsMacContainerLocated(); + + /// + /// Creates + /// + /// from explicitly provided MAC properties. + /// + /// + /// + /// + /// for which MAC container shall be created + /// + /// + /// + /// + /// to be used for MAC container creation + /// + /// + /// + /// + /// which specific implementation depends on interface implementation. + /// + AbstractMacIntegrityProtector CreateMacIntegrityProtector(PdfDocument document, MacProperties macProperties + ); + + /// + /// Creates + /// + /// from already existing AuthCode dictionary. + /// + /// + /// + /// + /// for which MAC container shall be created + /// + /// + /// AuthCode + /// + /// which contains MAC related information + /// + /// + /// + /// + /// which specific implementation depends on interface implementation. + /// + AbstractMacIntegrityProtector CreateMacIntegrityProtector(PdfDocument document, PdfDictionary authDictionary + ); + + /// Handles MAC validation error. + /// + /// + /// + /// to handle. + /// + void HandleMacValidationError(MacValidationException exception); + } +} diff --git a/itext/itext.kernel/itext/kernel/mac/MacContainerReader.cs b/itext/itext.kernel/itext/kernel/mac/MacContainerReader.cs new file mode 100644 index 0000000000..ae5cad8a2f --- /dev/null +++ b/itext/itext.kernel/itext/kernel/mac/MacContainerReader.cs @@ -0,0 +1,152 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using System.IO; +using iText.Bouncycastleconnector; +using iText.Commons.Bouncycastle; +using iText.Commons.Bouncycastle.Asn1; +using iText.Kernel.Exceptions; +using iText.Kernel.Pdf; + +namespace iText.Kernel.Mac { +//\cond DO_NOT_DOCUMENT + internal abstract class MacContainerReader { + private static readonly IBouncyCastleFactory BC_FACTORY = BouncyCastleFactoryCreator.GetFactory(); + + private readonly byte[] macContainer; + + private readonly long[] byteRange; + + private readonly byte[] signature; + +//\cond DO_NOT_DOCUMENT + internal MacContainerReader(PdfDictionary authDictionary) { + this.macContainer = ParseMacContainer(authDictionary); + this.byteRange = ParseByteRange(authDictionary); + this.signature = ParseSignature(authDictionary); + } +//\endcond + +//\cond DO_NOT_DOCUMENT + internal static iText.Kernel.Mac.MacContainerReader GetInstance(PdfDictionary authDictionary) { + PdfName macLocation = authDictionary.GetAsName(PdfName.MACLocation); + if (PdfName.Standalone.Equals(macLocation)) { + return new MacStandaloneContainerReader(authDictionary); + } + else { + if (PdfName.AttachedToSig.Equals(macLocation)) { + return new MacSignatureContainerReader(authDictionary); + } + } + throw new PdfException(KernelExceptionMessageConstant.MAC_LOCATION_NOT_SPECIFIED); + } +//\endcond + +//\cond DO_NOT_DOCUMENT + internal abstract byte[] ParseSignature(PdfDictionary authDictionary); +//\endcond + +//\cond DO_NOT_DOCUMENT + internal abstract long[] ParseByteRange(PdfDictionary authDictionary); +//\endcond + +//\cond DO_NOT_DOCUMENT + internal abstract byte[] ParseMacContainer(PdfDictionary authDictionary); +//\endcond + +//\cond DO_NOT_DOCUMENT + internal virtual long[] GetByteRange() { + return byteRange; + } +//\endcond + +//\cond DO_NOT_DOCUMENT + internal virtual byte[] GetSignature() { + return signature; + } +//\endcond + +//\cond DO_NOT_DOCUMENT + internal virtual byte[] ParseMac() { + IAsn1Sequence authDataSequence = GetAuthDataSequence(); + return BC_FACTORY.CreateASN1OctetString(authDataSequence.GetObjectAt(6)).GetOctets(); + } +//\endcond + +//\cond DO_NOT_DOCUMENT + internal virtual IAsn1Set ParseAuthAttributes() { + IAsn1Sequence authDataSequence = GetAuthDataSequence(); + return BC_FACTORY.CreateASN1Set(BC_FACTORY.CreateASN1TaggedObject(authDataSequence.GetObjectAt(5)), false); + } +//\endcond + +//\cond DO_NOT_DOCUMENT + internal virtual IAsn1Sequence ParseMessageDigest() { + IAsn1Set authAttributes = ParseAuthAttributes(); + return BC_FACTORY.CreateASN1Sequence(authAttributes.GetObjectAt(2)); + } +//\endcond + +//\cond DO_NOT_DOCUMENT + internal virtual byte[] ParseMacKey() { + IAsn1Sequence authDataSequence = GetAuthDataSequence(); + IAsn1Sequence recInfo = BC_FACTORY.CreateASN1Sequence(BC_FACTORY.CreateASN1TaggedObject(BC_FACTORY.CreateASN1Set + (authDataSequence.GetObjectAt(1)).GetObjectAt(0)).GetObject()); + IAsn1OctetString encryptedKey = BC_FACTORY.CreateASN1OctetString(recInfo.GetObjectAt(3)); + return encryptedKey.GetOctets(); + } +//\endcond + +//\cond DO_NOT_DOCUMENT + internal virtual String ParseDigestAlgorithm() { + IAsn1Sequence authDataSequence = GetAuthDataSequence(); + IAsn1Object digestAlgorithmContainer = BC_FACTORY.CreateASN1TaggedObject(authDataSequence.GetObjectAt(3)). + GetObject(); + IDerObjectIdentifier digestAlgorithm; + if (BC_FACTORY.CreateASN1ObjectIdentifier(digestAlgorithmContainer) != null) { + digestAlgorithm = BC_FACTORY.CreateASN1ObjectIdentifier(digestAlgorithmContainer); + } + else { + digestAlgorithm = BC_FACTORY.CreateASN1ObjectIdentifier(BC_FACTORY.CreateASN1Sequence(digestAlgorithmContainer + ).GetObjectAt(0)); + } + return digestAlgorithm.GetId(); + } +//\endcond + + private IAsn1Sequence GetAuthDataSequence() { + IAsn1Sequence contentInfoSequence; + try { + using (IAsn1InputStream din = BC_FACTORY.CreateASN1InputStream(new MemoryStream(macContainer))) { + contentInfoSequence = BC_FACTORY.CreateASN1Sequence(din.ReadObject()); + } + } + catch (System.IO.IOException e) { + throw new PdfException(KernelExceptionMessageConstant.CONTAINER_PARSING_EXCEPTION, e); + } + return BC_FACTORY.CreateASN1Sequence(BC_FACTORY.CreateASN1TaggedObject(contentInfoSequence.GetObjectAt(1)) + .GetObject()); + } + } +//\endcond +} diff --git a/itext/itext.kernel/itext/kernel/mac/MacPdfObject.cs b/itext/itext.kernel/itext/kernel/mac/MacPdfObject.cs new file mode 100644 index 0000000000..4982fd4031 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/mac/MacPdfObject.cs @@ -0,0 +1,70 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Pdf; + +namespace iText.Kernel.Mac { +//\cond DO_NOT_DOCUMENT + internal class MacPdfObject : PdfObjectWrapper { +//\cond DO_NOT_DOCUMENT + internal MacPdfObject(int macContainerSize) + : base(new PdfDictionary()) { + PdfLiteral macPlaceholder = new PdfLiteral(macContainerSize); + PdfLiteral byteRangePlaceholder = new PdfLiteral(80); + GetPdfObject().Put(PdfName.MACLocation, PdfName.Standalone); + GetPdfObject().Put(PdfName.MAC, macPlaceholder); + GetPdfObject().Put(PdfName.ByteRange, byteRangePlaceholder); + } +//\endcond + +//\cond DO_NOT_DOCUMENT + internal virtual long[] ComputeByteRange(long totalLength) { + PdfLiteral macPlaceholder = GetMacPlaceholder(); + long macStart = macPlaceholder.GetPosition(); + long macLength = macPlaceholder.GetBytesCount(); + long macEnd = macStart + macLength; + return new long[] { 0, macStart, macEnd, totalLength - macEnd }; + } +//\endcond + +//\cond DO_NOT_DOCUMENT + internal virtual long GetByteRangePosition() { + return GetByteRangePlaceholder().GetPosition(); + } +//\endcond + + private PdfLiteral GetMacPlaceholder() { + PdfObject mac = GetPdfObject().Get(PdfName.MAC); + return (PdfLiteral)mac; + } + + private PdfLiteral GetByteRangePlaceholder() { + PdfObject br = GetPdfObject().Get(PdfName.ByteRange); + return (PdfLiteral)br; + } + + protected internal override bool IsWrappedObjectMustBeIndirect() { + return false; + } + } +//\endcond +} diff --git a/itext/itext.kernel/itext/kernel/mac/MacProperties.cs b/itext/itext.kernel/itext/kernel/mac/MacProperties.cs new file mode 100644 index 0000000000..c59a6fb59c --- /dev/null +++ b/itext/itext.kernel/itext/kernel/mac/MacProperties.cs @@ -0,0 +1,177 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; + +namespace iText.Kernel.Mac { + /// Class which contains configurable properties for MAC integrity protection mechanism. + public class MacProperties { + private readonly MacProperties.MacDigestAlgorithm macDigestAlgorithm; + + private readonly MacProperties.MacAlgorithm macAlgorithm; + + private readonly MacProperties.KeyWrappingAlgorithm keyWrappingAlgorithm; + + /// + /// Creates + /// + /// class containing provided + /// . + /// + /// + /// Creates + /// + /// class containing provided + /// . + /// For other properties default values are used. + /// + /// + /// + /// + /// to be used in MAC integrity protection algorithm + /// + public MacProperties(MacProperties.MacDigestAlgorithm macDigestAlgorithm) + : this(macDigestAlgorithm, MacProperties.MacAlgorithm.HMAC_WITH_SHA_256, MacProperties.KeyWrappingAlgorithm + .AES_256_NO_PADD) { + } + + /// + /// Creates + /// + /// class containing provided properties. + /// + /// + /// + /// + /// to be used in MAC integrity protection algorithm + /// + /// + /// + /// + /// to be used in MAC integrity protection algorithm + /// + /// + /// + /// + /// to be used in MAC integrity protection algorithm + /// + public MacProperties(MacProperties.MacDigestAlgorithm macDigestAlgorithm, MacProperties.MacAlgorithm macAlgorithm + , MacProperties.KeyWrappingAlgorithm keyWrappingAlgorithm) { + this.macDigestAlgorithm = macDigestAlgorithm; + this.macAlgorithm = macAlgorithm; + this.keyWrappingAlgorithm = keyWrappingAlgorithm; + } + + /// + /// Gets + /// + /// to be used in MAC integrity protection algorithm. + /// + /// + /// + /// + /// to be used in MAC integrity protection algorithm + /// + public virtual MacProperties.MacDigestAlgorithm GetMacDigestAlgorithm() { + return macDigestAlgorithm; + } + + /// + /// Gets + /// + /// to be used in MAC integrity protection algorithm. + /// + /// + /// + /// + /// to be used in MAC integrity protection algorithm + /// + public virtual MacProperties.MacAlgorithm GetMacAlgorithm() { + return macAlgorithm; + } + + /// + /// Gets + /// + /// to be used in MAC integrity protection algorithm. + /// + /// + /// + /// + /// to be used in MAC integrity protection algorithm + /// + public virtual MacProperties.KeyWrappingAlgorithm GetKeyWrappingAlgorithm() { + return keyWrappingAlgorithm; + } + + /// Message digest algorithms, which can be used in MAC integrity protection algorithm. + public enum MacDigestAlgorithm { + SHA_256, + SHA_384, + SHA_512, + SHA3_256, + SHA3_384, + SHA3_512 + } + + // We can't use here enum with fields, because .NET doesn't support it, and enum + // will be ported to class, and EnumUtil.getAllValuesOfEnum won't work with class + public static String MacDigestAlgorithmToString(MacProperties.MacDigestAlgorithm macDigestAlgorithm) { + switch (macDigestAlgorithm) { + case MacProperties.MacDigestAlgorithm.SHA_256: { + return "SHA256"; + } + + case MacProperties.MacDigestAlgorithm.SHA_384: { + return "SHA384"; + } + + case MacProperties.MacDigestAlgorithm.SHA_512: { + return "SHA512"; + } + + case MacProperties.MacDigestAlgorithm.SHA3_256: { + return "SHA3-256"; + } + + case MacProperties.MacDigestAlgorithm.SHA3_384: { + return "SHA3-384"; + } + + case MacProperties.MacDigestAlgorithm.SHA3_512: { + return "SHA3-512"; + } + } + return null; + } + + /// MAC algorithms, which can be used during integrity protection operation. + public enum MacAlgorithm { + HMAC_WITH_SHA_256 + } + + /// Key wrapping algorithms, which can be used in MAC integrity protection algorithm. + public enum KeyWrappingAlgorithm { + AES_256_NO_PADD + } + } +} diff --git a/itext/itext.kernel/itext/kernel/mac/MacSignatureContainerReader.cs b/itext/itext.kernel/itext/kernel/mac/MacSignatureContainerReader.cs new file mode 100644 index 0000000000..c2cd9e9dd4 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/mac/MacSignatureContainerReader.cs @@ -0,0 +1,139 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using System.IO; +using iText.Bouncycastleconnector; +using iText.Commons.Bouncycastle; +using iText.Commons.Bouncycastle.Asn1; +using iText.Kernel.Exceptions; +using iText.Kernel.Pdf; + +namespace iText.Kernel.Mac { +//\cond DO_NOT_DOCUMENT + internal class MacSignatureContainerReader : MacContainerReader { + private static readonly IBouncyCastleFactory BC_FACTORY = BouncyCastleFactoryCreator.GetFactory(); + + private const String ID_ATTR_PDF_MAC_DATA = "1.0.32004.1.2"; + +//\cond DO_NOT_DOCUMENT + internal MacSignatureContainerReader(PdfDictionary authDictionary) + : base(authDictionary) { + } +//\endcond + +//\cond DO_NOT_DOCUMENT + internal override byte[] ParseSignature(PdfDictionary authDictionary) { + PdfDictionary signatureDictionary = GetSignatureDictionary(authDictionary); + PdfString contentsString = signatureDictionary.GetAsString(PdfName.Contents); + contentsString.MarkAsUnencryptedObject(); + return ParseSignatureValueFromSignatureContainer(contentsString.GetValueBytes()); + } +//\endcond + +//\cond DO_NOT_DOCUMENT + internal override long[] ParseByteRange(PdfDictionary authDictionary) { + PdfDictionary signatureDictionary = GetSignatureDictionary(authDictionary); + return signatureDictionary.GetAsArray(PdfName.ByteRange).ToLongArray(); + } +//\endcond + +//\cond DO_NOT_DOCUMENT + internal override byte[] ParseMacContainer(PdfDictionary authDictionary) { + PdfDictionary signatureDictionary = GetSignatureDictionary(authDictionary); + PdfString contentsString = signatureDictionary.GetAsString(PdfName.Contents); + contentsString.MarkAsUnencryptedObject(); + return ParseMacContainerFromSignatureContainer(contentsString.GetValueBytes()); + } +//\endcond + + private static byte[] ParseSignatureValueFromSignatureContainer(byte[] signature) { + try { + IAsn1Sequence signerInfoSeq = ParseSignerInfoSequence(signature); + int signatureValueIndex = 3; + IAsn1TaggedObject taggedSignedAttributes = BC_FACTORY.CreateASN1TaggedObject(signerInfoSeq.GetObjectAt(signatureValueIndex + )); + if (taggedSignedAttributes != null) { + ++signatureValueIndex; + } + IDerOctetString signatureDataOS = BC_FACTORY.CreateDEROctetString(signerInfoSeq.GetObjectAt(++signatureValueIndex + )); + return signatureDataOS.GetOctets(); + } + catch (Exception e) { + throw new PdfException(KernelExceptionMessageConstant.MAC_EXTRACTION_EXCEPTION, e); + } + } + + private static byte[] ParseMacContainerFromSignatureContainer(byte[] signature) { + try { + IAsn1Sequence signerInfoSeq = ParseSignerInfoSequence(signature); + int unsignedAttributesIndex = 3; + IAsn1TaggedObject taggedSignedAttributes = BC_FACTORY.CreateASN1TaggedObject(signerInfoSeq.GetObjectAt(unsignedAttributesIndex + )); + if (taggedSignedAttributes != null) { + ++unsignedAttributesIndex; + } + unsignedAttributesIndex += 2; + if (signerInfoSeq.Size() > unsignedAttributesIndex) { + IAsn1Set unsignedAttributes = BC_FACTORY.CreateASN1Set(BC_FACTORY.CreateASN1TaggedObject(signerInfoSeq.GetObjectAt + (unsignedAttributesIndex)), false); + for (int i = 0; i < unsignedAttributes.Size(); i++) { + IAsn1Sequence attrSeq = BC_FACTORY.CreateASN1Sequence(unsignedAttributes.GetObjectAt(i)); + IDerObjectIdentifier attrType = BC_FACTORY.CreateASN1ObjectIdentifier(attrSeq.GetObjectAt(0)); + if (ID_ATTR_PDF_MAC_DATA.Equals(attrType.GetId())) { + IAsn1Set macSet = BC_FACTORY.CreateASN1Set(attrSeq.GetObjectAt(1)); + return macSet.GetObjectAt(0).ToASN1Primitive().GetEncoded(); + } + } + } + } + catch (Exception e) { + throw new PdfException(KernelExceptionMessageConstant.MAC_EXTRACTION_EXCEPTION, e); + } + throw new PdfException(KernelExceptionMessageConstant.MAC_ATTRIBUTE_NOT_SPECIFIED); + } + + private static PdfDictionary GetSignatureDictionary(PdfDictionary authDictionary) { + if (authDictionary.GetAsDictionary(PdfName.SigObjRef) == null) { + throw new PdfException(KernelExceptionMessageConstant.SIG_OBJ_REF_NOT_SPECIFIED); + } + return authDictionary.GetAsDictionary(PdfName.SigObjRef); + } + + private static IAsn1Sequence ParseSignerInfoSequence(byte[] signature) { + using (IAsn1InputStream @is = BC_FACTORY.CreateASN1InputStream(new MemoryStream(signature))) { + IAsn1Sequence contentInfo = BC_FACTORY.CreateASN1Sequence(@is.ReadObject()); + IAsn1Sequence signedData = BC_FACTORY.CreateASN1Sequence(BC_FACTORY.CreateASN1TaggedObject(contentInfo.GetObjectAt + (1)).GetObject()); + int signerInfoIndex = 4; + IAsn1TaggedObject taggedObj = BC_FACTORY.CreateASN1TaggedObject(signedData.GetObjectAt(signerInfoIndex)); + if (taggedObj != null) { + ++signerInfoIndex; + } + return BC_FACTORY.CreateASN1Sequence(BC_FACTORY.CreateASN1Set(signedData.GetObjectAt(signerInfoIndex)).GetObjectAt + (0)); + } + } + } +//\endcond +} diff --git a/itext/itext.kernel/itext/kernel/mac/MacStandaloneContainerReader.cs b/itext/itext.kernel/itext/kernel/mac/MacStandaloneContainerReader.cs new file mode 100644 index 0000000000..eb419635eb --- /dev/null +++ b/itext/itext.kernel/itext/kernel/mac/MacStandaloneContainerReader.cs @@ -0,0 +1,57 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Exceptions; +using iText.Kernel.Pdf; + +namespace iText.Kernel.Mac { +//\cond DO_NOT_DOCUMENT + internal class MacStandaloneContainerReader : MacContainerReader { +//\cond DO_NOT_DOCUMENT + internal MacStandaloneContainerReader(PdfDictionary authDictionary) + : base(authDictionary) { + } +//\endcond + +//\cond DO_NOT_DOCUMENT + internal override byte[] ParseSignature(PdfDictionary authDictionary) { + return null; + } +//\endcond + +//\cond DO_NOT_DOCUMENT + internal override long[] ParseByteRange(PdfDictionary authDictionary) { + return authDictionary.GetAsArray(PdfName.ByteRange).ToLongArray(); + } +//\endcond + +//\cond DO_NOT_DOCUMENT + internal override byte[] ParseMacContainer(PdfDictionary authDictionary) { + if (authDictionary.GetAsString(PdfName.MAC) == null) { + throw new PdfException(KernelExceptionMessageConstant.MAC_NOT_SPECIFIED); + } + return authDictionary.GetAsString(PdfName.MAC).GetValueBytes(); + } +//\endcond + } +//\endcond +} diff --git a/itext/itext.kernel/itext/kernel/mac/MacValidationException.cs b/itext/itext.kernel/itext/kernel/mac/MacValidationException.cs new file mode 100644 index 0000000000..16c3126e0d --- /dev/null +++ b/itext/itext.kernel/itext/kernel/mac/MacValidationException.cs @@ -0,0 +1,52 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using iText.Kernel.Exceptions; + +namespace iText.Kernel.Mac { + /// Exception class for MAC validation errors. + public class MacValidationException : PdfException { + /// + /// Creates a new instance of + /// . + /// + /// the exception message + public MacValidationException(String message) + : base(message) { + } + + /// + /// Creates a new instance of + /// . + /// + /// the exception message + /// + /// the cause (which is saved for later retrieval by + /// + /// method) + /// + public MacValidationException(String message, Exception cause) + : base(message, cause) { + } + } +} diff --git a/itext/itext.kernel/itext/kernel/mac/StandaloneMacContainerLocator.cs b/itext/itext.kernel/itext/kernel/mac/StandaloneMacContainerLocator.cs new file mode 100644 index 0000000000..38e49f7bfc --- /dev/null +++ b/itext/itext.kernel/itext/kernel/mac/StandaloneMacContainerLocator.cs @@ -0,0 +1,70 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Pdf; + +namespace iText.Kernel.Mac { + /// + /// Default + /// + /// location strategy, which locates MAC container in document's trailer. + /// + public class StandaloneMacContainerLocator : IMacContainerLocator { + private bool macContainerLocated = false; + + /// + /// . + /// + public virtual void LocateMacContainer(AbstractMacIntegrityProtector macIntegrityProtector) { + ((StandaloneMacIntegrityProtector)macIntegrityProtector).PrepareDocument(); + macContainerLocated = true; + } + + /// + /// . + /// + public virtual bool IsMacContainerLocated() { + return macContainerLocated; + } + + /// + /// . + /// + public virtual AbstractMacIntegrityProtector CreateMacIntegrityProtector(PdfDocument document, MacProperties + macProperties) { + return new StandaloneMacIntegrityProtector(document, macProperties); + } + + /// + /// . + /// + public virtual AbstractMacIntegrityProtector CreateMacIntegrityProtector(PdfDocument document, PdfDictionary + authDictionary) { + return new StandaloneMacIntegrityProtector(document, authDictionary); + } + + /// + public virtual void HandleMacValidationError(MacValidationException exception) { + throw exception; + } + } +} diff --git a/itext/itext.kernel/itext/kernel/mac/StandaloneMacIntegrityProtector.cs b/itext/itext.kernel/itext/kernel/mac/StandaloneMacIntegrityProtector.cs new file mode 100644 index 0000000000..8b46685873 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/mac/StandaloneMacIntegrityProtector.cs @@ -0,0 +1,142 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using System.IO; +using iText.Commons.Bouncycastle.Security; +using iText.IO.Source; +using iText.Kernel.Exceptions; +using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Event; + +namespace iText.Kernel.Mac { +//\cond DO_NOT_DOCUMENT + /// Class responsible for integrity protection in encrypted documents, which uses MAC container in the standalone mode. + /// + internal class StandaloneMacIntegrityProtector : AbstractMacIntegrityProtector { + private MacPdfObject macPdfObject; + +//\cond DO_NOT_DOCUMENT + internal StandaloneMacIntegrityProtector(PdfDocument document, MacProperties macProperties) + : base(document, macProperties) { + } +//\endcond + +//\cond DO_NOT_DOCUMENT + internal StandaloneMacIntegrityProtector(PdfDocument document, PdfDictionary authDictionary) + : base(document, authDictionary) { + } +//\endcond + +//\cond DO_NOT_DOCUMENT + internal virtual void PrepareDocument() { + document.AddEventHandler(PdfDocumentEvent.START_DOCUMENT_CLOSING, new StandaloneMacIntegrityProtector.StandaloneMacPdfObjectAdder + (this)); + document.AddEventHandler(PdfDocumentEvent.START_WRITER_CLOSING, new StandaloneMacIntegrityProtector.StandaloneMacContainerEmbedder + (this)); + } +//\endcond + + private void EmbedMacContainerInTrailer() { + byte[] documentBytes = GetDocumentByteArrayOutputStream().ToArray(); + long[] byteRange = macPdfObject.ComputeByteRange(documentBytes.Length); + long byteRangePosition = macPdfObject.GetByteRangePosition(); + MemoryStream localBaos = new MemoryStream(); + PdfOutputStream os = new PdfOutputStream(localBaos); + os.Write('['); + foreach (long l in byteRange) { + os.WriteLong(l).Write(' '); + } + os.Write(']'); + Array.Copy(localBaos.ToArray(), 0, documentBytes, (int)byteRangePosition, localBaos.Length); + byte[] mac = CreateDocumentDigestAndMacContainer(documentBytes, byteRange); + PdfString macString = new PdfString(mac).SetHexWriting(true); + // fill in the MAC + localBaos.JReset(); + os.Write(macString); + Array.Copy(localBaos.ToArray(), 0, documentBytes, (int)byteRange[1], localBaos.Length); + GetDocumentByteArrayOutputStream().JReset(); + document.GetWriter().GetOutputStream().Write(documentBytes, 0, documentBytes.Length); + } + + private byte[] CreateDocumentDigestAndMacContainer(byte[] documentBytes, long[] byteRange) { + IRandomAccessSource ras = new RandomAccessSourceFactory().CreateSource(documentBytes); + try { + using (Stream rg = new RASInputStream(new RandomAccessSourceFactory().CreateRanged(ras, byteRange))) { + byte[] dataDigest = DigestBytes(rg); + return CreateMacContainer(dataDigest, GenerateRandomBytes(32), null).GetEncoded(); + } + } + catch (AbstractGeneralSecurityException e) { + throw new PdfException(KernelExceptionMessageConstant.CONTAINER_GENERATION_EXCEPTION, e); + } + } + + private int GetContainerSizeEstimate() { + try { + return CreateMacContainer(DigestBytes(new byte[0]), GenerateRandomBytes(32), null).GetEncoded().Length * 2 + + 2; + } + catch (AbstractGeneralSecurityException e) { + throw new PdfException(KernelExceptionMessageConstant.CONTAINER_GENERATION_EXCEPTION, e); + } + catch (System.IO.IOException e) { + throw new PdfException(KernelExceptionMessageConstant.CONTAINER_GENERATION_EXCEPTION, e); + } + } + + private MemoryStream GetDocumentByteArrayOutputStream() { + return ((MemoryStream)document.GetWriter().GetOutputStream()); + } + + private sealed class StandaloneMacPdfObjectAdder : AbstractPdfDocumentEventHandler { + protected internal override void OnAcceptedEvent(AbstractPdfDocumentEvent @event) { + this._enclosing.macPdfObject = new MacPdfObject(this._enclosing.GetContainerSizeEstimate()); + this._enclosing.document.GetTrailer().Put(PdfName.AuthCode, this._enclosing.macPdfObject.GetPdfObject()); + } + + internal StandaloneMacPdfObjectAdder(StandaloneMacIntegrityProtector _enclosing) { + this._enclosing = _enclosing; + } + + private readonly StandaloneMacIntegrityProtector _enclosing; + } + + private sealed class StandaloneMacContainerEmbedder : AbstractPdfDocumentEventHandler { + protected internal override void OnAcceptedEvent(AbstractPdfDocumentEvent @event) { + try { + this._enclosing.EmbedMacContainerInTrailer(); + } + catch (System.IO.IOException e) { + throw new PdfException(KernelExceptionMessageConstant.CONTAINER_EMBEDDING_EXCEPTION, e); + } + } + + internal StandaloneMacContainerEmbedder(StandaloneMacIntegrityProtector _enclosing) { + this._enclosing = _enclosing; + } + + private readonly StandaloneMacIntegrityProtector _enclosing; + } + } +//\endcond +} diff --git a/itext/itext.kernel/itext/kernel/numbering/RomanNumbering.cs b/itext/itext.kernel/itext/kernel/numbering/RomanNumbering.cs index 8bf64c0de0..8eaa7d70f5 100644 --- a/itext/itext.kernel/itext/kernel/numbering/RomanNumbering.cs +++ b/itext/itext.kernel/itext/kernel/numbering/RomanNumbering.cs @@ -85,9 +85,9 @@ protected internal static String Convert(int index) { // loop over the array with values for m-d-c-l-x-v-i RomanNumbering.RomanDigit dig = ROMAN_DIGITS[pos]; // adding as many digits as we can - while (index >= dig.value) { - buf.Append(dig.digit); - index -= dig.value; + while (index >= dig.GetValue()) { + buf.Append(dig.GetDigit()); + index -= dig.GetValue(); } // we have the complete number if (index <= 0) { @@ -95,12 +95,12 @@ protected internal static String Convert(int index) { } // look for the next digit that can be used in a special way int j = pos; - while (!ROMAN_DIGITS[++j].pre) { + while (!ROMAN_DIGITS[++j].IsPre()) { } // does the special notation apply? - if (index + ROMAN_DIGITS[j].value >= dig.value) { - buf.Append(ROMAN_DIGITS[j].digit).Append(dig.digit); - index -= dig.value - ROMAN_DIGITS[j].value; + if (index + ROMAN_DIGITS[j].GetValue() >= dig.GetValue()) { + buf.Append(ROMAN_DIGITS[j].GetDigit()).Append(dig.GetDigit()); + index -= dig.GetValue() - ROMAN_DIGITS[j].GetValue(); } pos++; } @@ -110,13 +110,13 @@ protected internal static String Convert(int index) { /// Helper class for Roman Digits private class RomanDigit { /// part of a roman number - public char digit; + private readonly char digit; /// value of the roman digit - public int value; + private readonly int value; /// can the digit be used as a prefix - public bool pre; + private readonly bool pre; //\cond DO_NOT_DOCUMENT /// Constructs a roman digit @@ -129,6 +129,24 @@ internal RomanDigit(char digit, int value, bool pre) { this.pre = pre; } //\endcond + + /// Retrieves the roman digit. + /// roman digit + public virtual char GetDigit() { + return digit; + } + + /// Retrieves the value of the roman digit. + /// value + public virtual int GetValue() { + return value; + } + + /// Retrieves whether the roman digit can be used as prefix. + /// true if it can, false otherwise + public virtual bool IsPre() { + return pre; + } } } } diff --git a/itext/itext.kernel/itext/kernel/pdf/DefaultFontStrategy.cs b/itext/itext.kernel/itext/kernel/pdf/DefaultFontStrategy.cs new file mode 100644 index 0000000000..0eda7a38e7 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/pdf/DefaultFontStrategy.cs @@ -0,0 +1,75 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using Microsoft.Extensions.Logging; +using iText.Commons; +using iText.Kernel.Font; + +namespace iText.Kernel.Pdf { + /// + /// The class defines a default font strategy for + /// + /// which is used in the scope of + /// . + /// + public class DefaultFontStrategy { + private readonly PdfDocument pdfDocument; + + private PdfFont defaultFont = null; + + /// + /// Instantiates a new instance of + /// + /// which + /// will be used for passed + /// + /// instance. + /// + /// the pdf document for which the strategy will be used to + public DefaultFontStrategy(PdfDocument pdfDocument) { + this.pdfDocument = pdfDocument; + } + + /// Gets default font. + /// + /// the + /// + /// instance + /// + public virtual PdfFont GetFont() { + if (defaultFont == null) { + try { + defaultFont = PdfFontFactory.CreateFont(); + if (pdfDocument.GetWriter() != null) { + defaultFont.MakeIndirect(pdfDocument); + } + } + catch (System.IO.IOException e) { + ILogger logger = ITextLogManager.GetLogger(typeof(iText.Kernel.Pdf.DefaultFontStrategy)); + logger.LogError(e, iText.IO.Logs.IoLogMessageConstant.EXCEPTION_WHILE_CREATING_DEFAULT_FONT); + defaultFont = null; + } + } + return defaultFont; + } + } +} diff --git a/itext/itext.kernel/itext/kernel/pdf/tagutils/TagTreeIteratorElementApprover.cs b/itext/itext.kernel/itext/kernel/pdf/DocumentInfoHelper.cs similarity index 56% rename from itext/itext.kernel/itext/kernel/pdf/tagutils/TagTreeIteratorElementApprover.cs rename to itext/itext.kernel/itext/kernel/pdf/DocumentInfoHelper.cs index 5ff992fd1e..a1d5c30de5 100644 --- a/itext/itext.kernel/itext/kernel/pdf/tagutils/TagTreeIteratorElementApprover.cs +++ b/itext/itext.kernel/itext/kernel/pdf/DocumentInfoHelper.cs @@ -20,37 +20,36 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ -using iText.Kernel.Pdf.Tagging; - -namespace iText.Kernel.Pdf.Tagutils { +namespace iText.Kernel.Pdf { /// - /// Element checker for - /// . + /// The class is helper which used inside + /// + /// to properly configure PDF document's info dictionary. /// - /// - /// Element checker for - /// . - /// It is used to check whether specific element should be traversed. - /// - public class TagTreeIteratorElementApprover { - /// - /// Creates a new instance of - /// - /// - public TagTreeIteratorElementApprover() { - } - - // Empty constructor - /// Checks whether the element should be traversed. - /// the element to check + public class DocumentInfoHelper { + /// If document info dictionary should be added to the trailer. /// /// /// - /// if the element should be traversed, - /// false otherwise + /// if should be added, otherwise + /// /// - public virtual bool Approve(IStructureNode elem) { - return elem != null; + public virtual bool ShouldAddDocumentInfoToTrailer() { + return true; + } + + /// + /// Adjusts document info before it's flushing and adding to the trailer + /// if required, see + /// . + /// + /// + /// the + /// + /// instance to adjust + /// + public virtual void AdjustDocumentInfo(PdfDocumentInfo documentInfo) { } + // do nothing } } diff --git a/itext/itext.kernel/itext/kernel/pdf/DocumentProperties.cs b/itext/itext.kernel/itext/kernel/pdf/DocumentProperties.cs index 1ce5ec0c74..31ccc41c2e 100644 --- a/itext/itext.kernel/itext/kernel/pdf/DocumentProperties.cs +++ b/itext/itext.kernel/itext/kernel/pdf/DocumentProperties.cs @@ -20,7 +20,10 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ +using System; +using System.Collections.Generic; using iText.Commons.Actions.Contexts; +using iText.Kernel.Exceptions; namespace iText.Kernel.Pdf { /// @@ -37,6 +40,10 @@ namespace iText.Kernel.Pdf { public class DocumentProperties { protected internal IMetaInfo metaInfo = null; +//\cond DO_NOT_DOCUMENT + internal Dictionary dependencies = new Dictionary(); +//\endcond + /// Default constructor, use provided setters for configuration options. public DocumentProperties() { } @@ -64,5 +71,24 @@ public virtual iText.Kernel.Pdf.DocumentProperties SetEventCountingMetaInfo(IMet public virtual bool IsEventCountingMetaInfoSet() { return this.metaInfo != null; } + + /// Register custom dependency for the document. + /// Type of the dependency. + /// The instance of the dependency. + /// + /// this + /// + /// instance + /// + public virtual iText.Kernel.Pdf.DocumentProperties RegisterDependency(Type clazz, Object instance) { + if (clazz == null) { + throw new ArgumentException(KernelExceptionMessageConstant.TYPE_SHOULD_NOT_BE_NULL); + } + if (instance == null) { + throw new ArgumentException(KernelExceptionMessageConstant.INSTANCE_SHOULD_NOT_BE_NULL); + } + dependencies.Put(clazz, instance); + return this; + } } } diff --git a/itext/itext.kernel/itext/kernel/pdf/EncryptionConstants.cs b/itext/itext.kernel/itext/kernel/pdf/EncryptionConstants.cs index c94b712907..b4aa698eb8 100644 --- a/itext/itext.kernel/itext/kernel/pdf/EncryptionConstants.cs +++ b/itext/itext.kernel/itext/kernel/pdf/EncryptionConstants.cs @@ -46,6 +46,11 @@ private EncryptionConstants() { /// Type of encryption. AES encryption algorithm will be used with the key length of 256 bits. public const int ENCRYPTION_AES_256 = 3; + /// Type of encryption. + /// Type of encryption. Advanced Encryption Standard-Galois/Counter Mode (AES-GCM) encryption algorithm. + /// + public const int ENCRYPTION_AES_GCM = 4; + /// Add this to the mode to keep the metadata in clear text. public const int DO_NOT_ENCRYPT_METADATA = 8; diff --git a/itext/itext.kernel/itext/kernel/pdf/EncryptionProperties.cs b/itext/itext.kernel/itext/kernel/pdf/EncryptionProperties.cs index 9f2e344366..e2239aa967 100644 --- a/itext/itext.kernel/itext/kernel/pdf/EncryptionProperties.cs +++ b/itext/itext.kernel/itext/kernel/pdf/EncryptionProperties.cs @@ -22,6 +22,7 @@ You should have received a copy of the GNU Affero General Public License */ using System.Security.Cryptography; using iText.Commons.Bouncycastle.Cert; +using iText.Kernel.Mac; namespace iText.Kernel.Pdf { /// Allows configuration of output PDF encryption. @@ -40,6 +41,17 @@ public class EncryptionProperties { protected internal int[] publicKeyEncryptPermissions; + /// + /// + /// class to configure MAC integrity protection properties. + /// + protected internal MacProperties macProperties; + +//\cond DO_NOT_DOCUMENT + internal static readonly MacProperties DEFAULT_MAC_PROPERTIES = new MacProperties(MacProperties.MacDigestAlgorithm + .SHA3_512); +//\endcond + /// Sets the encryption options for the document. /// /// the user password. Can be null or of zero length, which is equal to @@ -101,6 +113,79 @@ public class EncryptionProperties { /// public virtual EncryptionProperties SetStandardEncryption(byte[] userPassword, byte[] ownerPassword, int permissions , int encryptionAlgorithm) { + return SetStandardEncryption(userPassword, ownerPassword, permissions, encryptionAlgorithm, DEFAULT_MAC_PROPERTIES + ); + } + + /// Sets the encryption options for the document. + /// + /// the user password. Can be null or of zero length, which is equal to + /// omitting the user password + /// + /// + /// the owner password. If it's null or empty, iText will generate + /// a random string to be used as the owner password + /// + /// + /// the user permissions. The open permissions for the document can be + /// + /// , + /// + /// , + /// + /// , + /// + /// , + /// + /// , + /// + /// , + /// + /// and + /// . + /// The permissions can be combined by ORing them + /// + /// + /// the type of encryption. It can be one of + /// + /// , + /// + /// , + /// + /// or + /// . + /// Optionally + /// + /// can be OEed + /// to output the metadata in cleartext. + /// + /// can be ORed as well. + /// Please be aware that the passed encryption types may override permissions: + /// + /// implicitly sets + /// + /// and + /// + /// as false; + /// + /// implicitly sets + /// + /// as false; + /// + /// + /// + /// + /// class to configure MAC integrity protection properties. + /// Pass + /// + /// if you want to disable MAC protection for any reason + /// + /// + /// this + /// + /// + public virtual EncryptionProperties SetStandardEncryption(byte[] userPassword, byte[] ownerPassword, int permissions + , int encryptionAlgorithm, MacProperties macProperties) { ClearEncryption(); this.userPassword = userPassword; if (ownerPassword != null) { @@ -112,6 +197,7 @@ public virtual EncryptionProperties SetStandardEncryption(byte[] userPassword, b } this.standardEncryptPermissions = permissions; this.encryptionAlgorithm = encryptionAlgorithm; + this.macProperties = macProperties; return this; } @@ -169,16 +255,25 @@ public virtual EncryptionProperties SetStandardEncryption(byte[] userPassword, b /// /// as false; /// + /// + /// + /// + /// class to configure MAC integrity protection properties. + /// Pass + /// + /// if you want to disable MAC protection for any reason + /// /// /// this /// /// public virtual EncryptionProperties SetPublicKeyEncryption(IX509Certificate[] certs, int[] permissions, int - encryptionAlgorithm) { + encryptionAlgorithm, MacProperties macProperties) { ClearEncryption(); this.publicCertificates = certs; this.publicKeyEncryptPermissions = permissions; this.encryptionAlgorithm = encryptionAlgorithm; + this.macProperties = macProperties; return this; } @@ -199,6 +294,7 @@ private void ClearEncryption() { this.publicKeyEncryptPermissions = null; this.userPassword = null; this.ownerPassword = null; + this.macProperties = null; } private static void RandomBytes(byte[] bytes) { diff --git a/itext/itext.kernel/itext/kernel/pdf/FingerPrint.cs b/itext/itext.kernel/itext/kernel/pdf/FingerPrint.cs index 2fe36e1db1..d523054a3f 100644 --- a/itext/itext.kernel/itext/kernel/pdf/FingerPrint.cs +++ b/itext/itext.kernel/itext/kernel/pdf/FingerPrint.cs @@ -28,18 +28,34 @@ namespace iText.Kernel.Pdf { /// Data container for debugging information. /// /// Data container for debugging information. This class keeps a record of every registered product that - /// was involved in the creation of a certain PDF file. This information can then be used to log to the - /// logger or to the file. + /// was involved in the creation of a certain PDF file. /// public class FingerPrint { private ICollection productDataSet; + private bool fingerPrintEnabled = true; + /// Default constructor. /// Default constructor. Initializes the productDataSet. public FingerPrint() { this.productDataSet = new LinkedHashSet(); } + /// This method is used to disable iText fingerprint. + /// + /// This method is used to disable iText fingerprint. + /// IText fingerPrint can only be disabled if all products are in non AGPL mode. + /// + public virtual void DisableFingerPrint() { + fingerPrintEnabled = false; + } + + /// This method is used to check iText fingerprint state. + /// true if fingerprint will be added to the document + public virtual bool IsFingerPrintEnabled() { + return fingerPrintEnabled; + } + /// Registers a product to be added to the fingerprint or other debugging info. /// ProductData to be added /// true if the fingerprint did not already contain the specified element diff --git a/itext/itext.kernel/itext/kernel/pdf/MemoryLimitsAwareHandler.cs b/itext/itext.kernel/itext/kernel/pdf/MemoryLimitsAwareHandler.cs index b59b59cb0c..c78afdd828 100644 --- a/itext/itext.kernel/itext/kernel/pdf/MemoryLimitsAwareHandler.cs +++ b/itext/itext.kernel/itext/kernel/pdf/MemoryLimitsAwareHandler.cs @@ -22,7 +22,10 @@ You should have received a copy of the GNU Affero General Public License */ using System; using System.Collections.Generic; +using Microsoft.Extensions.Logging; +using iText.Commons; using iText.Kernel.Exceptions; +using iText.Kernel.Logs; namespace iText.Kernel.Pdf { /// @@ -43,6 +46,9 @@ namespace iText.Kernel.Pdf { /// /// public class MemoryLimitsAwareHandler { + private static readonly ILogger LOGGER = ITextLogManager.GetLogger(typeof(iText.Kernel.Pdf.MemoryLimitsAwareHandler + )); + private const int SINGLE_SCALE_COEFFICIENT = 100; private const int SUM_SCALE_COEFFICIENT = 500; @@ -115,6 +121,29 @@ private MemoryLimitsAwareHandler(int maxSizeOfSingleDecompressedPdfStream, long this.maxXObjectsSizePerPage = maxXObjectsSizePerPage; } + /// + /// Creates a new instance of + /// + /// by copying settings from this instance + /// of + /// . + /// + /// + /// a new instance of + /// . + /// + public virtual iText.Kernel.Pdf.MemoryLimitsAwareHandler CreateNewInstance() { + iText.Kernel.Pdf.MemoryLimitsAwareHandler to = new iText.Kernel.Pdf.MemoryLimitsAwareHandler(); + to.maxSizeOfSingleDecompressedPdfStream = this.maxSizeOfSingleDecompressedPdfStream; + to.maxSizeOfDecompressedPdfStreamsSum = this.maxSizeOfDecompressedPdfStreamsSum; + to.maxNumberOfElementsInXrefStructure = this.maxNumberOfElementsInXrefStructure; + to.maxXObjectsSizePerPage = this.maxXObjectsSizePerPage; + if (this.GetType() != typeof(iText.Kernel.Pdf.MemoryLimitsAwareHandler)) { + LOGGER.LogWarning(KernelLogMessageConstant.MEMORYLIMITAWAREHANDLER_OVERRIDE_CREATENEWINSTANCE_METHOD); + } + return to; + } + /// Gets the maximum allowed size which can be occupied by a single decompressed pdf stream. /// the maximum allowed size which can be occupied by a single decompressed pdf stream. public virtual int GetMaxSizeOfSingleDecompressedPdfStream() { diff --git a/itext/itext.kernel/itext/kernel/pdf/OcgPropertiesCopier.cs b/itext/itext.kernel/itext/kernel/pdf/OcgPropertiesCopier.cs index a323d1124b..7276b16dda 100644 --- a/itext/itext.kernel/itext/kernel/pdf/OcgPropertiesCopier.cs +++ b/itext/itext.kernel/itext/kernel/pdf/OcgPropertiesCopier.cs @@ -40,25 +40,30 @@ private OcgPropertiesCopier() { } // Empty constructor - public static void CopyOCGProperties(PdfDocument fromDocument, PdfDocument toDocument, IDictionary page2page) { + /// Copy unique page OCGs stored inside annotations/xobjects/resources from source pages to destination pages. + /// + /// document from which OCGs should be copied + /// document to which OCGs should be copied + /// page mapping, linking source pages to destination ones + public static void CopyOCGProperties(PdfDocument sourceDocument, PdfDocument destinationDocument, IDictionary + sourceToDestPageMapping) { try { // Configs are not copied - PdfDictionary toOcProperties = toDocument.GetCatalog().GetPdfObject().GetAsDictionary(PdfName.OCProperties + PdfDictionary toOcProperties = destinationDocument.GetCatalog().GetPdfObject().GetAsDictionary(PdfName.OCProperties ); - ICollection fromOcgsToCopy = iText.Kernel.Pdf.OcgPropertiesCopier.GetAllUsedNonFlushedOCGs - (page2page, toOcProperties); - if (fromOcgsToCopy.IsEmpty()) { + ICollection ocgsToCopy = iText.Kernel.Pdf.OcgPropertiesCopier.GetAllUsedNonFlushedOCGs + (sourceToDestPageMapping, toOcProperties); + if (ocgsToCopy.IsEmpty()) { return; } // Reset ocProperties field in order to create it a new at the // method end using the new (merged) OCProperties dictionary - toOcProperties = toDocument.GetCatalog().FillAndGetOcPropertiesDictionary(); - PdfDictionary fromOcProperties = fromDocument.GetCatalog().GetPdfObject().GetAsDictionary(PdfName.OCProperties + toOcProperties = destinationDocument.GetCatalog().FillAndGetOcPropertiesDictionary(); + PdfDictionary fromOcProperties = sourceDocument.GetCatalog().GetPdfObject().GetAsDictionary(PdfName.OCProperties ); - iText.Kernel.Pdf.OcgPropertiesCopier.CopyOCGs(fromOcgsToCopy, toOcProperties, toDocument); - iText.Kernel.Pdf.OcgPropertiesCopier.CopyDDictionary(fromOcgsToCopy, fromOcProperties.GetAsDictionary(PdfName - .D), toOcProperties, toDocument); + iText.Kernel.Pdf.OcgPropertiesCopier.CopyOCGs(ocgsToCopy, toOcProperties, destinationDocument); + iText.Kernel.Pdf.OcgPropertiesCopier.CopyDDictionary(ocgsToCopy, fromOcProperties.GetAsDictionary(PdfName. + D), toOcProperties, destinationDocument); } catch (Exception e) { LOGGER.LogError(MessageFormatUtil.Format(iText.IO.Logs.IoLogMessageConstant.OCG_COPYING_ERROR, e.ToString( @@ -66,6 +71,26 @@ public static void CopyOCGProperties(PdfDocument fromDocument, PdfDocument toDoc } } +//\cond DO_NOT_DOCUMENT + /// Get all OCGs from a given page annotations/xobjects/resources, including ones already stored in catalog + /// + /// where to search for OCGs. + /// set of indirect references pointing to found OCGs. + internal static ICollection GetOCGsFromPage(PdfPage page) { + //Using linked hash set for elements order consistency (e.g. in tests) + ICollection ocgs = new LinkedHashSet(); + IList annotations = page.GetAnnotations(); + foreach (PdfAnnotation annotation in annotations) { + //Pass null instead of catalog OCProperties value, to include ocg clashing with catalog + GetUsedNonFlushedOCGsFromAnnotation(annotation, annotation, ocgs, null); + } + PdfDictionary resources = page.GetPdfObject().GetAsDictionary(PdfName.Resources); + iText.Kernel.Pdf.OcgPropertiesCopier.GetUsedNonFlushedOCGsFromResources(resources, resources, ocgs, null, + new HashSet()); + return ocgs; + } +//\endcond + private static ICollection GetAllUsedNonFlushedOCGs(IDictionary page2page , PdfDictionary toOcProperties) { // NOTE: the PDF is considered to be valid and therefore the presence of OСG in OCProperties.OCGs is not checked @@ -81,19 +106,10 @@ private static ICollection GetAllUsedNonFlushedOCGs(IDicti IList fromAnnotations = fromPage.GetAnnotations(); for (int j = 0; j < toAnnotations.Count; j++) { if (!toAnnotations[j].IsFlushed()) { - PdfDictionary toAnnotDict = toAnnotations[j].GetPdfObject(); - PdfDictionary fromAnnotDict = fromAnnotations[j].GetPdfObject(); PdfAnnotation toAnnot = toAnnotations[j]; PdfAnnotation fromAnnot = fromAnnotations[j]; - if (!toAnnotDict.IsFlushed()) { - iText.Kernel.Pdf.OcgPropertiesCopier.GetUsedNonFlushedOCGsFromOcDict(toAnnotDict.GetAsDictionary(PdfName.OC - ), fromAnnotDict.GetAsDictionary(PdfName.OC), fromUsedOcgs, toOcProperties); - iText.Kernel.Pdf.OcgPropertiesCopier.GetUsedNonFlushedOCGsFromXObject(toAnnot.GetNormalAppearanceObject(), - fromAnnot.GetNormalAppearanceObject(), fromUsedOcgs, toOcProperties, new HashSet()); - iText.Kernel.Pdf.OcgPropertiesCopier.GetUsedNonFlushedOCGsFromXObject(toAnnot.GetRolloverAppearanceObject( - ), fromAnnot.GetRolloverAppearanceObject(), fromUsedOcgs, toOcProperties, new HashSet()); - iText.Kernel.Pdf.OcgPropertiesCopier.GetUsedNonFlushedOCGsFromXObject(toAnnot.GetDownAppearanceObject(), fromAnnot - .GetDownAppearanceObject(), fromUsedOcgs, toOcProperties, new HashSet()); + if (!toAnnot.GetPdfObject().IsFlushed()) { + GetUsedNonFlushedOCGsFromAnnotation(toAnnot, fromAnnot, fromUsedOcgs, toOcProperties); } } } @@ -105,6 +121,18 @@ private static ICollection GetAllUsedNonFlushedOCGs(IDicti return fromUsedOcgs; } + private static void GetUsedNonFlushedOCGsFromAnnotation(PdfAnnotation toAnnot, PdfAnnotation fromAnnot, ICollection + fromUsedOcgs, PdfDictionary toOcProperties) { + iText.Kernel.Pdf.OcgPropertiesCopier.GetUsedNonFlushedOCGsFromOcDict(toAnnot.GetPdfObject().GetAsDictionary + (PdfName.OC), fromAnnot.GetPdfObject().GetAsDictionary(PdfName.OC), fromUsedOcgs, toOcProperties); + iText.Kernel.Pdf.OcgPropertiesCopier.GetUsedNonFlushedOCGsFromXObject(toAnnot.GetNormalAppearanceObject(), + fromAnnot.GetNormalAppearanceObject(), fromUsedOcgs, toOcProperties, new HashSet()); + iText.Kernel.Pdf.OcgPropertiesCopier.GetUsedNonFlushedOCGsFromXObject(toAnnot.GetRolloverAppearanceObject( + ), fromAnnot.GetRolloverAppearanceObject(), fromUsedOcgs, toOcProperties, new HashSet()); + iText.Kernel.Pdf.OcgPropertiesCopier.GetUsedNonFlushedOCGsFromXObject(toAnnot.GetDownAppearanceObject(), fromAnnot + .GetDownAppearanceObject(), fromUsedOcgs, toOcProperties, new HashSet()); + } + private static void GetUsedNonFlushedOCGsFromResources(PdfDictionary toResources, PdfDictionary fromResources , ICollection fromUsedOcgs, PdfDictionary toOcProperties, ICollection visitedObjects) { diff --git a/itext/itext.kernel/itext/kernel/pdf/PageContentRotationHelper.cs b/itext/itext.kernel/itext/kernel/pdf/PageContentRotationHelper.cs new file mode 100644 index 0000000000..7b88756e07 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/pdf/PageContentRotationHelper.cs @@ -0,0 +1,91 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +namespace iText.Kernel.Pdf { + /// + /// Helper class to specify or check whether inverse matrix is already applied to the page content stream in case + /// page rotation is applied and + /// + /// is set to + /// . + /// + /// + /// Helper class to specify or check whether inverse matrix is already applied to the page content stream in case + /// page rotation is applied and + /// + /// is set to + /// . + /// + /// Page rotation inverse matrix rotates content into the opposite direction from page rotation direction + /// in order to give the impression of the not rotated text. It should be applied only once for the page. + /// + public sealed class PageContentRotationHelper { + /// + /// Checks if page rotation inverse matrix (which rotates content into the opposite direction from the page rotation + /// direction in order to give the impression of the not rotated text) is already applied to the page content stream. + /// + /// + /// Checks if page rotation inverse matrix (which rotates content into the opposite direction from the page rotation + /// direction in order to give the impression of the not rotated text) is already applied to the page content stream. + /// See + /// . + /// + /// + /// + /// + /// to check applied content rotation for + /// + /// + /// + /// + /// if inverse matrix is already applied, + /// + /// otherwise + /// + public static bool IsPageRotationInverseMatrixWritten(PdfPage page) { + return page.IsPageRotationInverseMatrixWritten(); + } + + /// + /// Specify that inverse matrix (which rotates content into the opposite direction from the page rotation + /// direction in order to give the impression of the not rotated text) is applied to the page content stream. + /// + /// + /// Specify that inverse matrix (which rotates content into the opposite direction from the page rotation + /// direction in order to give the impression of the not rotated text) is applied to the page content stream. + /// See + /// . + /// + /// + /// + /// + /// for which to specify that content rotation is applied + /// + public static void SetPageRotationInverseMatrixWritten(PdfPage page) { + page.SetPageRotationInverseMatrixWritten(); + } + + private PageContentRotationHelper() { + } + // Private constructor will prevent the instantiation of this class directly. + } +} diff --git a/itext/itext.kernel/itext/kernel/pdf/PageFlushingHelper.cs b/itext/itext.kernel/itext/kernel/pdf/PageFlushingHelper.cs index 5b84b48aea..2fe775a544 100644 --- a/itext/itext.kernel/itext/kernel/pdf/PageFlushingHelper.cs +++ b/itext/itext.kernel/itext/kernel/pdf/PageFlushingHelper.cs @@ -23,8 +23,8 @@ You should have received a copy of the GNU Affero General Public License using System; using System.Collections.Generic; using iText.Commons.Utils; -using iText.Kernel.Events; using iText.Kernel.Exceptions; +using iText.Kernel.Pdf.Event; using iText.Kernel.Pdf.Layer; namespace iText.Kernel.Pdf { diff --git a/itext/itext.kernel/itext/kernel/pdf/PdfAConformance.cs b/itext/itext.kernel/itext/kernel/pdf/PdfAConformance.cs new file mode 100644 index 0000000000..e9955ce48f --- /dev/null +++ b/itext/itext.kernel/itext/kernel/pdf/PdfAConformance.cs @@ -0,0 +1,108 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; + +namespace iText.Kernel.Pdf { + /// PDF/A is a special variant of PDF designed specifically for long-term document preservation (the “A” stands for archive). + /// + /// + /// PDF/A is a special variant of PDF designed specifically for long-term document preservation (the “A” stands for archive). + /// + /// The class contains an enumeration of all the PDF/A conformance currently supported by iText. + /// + public sealed class PdfAConformance { + /// PDF/A-1A + public static readonly iText.Kernel.Pdf.PdfAConformance PDF_A_1A = new iText.Kernel.Pdf.PdfAConformance("1" + , "A"); + + /// PDF/A-1B + public static readonly iText.Kernel.Pdf.PdfAConformance PDF_A_1B = new iText.Kernel.Pdf.PdfAConformance("1" + , "B"); + + /// PDF/A-2A + public static readonly iText.Kernel.Pdf.PdfAConformance PDF_A_2A = new iText.Kernel.Pdf.PdfAConformance("2" + , "A"); + + /// PDF/A-2B + public static readonly iText.Kernel.Pdf.PdfAConformance PDF_A_2B = new iText.Kernel.Pdf.PdfAConformance("2" + , "B"); + + /// PDF/A-2U + public static readonly iText.Kernel.Pdf.PdfAConformance PDF_A_2U = new iText.Kernel.Pdf.PdfAConformance("2" + , "U"); + + /// PDF/A-3A + public static readonly iText.Kernel.Pdf.PdfAConformance PDF_A_3A = new iText.Kernel.Pdf.PdfAConformance("3" + , "A"); + + /// PDF/A-3B + public static readonly iText.Kernel.Pdf.PdfAConformance PDF_A_3B = new iText.Kernel.Pdf.PdfAConformance("3" + , "B"); + + /// PDF/A-3U + public static readonly iText.Kernel.Pdf.PdfAConformance PDF_A_3U = new iText.Kernel.Pdf.PdfAConformance("3" + , "U"); + + /// PDF/A-4 + public static readonly iText.Kernel.Pdf.PdfAConformance PDF_A_4 = new iText.Kernel.Pdf.PdfAConformance("4" + , null); + + /// PDF/A-4E + public static readonly iText.Kernel.Pdf.PdfAConformance PDF_A_4E = new iText.Kernel.Pdf.PdfAConformance("4" + , "E"); + + /// PDF/A-4F + public static readonly iText.Kernel.Pdf.PdfAConformance PDF_A_4F = new iText.Kernel.Pdf.PdfAConformance("4" + , "F"); + + private readonly String part; + + private readonly String level; + +//\cond DO_NOT_DOCUMENT + /// + /// Creates a new + /// + /// instance. + /// + /// the part of the PDF/A conformance + /// the level of the PDF/A conformance + internal PdfAConformance(String part, String level) { + this.part = part; + this.level = level; + } +//\endcond + + /// Get the part of the PDF/A conformance. + /// the part of the PDF/A conformance + public String GetPart() { + return this.part; + } + + /// Get the level of the PDF/A conformance. + /// the level of the PDF/A conformance + public String GetLevel() { + return this.level; + } + } +} diff --git a/itext/itext.kernel/itext/kernel/pdf/PdfAConformanceLevel.cs b/itext/itext.kernel/itext/kernel/pdf/PdfAConformanceLevel.cs deleted file mode 100644 index 7931ef6837..0000000000 --- a/itext/itext.kernel/itext/kernel/pdf/PdfAConformanceLevel.cs +++ /dev/null @@ -1,180 +0,0 @@ -/* -This file is part of the iText (R) project. -Copyright (c) 1998-2024 Apryse Group NV -Authors: Apryse Software. - -This program is offered under a commercial and under the AGPL license. -For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. - -AGPL licensing: -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . -*/ -using System; -using iText.Kernel.XMP; -using iText.Kernel.XMP.Properties; - -namespace iText.Kernel.Pdf { - /// Enumeration of all the PDF/A conformance levels. - public class PdfAConformanceLevel : IConformanceLevel { - public static readonly iText.Kernel.Pdf.PdfAConformanceLevel PDF_A_1A = new iText.Kernel.Pdf.PdfAConformanceLevel - ("1", "A"); - - public static readonly iText.Kernel.Pdf.PdfAConformanceLevel PDF_A_1B = new iText.Kernel.Pdf.PdfAConformanceLevel - ("1", "B"); - - public static readonly iText.Kernel.Pdf.PdfAConformanceLevel PDF_A_2A = new iText.Kernel.Pdf.PdfAConformanceLevel - ("2", "A"); - - public static readonly iText.Kernel.Pdf.PdfAConformanceLevel PDF_A_2B = new iText.Kernel.Pdf.PdfAConformanceLevel - ("2", "B"); - - public static readonly iText.Kernel.Pdf.PdfAConformanceLevel PDF_A_2U = new iText.Kernel.Pdf.PdfAConformanceLevel - ("2", "U"); - - public static readonly iText.Kernel.Pdf.PdfAConformanceLevel PDF_A_3A = new iText.Kernel.Pdf.PdfAConformanceLevel - ("3", "A"); - - public static readonly iText.Kernel.Pdf.PdfAConformanceLevel PDF_A_3B = new iText.Kernel.Pdf.PdfAConformanceLevel - ("3", "B"); - - public static readonly iText.Kernel.Pdf.PdfAConformanceLevel PDF_A_3U = new iText.Kernel.Pdf.PdfAConformanceLevel - ("3", "U"); - - public static readonly iText.Kernel.Pdf.PdfAConformanceLevel PDF_A_4 = new iText.Kernel.Pdf.PdfAConformanceLevel - ("4", null); - - public static readonly iText.Kernel.Pdf.PdfAConformanceLevel PDF_A_4E = new iText.Kernel.Pdf.PdfAConformanceLevel - ("4", "E"); - - public static readonly iText.Kernel.Pdf.PdfAConformanceLevel PDF_A_4F = new iText.Kernel.Pdf.PdfAConformanceLevel - ("4", "F"); - - public const String PDF_A_4_REVISION = "2020"; - - private readonly String conformance; - - private readonly String part; - - private PdfAConformanceLevel(String part, String conformance) { - this.conformance = conformance; - this.part = part; - } - - public virtual String GetConformance() { - return conformance; - } - - public virtual String GetPart() { - return part; - } - - public static iText.Kernel.Pdf.PdfAConformanceLevel GetConformanceLevel(String part, String conformance) { - String lowLetter = conformance == null ? null : conformance.ToUpperInvariant(); - bool aLevel = "A".Equals(lowLetter); - bool bLevel = "B".Equals(lowLetter); - bool uLevel = "U".Equals(lowLetter); - bool eLevel = "E".Equals(lowLetter); - bool fLevel = "F".Equals(lowLetter); - switch (part) { - case "1": { - if (aLevel) { - return iText.Kernel.Pdf.PdfAConformanceLevel.PDF_A_1A; - } - if (bLevel) { - return iText.Kernel.Pdf.PdfAConformanceLevel.PDF_A_1B; - } - break; - } - - case "2": { - if (aLevel) { - return iText.Kernel.Pdf.PdfAConformanceLevel.PDF_A_2A; - } - if (bLevel) { - return iText.Kernel.Pdf.PdfAConformanceLevel.PDF_A_2B; - } - if (uLevel) { - return iText.Kernel.Pdf.PdfAConformanceLevel.PDF_A_2U; - } - break; - } - - case "3": { - if (aLevel) { - return iText.Kernel.Pdf.PdfAConformanceLevel.PDF_A_3A; - } - if (bLevel) { - return iText.Kernel.Pdf.PdfAConformanceLevel.PDF_A_3B; - } - if (uLevel) { - return iText.Kernel.Pdf.PdfAConformanceLevel.PDF_A_3U; - } - break; - } - - case "4": { - if (eLevel) { - return iText.Kernel.Pdf.PdfAConformanceLevel.PDF_A_4E; - } - if (fLevel) { - return iText.Kernel.Pdf.PdfAConformanceLevel.PDF_A_4F; - } - return iText.Kernel.Pdf.PdfAConformanceLevel.PDF_A_4; - } - } - return null; - } - - public static iText.Kernel.Pdf.PdfAConformanceLevel GetConformanceLevel(XMPMeta meta) { - XMPProperty conformanceXmpProperty = null; - XMPProperty partXmpProperty = null; - try { - conformanceXmpProperty = meta.GetProperty(XMPConst.NS_PDFA_ID, XMPConst.CONFORMANCE); - partXmpProperty = meta.GetProperty(XMPConst.NS_PDFA_ID, XMPConst.PART); - } - catch (XMPException) { - } - if (partXmpProperty == null || (conformanceXmpProperty == null && !"4".Equals(partXmpProperty.GetValue())) - ) { - return null; - } - else { - return GetConformanceLevel(partXmpProperty.GetValue(), conformanceXmpProperty == null ? null : conformanceXmpProperty - .GetValue()); - } - } - - /// Gets the PdfA conformance level. - /// - /// the possible candidate for - /// - /// - /// the document - /// the conformance level or null if it's not PDFA - [System.ObsoleteAttribute(@"since 8.0.4 Will be removed in next major release")] - public static iText.Kernel.Pdf.PdfAConformanceLevel GetPDFAConformance(IConformanceLevel possibleConformance - , PdfDocument document) { - if (possibleConformance is iText.Kernel.Pdf.PdfAConformanceLevel) { - return (iText.Kernel.Pdf.PdfAConformanceLevel)possibleConformance; - } - if (document == null) { - return null; - } - if (document.GetConformanceLevel() is iText.Kernel.Pdf.PdfAConformanceLevel) { - return (iText.Kernel.Pdf.PdfAConformanceLevel)document.GetConformanceLevel(); - } - return null; - } - } -} diff --git a/itext/itext.kernel/itext/kernel/pdf/PdfCatalog.cs b/itext/itext.kernel/itext/kernel/pdf/PdfCatalog.cs index e544b920ab..c566b3ccb7 100644 --- a/itext/itext.kernel/itext/kernel/pdf/PdfCatalog.cs +++ b/itext/itext.kernel/itext/kernel/pdf/PdfCatalog.cs @@ -376,11 +376,11 @@ public virtual void SetLang(PdfString lang) { } /// - /// Add an extensions dictionary containing developer prefix identification and version + /// Adds an extensions dictionary containing developer prefix identification and version /// numbers for developer extensions that occur in this document. /// /// - /// Add an extensions dictionary containing developer prefix identification and version + /// Adds an extensions dictionary containing developer prefix identification and version /// numbers for developer extensions that occur in this document. /// See ISO 32000-1, Table 28 – Entries in the catalog dictionary. /// @@ -432,6 +432,41 @@ public virtual void AddDeveloperExtension(PdfDeveloperExtension extension) { } } + /// + /// Removes an extensions dictionary containing developer prefix identification and version + /// numbers for developer extensions that do not occur in this document. + /// + /// + /// Removes an extensions dictionary containing developer prefix identification and version + /// numbers for developer extensions that do not occur in this document. + /// See ISO 32000-1, Table 28 – Entries in the catalog dictionary. + /// + /// developer extension to be removed from the document + public virtual void RemoveDeveloperExtension(PdfDeveloperExtension extension) { + PdfDictionary extensions = GetPdfObject().GetAsDictionary(PdfName.Extensions); + if (extensions == null) { + return; + } + if (extension.IsMultiValued()) { + PdfArray existingExtensionArray = extensions.GetAsArray(extension.GetPrefix()); + if (existingExtensionArray == null) { + return; + } + for (int i = 0; i < existingExtensionArray.Size(); i++) { + PdfDictionary pdfDict = existingExtensionArray.GetAsDictionary(i); + // for array-based extensions, we check for membership only, since comparison doesn't make sense + if (pdfDict.GetAsNumber(PdfName.ExtensionLevel).IntValue() == extension.GetExtensionLevel()) { + existingExtensionArray.Remove(i); + existingExtensionArray.SetModified(); + return; + } + } + } + else { + extensions.Remove(extension.GetPrefix()); + } + } + /// /// Gets collection dictionary that a conforming reader shall use to enhance the presentation of file attachments /// stored in the PDF document. diff --git a/itext/itext.kernel/itext/kernel/pdf/PdfConformance.cs b/itext/itext.kernel/itext/kernel/pdf/PdfConformance.cs new file mode 100644 index 0000000000..524ea7bd5b --- /dev/null +++ b/itext/itext.kernel/itext/kernel/pdf/PdfConformance.cs @@ -0,0 +1,373 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using iText.Kernel.XMP; +using iText.Kernel.XMP.Options; +using iText.Kernel.XMP.Properties; + +namespace iText.Kernel.Pdf { + /// The class represents possible PDF document conformance. + public class PdfConformance { + public const String PDF_A_4_REVISION = "2020"; + + public static readonly iText.Kernel.Pdf.PdfConformance PDF_A_1A = new iText.Kernel.Pdf.PdfConformance(PdfAConformance + .PDF_A_1A); + + public static readonly iText.Kernel.Pdf.PdfConformance PDF_A_1B = new iText.Kernel.Pdf.PdfConformance(PdfAConformance + .PDF_A_1B); + + public static readonly iText.Kernel.Pdf.PdfConformance PDF_A_2A = new iText.Kernel.Pdf.PdfConformance(PdfAConformance + .PDF_A_2A); + + public static readonly iText.Kernel.Pdf.PdfConformance PDF_A_2B = new iText.Kernel.Pdf.PdfConformance(PdfAConformance + .PDF_A_2B); + + public static readonly iText.Kernel.Pdf.PdfConformance PDF_A_2U = new iText.Kernel.Pdf.PdfConformance(PdfAConformance + .PDF_A_2U); + + public static readonly iText.Kernel.Pdf.PdfConformance PDF_A_3A = new iText.Kernel.Pdf.PdfConformance(PdfAConformance + .PDF_A_3A); + + public static readonly iText.Kernel.Pdf.PdfConformance PDF_A_3B = new iText.Kernel.Pdf.PdfConformance(PdfAConformance + .PDF_A_3B); + + public static readonly iText.Kernel.Pdf.PdfConformance PDF_A_3U = new iText.Kernel.Pdf.PdfConformance(PdfAConformance + .PDF_A_3U); + + public static readonly iText.Kernel.Pdf.PdfConformance PDF_A_4 = new iText.Kernel.Pdf.PdfConformance(PdfAConformance + .PDF_A_4); + + public static readonly iText.Kernel.Pdf.PdfConformance PDF_A_4E = new iText.Kernel.Pdf.PdfConformance(PdfAConformance + .PDF_A_4E); + + public static readonly iText.Kernel.Pdf.PdfConformance PDF_A_4F = new iText.Kernel.Pdf.PdfConformance(PdfAConformance + .PDF_A_4F); + + public static readonly iText.Kernel.Pdf.PdfConformance PDF_UA_1 = new iText.Kernel.Pdf.PdfConformance(PdfUAConformance + .PDF_UA_1); + + public static readonly iText.Kernel.Pdf.PdfConformance PDF_NONE_CONFORMANCE = new iText.Kernel.Pdf.PdfConformance + (); + + private readonly PdfAConformance aConformance; + + private readonly PdfUAConformance uaConformance; + + /// + /// Creates a new + /// + /// instance based on PDF/A and PDF/UA conformance. + /// + /// the PDF/A conformance + /// the PDF/UA conformance + public PdfConformance(PdfAConformance aConformance, PdfUAConformance uaConformance) { + this.aConformance = aConformance; + this.uaConformance = uaConformance; + } + + /// + /// Creates a new + /// + /// instance based on only PDF/A conformance. + /// + /// the PDF/A conformance + public PdfConformance(PdfAConformance aConformance) { + this.aConformance = aConformance; + this.uaConformance = null; + } + + /// + /// Creates a new + /// + /// instance based on only PDF/UA conformance. + /// + /// the PDF/UA conformance + public PdfConformance(PdfUAConformance uaConformance) { + this.uaConformance = uaConformance; + this.aConformance = null; + } + + /// + /// Creates a new + /// + /// instance without PDF/A or PDF/UA conformance. + /// + public PdfConformance() { + this.aConformance = null; + this.uaConformance = null; + } + + /// Checks if any PDF/A conformance is specified. + /// + /// + /// + /// if PDF/A conformance is specified, otherwise + /// + /// + public virtual bool IsPdfA() { + return aConformance != null; + } + + /// Checks if any PDF/UA conformance is specified. + /// + /// + /// + /// if PDF/UA conformance is specified, otherwise + /// + /// + public virtual bool IsPdfUA() { + return uaConformance != null; + } + + /// Checks if any PDF/A or PDF/UA conformance is specified. + /// + /// + /// + /// if PDF/A or PDF/UA conformance is specified, otherwise + /// + /// + public virtual bool IsPdfAOrUa() { + return IsPdfA() || IsPdfUA(); + } + + /// + /// Gets the + /// + /// instance if specified. + /// + /// + /// the specified + /// + /// instance or + /// . + /// + public virtual PdfAConformance GetAConformance() { + return aConformance; + } + + /// + /// Gets the + /// + /// instance if specified. + /// + /// + /// the specified + /// + /// instance or + /// . + /// + public virtual PdfUAConformance GetUAConformance() { + return uaConformance; + } + + public override bool Equals(Object o) { + if (this == o) { + return true; + } + if (o == null || GetType() != o.GetType()) { + return false; + } + iText.Kernel.Pdf.PdfConformance that = (iText.Kernel.Pdf.PdfConformance)o; + return aConformance == that.aConformance && uaConformance == that.uaConformance; + } + + public override int GetHashCode() { + int result = aConformance == null ? 0 : aConformance.GetHashCode(); + result = 31 * result + (uaConformance == null ? 0 : uaConformance.GetHashCode()); + return result; + } + + /// + /// Gets + /// + /// instance from + /// . + /// + /// the meta data to parse + /// + /// the + /// + /// instance + /// + public static iText.Kernel.Pdf.PdfConformance GetConformance(XMPMeta meta) { + if (meta == null) { + return iText.Kernel.Pdf.PdfConformance.PDF_NONE_CONFORMANCE; + } + XMPProperty conformanceAXmpProperty = null; + XMPProperty partAXmpProperty = null; + PdfAConformance aLevel = null; + try { + conformanceAXmpProperty = meta.GetProperty(XMPConst.NS_PDFA_ID, XMPConst.CONFORMANCE); + partAXmpProperty = meta.GetProperty(XMPConst.NS_PDFA_ID, XMPConst.PART); + } + catch (XMPException) { + } + if (partAXmpProperty != null && (conformanceAXmpProperty != null || "4".Equals(partAXmpProperty.GetValue() + ))) { + aLevel = GetAConformance(partAXmpProperty.GetValue(), conformanceAXmpProperty == null ? null : conformanceAXmpProperty + .GetValue()); + } + XMPProperty partUAXmpProperty = null; + PdfUAConformance uaLevel = null; + try { + partUAXmpProperty = meta.GetProperty(XMPConst.NS_PDFUA_ID, XMPConst.PART); + } + catch (XMPException) { + } + if (partUAXmpProperty != null) { + uaLevel = GetUAConformance(partUAXmpProperty.GetValue()); + } + return new iText.Kernel.Pdf.PdfConformance(aLevel, uaLevel); + } + + /// Sets required fields into XMP metadata according to passed PDF conformance. + /// the xmp metadata to which required PDF conformance fields will be set + /// the PDF conformance according to which XMP will be updated + public static void SetConformanceToXmp(XMPMeta xmpMeta, iText.Kernel.Pdf.PdfConformance conformance) { + if (conformance == null) { + return; + } + // Don't set any property if property value was set, so if + // smth was invalid in source document, it will be left as is. + // But if e.g. for PDF/A-4 revision wasn't specified, we will fix it. + if (conformance.IsPdfUA()) { + if (xmpMeta.GetProperty(XMPConst.NS_PDFUA_ID, XMPConst.PART) == null) { + xmpMeta.SetPropertyInteger(XMPConst.NS_PDFUA_ID, XMPConst.PART, 1, new PropertyOptions(PropertyOptions.SEPARATE_NODE + )); + } + } + if (conformance.IsPdfA()) { + PdfAConformance aLevel = conformance.GetAConformance(); + if (xmpMeta.GetProperty(XMPConst.NS_PDFA_ID, XMPConst.PART) == null) { + xmpMeta.SetProperty(XMPConst.NS_PDFA_ID, XMPConst.PART, aLevel.GetPart()); + } + if (aLevel.GetLevel() != null && xmpMeta.GetProperty(XMPConst.NS_PDFA_ID, XMPConst.CONFORMANCE) == null) { + xmpMeta.SetProperty(XMPConst.NS_PDFA_ID, XMPConst.CONFORMANCE, aLevel.GetLevel()); + } + if ("4".Equals(aLevel.GetPart()) && xmpMeta.GetProperty(XMPConst.NS_PDFA_ID, XMPConst.REV) == null) { + xmpMeta.SetProperty(XMPConst.NS_PDFA_ID, XMPConst.REV, iText.Kernel.Pdf.PdfConformance.PDF_A_4_REVISION); + } + if (xmpMeta.GetPropertyInteger(XMPConst.NS_PDFUA_ID, XMPConst.PART) != null) { + XMPMeta taggedExtensionMeta = XMPMetaFactory.ParseFromString(PDF_UA_EXTENSION); + XMPUtils.AppendProperties(taggedExtensionMeta, xmpMeta, true, false); + } + } + } + + /// + /// Gets an instance of + /// + /// based on passed part and level. + /// + /// the part of PDF/A conformance + /// the level of PDF/A conformance + /// + /// the + /// + /// instance or + /// + /// if there is no PDF/A conformance for passed parameters + /// + public static PdfAConformance GetAConformance(String part, String level) { + String lowLetter = level == null ? null : level.ToUpperInvariant(); + bool aLevel = "A".Equals(lowLetter); + bool bLevel = "B".Equals(lowLetter); + bool uLevel = "U".Equals(lowLetter); + bool eLevel = "E".Equals(lowLetter); + bool fLevel = "F".Equals(lowLetter); + switch (part) { + case "1": { + if (aLevel) { + return PdfAConformance.PDF_A_1A; + } + if (bLevel) { + return PdfAConformance.PDF_A_1B; + } + break; + } + + case "2": { + if (aLevel) { + return PdfAConformance.PDF_A_2A; + } + if (bLevel) { + return PdfAConformance.PDF_A_2B; + } + if (uLevel) { + return PdfAConformance.PDF_A_2U; + } + break; + } + + case "3": { + if (aLevel) { + return PdfAConformance.PDF_A_3A; + } + if (bLevel) { + return PdfAConformance.PDF_A_3B; + } + if (uLevel) { + return PdfAConformance.PDF_A_3U; + } + break; + } + + case "4": { + if (eLevel) { + return PdfAConformance.PDF_A_4E; + } + if (fLevel) { + return PdfAConformance.PDF_A_4F; + } + return PdfAConformance.PDF_A_4; + } + } + return null; + } + + private static PdfUAConformance GetUAConformance(String part) { + if ("1".Equals(part)) { + return PdfUAConformance.PDF_UA_1; + } + return null; + } + + private const String PDF_UA_EXTENSION = " \n" + " \n" + + " \n" + + " \n" + " \n" + " \n" + + " \n" + + " pdfuaid\n" + " PDF/UA identification schema\n" + + " \n" + " \n" + " \n" + + " internal\n" + " PDF/UA version identifier\n" + + " part\n" + " Integer\n" + + " \n" + " \n" + " internal\n" + + " PDF/UA amendment identifier\n" + + " amd\n" + " Text\n" + + " \n" + " \n" + " internal\n" + + " PDF/UA corrigenda identifier\n" + + " corr\n" + " Text\n" + + " \n" + " \n" + " \n" + + " \n" + " \n" + " \n" + + " \n" + " \n" + " "; + } +} diff --git a/itext/itext.kernel/itext/kernel/pdf/PdfDeveloperExtension.cs b/itext/itext.kernel/itext/kernel/pdf/PdfDeveloperExtension.cs index ea302a3e48..61e2f2fc77 100644 --- a/itext/itext.kernel/itext/kernel/pdf/PdfDeveloperExtension.cs +++ b/itext/itext.kernel/itext/kernel/pdf/PdfDeveloperExtension.cs @@ -62,6 +62,16 @@ public class PdfDeveloperExtension { (PdfName.ISO_, PdfName.Pdf_Version_2_0, 32002, "https://www.iso.org/standard/45875.html", ":2022", true ); + /// An instance of this class for ISO/TS 32004. + public static readonly iText.Kernel.Pdf.PdfDeveloperExtension ISO_32004 = new iText.Kernel.Pdf.PdfDeveloperExtension + (PdfName.ISO_, PdfName.Pdf_Version_2_0, 32004, "https://www.iso.org/standard/45877.html", ":2024", true + ); + + /// An instance of this class for ISO/TS 32003. + public static readonly iText.Kernel.Pdf.PdfDeveloperExtension ISO_32003 = new iText.Kernel.Pdf.PdfDeveloperExtension + (PdfName.ISO_, PdfName.Pdf_Version_2_0, 32003, "https://www.iso.org/standard/45876.html", ":2023", true + ); + /// The prefix used in the Extensions dictionary added to the Catalog. protected internal PdfName prefix; diff --git a/itext/itext.kernel/itext/kernel/pdf/PdfDocument.cs b/itext/itext.kernel/itext/kernel/pdf/PdfDocument.cs index 637eaaf5dc..eec61fff30 100644 --- a/itext/itext.kernel/itext/kernel/pdf/PdfDocument.cs +++ b/itext/itext.kernel/itext/kernel/pdf/PdfDocument.cs @@ -33,32 +33,32 @@ You should have received a copy of the GNU Affero General Public License using iText.Kernel.Actions.Data; using iText.Kernel.Actions.Events; using iText.Kernel.Colors; -using iText.Kernel.Events; using iText.Kernel.Exceptions; using iText.Kernel.Font; using iText.Kernel.Geom; using iText.Kernel.Logs; using iText.Kernel.Numbering; using iText.Kernel.Pdf.Annot; -using iText.Kernel.Pdf.Canvas; using iText.Kernel.Pdf.Collection; +using iText.Kernel.Pdf.Event; using iText.Kernel.Pdf.Filespec; using iText.Kernel.Pdf.Navigation; using iText.Kernel.Pdf.Statistics; using iText.Kernel.Pdf.Tagging; using iText.Kernel.Pdf.Tagutils; -using iText.Kernel.Utils; +using iText.Kernel.Validation; +using iText.Kernel.Validation.Context; using iText.Kernel.XMP; using iText.Kernel.XMP.Options; namespace iText.Kernel.Pdf { /// Main enter point to work with PDF document. - public class PdfDocument : IEventDispatcher, IDisposable { - // + public class PdfDocument : IDisposable { private static readonly PdfName[] PDF_NAMES_TO_REMOVE_FROM_ORIGINAL_TRAILER = new PdfName[] { PdfName.Encrypt - , PdfName.Size, PdfName.Prev, PdfName.Root, PdfName.Info, PdfName.ID, PdfName.XRefStm }; + , PdfName.Size, PdfName.Prev, PdfName.Root, PdfName.Info, PdfName.ID, PdfName.XRefStm, PdfName.AuthCode + }; - private static readonly IPdfPageFactory pdfPageFactory = new PdfPageFactory(); + private static readonly ILogger LOGGER = ITextLogManager.GetLogger(typeof(iText.Kernel.Pdf.PdfDocument)); protected internal readonly StampingProperties properties; @@ -70,6 +70,8 @@ public class PdfDocument : IEventDispatcher, IDisposable { private readonly IDictionary documentFonts = new Dictionary(); + private readonly ICollection documentHandlers = new LinkedHashSet(); + private readonly SequenceId documentId; /// To be adjusted destinations. @@ -81,8 +83,6 @@ public class PdfDocument : IEventDispatcher, IDisposable { private readonly IList pendingDestinationMutations = new List(); - protected internal EventDispatcher eventDispatcher = new EventDispatcher(); - /// PdfWriter associated with the document. /// /// PdfWriter associated with the document. @@ -97,21 +97,17 @@ public class PdfDocument : IEventDispatcher, IDisposable { /// protected internal PdfReader reader = null; - /// XMP Metadata for the document. - protected internal byte[] xmpMetadata = null; - /// Document catalog. protected internal PdfCatalog catalog = null; /// Document trailed. protected internal PdfDictionary trailer = null; - /// Document info. - protected internal PdfDocumentInfo info = null; - /// Document version. protected internal PdfVersion pdfVersion = PdfVersion.PDF_1_7; + protected internal PdfConformance pdfConformance = PdfConformance.PDF_NONE_CONFORMANCE; + protected internal FingerPrint fingerPrint; protected internal SerializeOptions serializeOptions = new SerializeOptions(); @@ -133,6 +129,12 @@ public class PdfDocument : IEventDispatcher, IDisposable { protected internal TagStructureContext tagStructureContext; + protected internal DocumentInfoHelper documentInfoHelper = new DocumentInfoHelper(); + + protected internal DefaultFontStrategy defaultFontStrategy; + + protected internal IPdfPageFactory pdfPageFactory = new PdfPageFactory(); + //\cond DO_NOT_DOCUMENT /// Cache of already serialized objects from this document for smart mode. internal IDictionary serializedObjectsCache = new DictionaryThe original modified (second) id when the document is read initially. private PdfString modifiedDocumentId; - private PdfFont defaultFont = null; - private EncryptedEmbeddedStreamsHandler encryptedEmbeddedStreamsHandler; + /// Document info. + private PdfDocumentInfo info = null; + + /// XMP Metadata bytes for the document. + private byte[] xmpMetadataBytes = null; + + /// XMP Metadata which is used to prevent bytes deserialization for a few times on the same bytes. + private XMPMeta xmpMetadata = null; + private readonly DIContainer diContainer = new DIContainer(); /// Open PDF document in reading mode. /// PDF reader. public PdfDocument(PdfReader reader) : this(reader, new DocumentProperties()) { + defaultFontStrategy = new DefaultFontStrategy(this); } /// Open PDF document in reading mode. /// PDF reader. /// document properties public PdfDocument(PdfReader reader, DocumentProperties properties) { + defaultFontStrategy = new DefaultFontStrategy(this); if (reader == null) { throw new ArgumentException("The reader in PdfDocument constructor can not be null."); } documentId = new SequenceId(); this.reader = reader; - // default values of the StampingProperties doesn't affect anything - this.properties = new StampingProperties(); - this.properties.SetEventCountingMetaInfo(properties.metaInfo); + this.properties = new StampingProperties(properties); Open(null); } @@ -192,6 +201,7 @@ public PdfDocument(PdfReader reader, DocumentProperties properties) { /// PDF writer public PdfDocument(PdfWriter writer) : this(writer, new DocumentProperties()) { + defaultFontStrategy = new DefaultFontStrategy(this); } /// Open PDF document in writing mode. @@ -202,14 +212,13 @@ public PdfDocument(PdfWriter writer) /// PDF writer /// document properties public PdfDocument(PdfWriter writer, DocumentProperties properties) { + defaultFontStrategy = new DefaultFontStrategy(this); if (writer == null) { throw new ArgumentException("The writer in PdfDocument constructor can not be null."); } documentId = new SequenceId(); this.writer = writer; - // default values of the StampingProperties doesn't affect anything - this.properties = new StampingProperties(); - this.properties.SetEventCountingMetaInfo(properties.metaInfo); + this.properties = new StampingProperties(properties); Open(writer.properties.pdfVersion); } @@ -222,6 +231,7 @@ public PdfDocument(PdfWriter writer, DocumentProperties properties) { /// PDF writer. public PdfDocument(PdfReader reader, PdfWriter writer) : this(reader, writer, new StampingProperties()) { + defaultFontStrategy = new DefaultFontStrategy(this); } /// Open PDF document in stamping mode. @@ -229,6 +239,7 @@ public PdfDocument(PdfReader reader, PdfWriter writer) /// PDF writer. /// properties of the stamping process public PdfDocument(PdfReader reader, PdfWriter writer, StampingProperties properties) { + defaultFontStrategy = new DefaultFontStrategy(this); if (reader == null) { throw new ArgumentException("The reader in PdfDocument constructor can not be null."); } @@ -241,52 +252,147 @@ public PdfDocument(PdfReader reader, PdfWriter writer, StampingProperties proper this.properties = properties; bool writerHasEncryption = WriterHasEncryption(); if (properties.appendMode && writerHasEncryption) { - ILogger logger = ITextLogManager.GetLogger(typeof(iText.Kernel.Pdf.PdfDocument)); - logger.LogWarning(iText.IO.Logs.IoLogMessageConstant.WRITER_ENCRYPTION_IS_IGNORED_APPEND); + LOGGER.LogWarning(iText.IO.Logs.IoLogMessageConstant.WRITER_ENCRYPTION_IS_IGNORED_APPEND); } if (properties.preserveEncryption && writerHasEncryption) { - ILogger logger = ITextLogManager.GetLogger(typeof(iText.Kernel.Pdf.PdfDocument)); - logger.LogWarning(iText.IO.Logs.IoLogMessageConstant.WRITER_ENCRYPTION_IS_IGNORED_PRESERVE); + LOGGER.LogWarning(iText.IO.Logs.IoLogMessageConstant.WRITER_ENCRYPTION_IS_IGNORED_PRESERVE); } Open(writer.properties.pdfVersion); } + /// Checks if the document closing has been started or not. + /// + /// + /// + /// if closing process has been started, otherwise + /// + /// + public virtual bool IsClosing() { + return isClosing; + } + /// Sets the XMP Metadata. + /// + /// Sets the XMP Metadata. + /// + /// The XMP Metadata values are synchronized with information dictionary. + /// /// the xmpMetadata to set /// serialization options public virtual void SetXmpMetadata(XMPMeta xmpMeta, SerializeOptions serializeOptions) { this.serializeOptions = serializeOptions; - SetXmpMetadata(XMPMetaFactory.SerializeToBuffer(xmpMeta, serializeOptions)); - } - - /// Use this method to set the XMP Metadata. - /// The xmpMetadata to set. - protected internal virtual void SetXmpMetadata(byte[] xmpMetadata) { - this.xmpMetadata = xmpMetadata; + this.xmpMetadataBytes = XMPMetaFactory.SerializeToBuffer(xmpMeta, serializeOptions); + this.xmpMetadata = xmpMeta; } /// Sets the XMP Metadata. + /// + /// Sets the XMP Metadata. + /// + /// The XMP Metadata values are synchronized with information dictionary. + /// + /// + /// will be used for serialization, they + /// can be changed by + /// . + /// /// the xmpMetadata to set public virtual void SetXmpMetadata(XMPMeta xmpMeta) { - serializeOptions.SetPadding(2000); SetXmpMetadata(xmpMeta, serializeOptions); } - /// Gets XMPMetadata. - /// the XMPMetadata - public virtual byte[] GetXmpMetadata() { + /// Sets the XMP Metadata. + /// + /// Sets the XMP Metadata. + /// + /// The XMP Metadata values are synchronized with information dictionary. + /// + /// the xmpMetadata bytes to set + protected internal virtual void SetXmpMetadata(byte[] xmpMetadata) { + this.xmpMetadataBytes = xmpMetadata; + this.xmpMetadata = null; + try { + GetXmpMetadata(); + } + catch (XMPException e) { + LOGGER.LogError(e, iText.IO.Logs.IoLogMessageConstant.EXCEPTION_WHILE_UPDATING_XMPMETADATA); + } + } + + /// Gets XMP Metadata. + /// + /// Gets XMP Metadata. + /// + /// XMP Metadata is lazy initialized. It will be initialized during the first call of this method. + /// + /// To update XMP Metadata of the document, use + /// + /// method. + /// + /// existed XMP Metadata + public virtual XMPMeta GetXmpMetadata() { return GetXmpMetadata(false); } - /// Gets XMPMetadata or create a new one. - /// if true, create a new empty XMPMetadata if it did not present. - /// existed or newly created XMPMetadata byte array. - public virtual byte[] GetXmpMetadata(bool createNew) { - if (xmpMetadata == null && createNew) { + /// Gets XMP Metadata or create a new one. + /// + /// Gets XMP Metadata or create a new one. + /// + /// XMP Metadata is lazy initialized. It will be initialized during the first call of this method. + /// + /// To update XMP Metadata of the document, use + /// + /// method. + /// + /// if true, create a new empty XMP Metadata if it did not present + /// existed or newly created XMP Metadata + public virtual XMPMeta GetXmpMetadata(bool createNew) { + if (xmpMetadata == null) { + byte[] bytes = GetXmpMetadataBytes(createNew); + xmpMetadata = bytes == null ? null : XMPMetaFactory.ParseFromBuffer(bytes); + } + return xmpMetadata; + } + + /// Gets XMP Metadata. + /// + /// Gets XMP Metadata. + /// + /// XMP Metadata is lazy initialized. It will be initialized during the first call of this method. + /// + /// To update XMP Metadata of the document, use + /// + /// method. + /// + /// existed XMP Metadata bytes + public virtual byte[] GetXmpMetadataBytes() { + return GetXmpMetadataBytes(false); + } + + /// Gets XMP Metadata or create a new one. + /// + /// Gets XMP Metadata or create a new one. + /// + /// XMP Metadata is lazy initialized. It will be initialized during the first call of this method. + /// + /// To update XMP Metadata of the document, use + /// + /// method. + /// + /// if true, create a new empty XMP Metadata if it did not present + /// existed or newly created XMP Metadata byte array + public virtual byte[] GetXmpMetadataBytes(bool createNew) { + CheckClosingStatus(); + if (xmpMetadataBytes == null) { + PdfStream xmpMetadataStream = catalog.GetPdfObject().GetAsStream(PdfName.Metadata); + if (xmpMetadataStream != null) { + xmpMetadataBytes = xmpMetadataStream.GetBytes(); + } + } + if (createNew && xmpMetadataBytes == null) { XMPMeta xmpMeta = XMPMetaFactory.Create(); xmpMeta.SetObjectName(XMPConst.TAG_XMPMETA); xmpMeta.SetObjectName(""); - AddCustomMetadataExtensions(xmpMeta); try { xmpMeta.SetProperty(XMPConst.NS_DC, PdfConst.Format, "application/pdf"); SetXmpMetadata(xmpMeta); @@ -294,7 +400,10 @@ public virtual byte[] GetXmpMetadata(bool createNew) { catch (XMPException) { } } - return xmpMetadata; + if (xmpMetadataBytes == null) { + return null; + } + return JavaUtil.ArraysCopyOf(xmpMetadataBytes, xmpMetadataBytes.Length); } /// Gets PdfObject by object number. @@ -575,17 +684,23 @@ public virtual DIContainer GetDiContainer() { /// Gets document information dictionary. /// /// Gets document information dictionary. + /// /// /// is lazy initialized. It will be initialized during the first call of this method. + /// + /// The information dictionary values are synchronized with document XMP Metadata. /// /// document information dictionary. public virtual PdfDocumentInfo GetDocumentInfo() { CheckClosingStatus(); if (info == null) { - PdfObject infoDict = trailer.Get(PdfName.Info); - info = new PdfDocumentInfo(infoDict is PdfDictionary ? (PdfDictionary)infoDict : new PdfDictionary(), this - ); - XmpMetaInfoConverter.AppendMetadataToInfo(xmpMetadata, info); + PdfDictionary infoDict = trailer == null ? null : trailer.GetAsDictionary(PdfName.Info); + info = new PdfDocumentInfo(infoDict == null ? new PdfDictionary() : infoDict, this); + try { + XmpMetaInfoConverter.AppendMetadataToInfo(GetXmpMetadata(), info); + } + catch (XMPException) { + } } return info; } @@ -598,7 +713,7 @@ public virtual PdfDocumentInfo GetDocumentInfo() { /// /// should be used /// - /// original dccument id + /// original document id public virtual PdfString GetOriginalDocumentId() { return originalDocumentId; } @@ -636,34 +751,57 @@ public virtual void SetDefaultPageSize(PageSize pageSize) { defaultPageSize = pageSize; } - /// - public virtual void AddEventHandler(String type, iText.Kernel.Events.IEventHandler handler) { - eventDispatcher.AddEventHandler(type, handler); - } - - /// - public virtual void DispatchEvent(Event @event) { - eventDispatcher.DispatchEvent(@event); + /// Adds new event handler. + /// a type of event to be handled + /// event handler + public virtual void AddEventHandler(String type, AbstractPdfDocumentEventHandler handler) { + handler.AddType(type); + documentHandlers.Add(handler); } - /// - public virtual void DispatchEvent(Event @event, bool delayed) { - eventDispatcher.DispatchEvent(@event, delayed); + /// Dispatches an event. + /// + /// the + /// + /// to be dispatched + /// + public virtual void DispatchEvent(AbstractPdfDocumentEvent @event) { + @event.SetDocument(this); + foreach (IEventHandler handler in documentHandlers) { + handler.OnEvent(@event); + } } - /// - public virtual bool HasEventHandler(String type) { - return eventDispatcher.HasEventHandler(type); + /// Checks if provided event handler assigned for this document. + /// + /// the + /// + /// to check + /// + /// + /// + /// + /// if event handler is assigned for this document, + /// + /// otherwise + /// + public virtual bool HasEventHandler(AbstractPdfDocumentEventHandler handler) { + return documentHandlers.Contains(handler); } - /// - public virtual void RemoveEventHandler(String type, iText.Kernel.Events.IEventHandler handler) { - eventDispatcher.RemoveEventHandler(type, handler); + /// Removes event handler. + /// + /// + /// + /// event handler to remove for this document + /// + public virtual void RemoveEventHandler(AbstractPdfDocumentEventHandler handler) { + documentHandlers.Remove(handler); } - /// + /// Removes all event handlers for this document. public virtual void RemoveAllHandlers() { - eventDispatcher.RemoveAllHandlers(); + documentHandlers.Clear(); } /// @@ -744,6 +882,7 @@ public virtual void Close() { .GetInstance())); // The event will prepare document for flushing, i.e. will set an appropriate producer line manager.OnEvent(new FlushPdfDocumentEvent(this)); + DispatchEvent(new PdfDocumentEvent(PdfDocumentEvent.START_DOCUMENT_CLOSING)); UpdateXmpMetadata(); // In PDF 2.0, all the values except CreationDate and ModDate are deprecated. Remove them now if (pdfVersion.CompareTo(PdfVersion.PDF_2_0) >= 0) { @@ -751,17 +890,17 @@ public virtual void Close() { GetDocumentInfo().GetPdfObject().Remove(deprecatedKey); } } - if (GetXmpMetadata() != null) { + if (GetXmpMetadataBytes() != null) { PdfStream xmp = catalog.GetPdfObject().GetAsStream(PdfName.Metadata); if (IsAppendMode() && xmp != null && !xmp.IsFlushed() && xmp.GetIndirectReference() != null) { // Use existing object for append mode - xmp.SetData(xmpMetadata); + xmp.SetData(GetXmpMetadataBytes()); xmp.SetModified(); } else { // Create new object xmp = (PdfStream)new PdfStream().MakeIndirect(this); - xmp.GetOutputStream().Write(xmpMetadata); + xmp.GetOutputStream().Write(GetXmpMetadataBytes()); catalog.GetPdfObject().Put(PdfName.Metadata, xmp); catalog.SetModified(); } @@ -776,7 +915,7 @@ public virtual void Close() { if (!properties.appendMode && catalog.IsOCPropertiesMayHaveChanged()) { catalog.GetPdfObject().Put(PdfName.OCProperties, catalog.GetOCProperties(false).GetPdfObject()); } - CheckIsoConformance(); + CheckIsoConformance(new PdfDocumentValidationContext(this, GetDocumentFonts())); if (GetNumberOfPages() == 0) { // Add new page here, not in PdfPagesTree#generateTree method, so that any page // operations are available when handling the START_PAGE and INSERT_PAGE events @@ -784,6 +923,14 @@ public virtual void Close() { } PdfObject crypto = null; ICollection forbiddenToFlush = new HashSet(); + documentInfoHelper.AdjustDocumentInfo(GetDocumentInfo()); + // The following 2 operators prevent the possible inconsistency between root and info + // entries existing in the trailer object and corresponding fields. This inconsistency + // may appear when user gets trailer and explicitly sets new root or info dictionaries. + if (documentInfoHelper.ShouldAddDocumentInfoToTrailer()) { + trailer.Put(PdfName.Info, GetDocumentInfo().GetPdfObject()); + } + trailer.Put(PdfName.Root, catalog.GetPdfObject()); if (properties.appendMode) { if (structTreeRoot != null) { TryFlushTagStructure(true); @@ -801,11 +948,13 @@ public virtual void Close() { } } PdfObject pageRoot = catalog.GetPageTree().GenerateTree(); - FlushInfoDictionary(properties.appendMode); if (catalog.GetPdfObject().IsModified() || pageRoot.IsModified()) { catalog.Put(PdfName.Pages, pageRoot); catalog.GetPdfObject().Flush(false); } + if (GetDocumentInfo().GetPdfObject().IsModified()) { + GetDocumentInfo().GetPdfObject().Flush(false); + } FlushFonts(); if (writer.crypto != null) { System.Diagnostics.Debug.Assert(reader.decrypt.GetPdfObject() == writer.crypto.GetPdfObject(), "Conflict with source encryption" @@ -849,8 +998,8 @@ public virtual void Close() { if (structTreeRoot != null) { TryFlushTagStructure(false); } - FlushInfoDictionary(properties.appendMode); catalog.GetPdfObject().Flush(false); + GetDocumentInfo().GetPdfObject().Flush(false); FlushFonts(); if (writer.crypto != null) { crypto = writer.crypto.GetPdfObject(); @@ -876,15 +1025,11 @@ public virtual void Close() { // To avoid encryption of XrefStream and Encryption dictionary remove crypto. // NOTE. No need in reverting, because it is the last operation with the document. writer.crypto = null; - CheckIsoConformance(crypto, IsoKey.CRYPTO); + CheckIsoConformance(new CryptoValidationContext(crypto)); if (!properties.appendMode && crypto != null) { // no need to flush crypto in append mode, it shall not have changed in this case crypto.Flush(false); } - // The following operator prevents the possible inconsistency between root and info - // entries existing in the trailer object and corresponding fields. This inconsistency - // may appear when user gets trailer and explicitly sets new root or info dictionaries. - trailer.Put(PdfName.Root, catalog.GetPdfObject()); //By this time original and modified document ids should always be not null due to initializing in // either writer properties, or in the writer init section on document open or from pdfreader. So we // shouldn't worry about it being null next @@ -896,9 +1041,14 @@ public virtual void Close() { long amountOfBytes = ((CountOutputStream)writer.GetOutputStream()).GetAmountOfWrittenBytes(); manager.OnEvent(new SizeOfPdfStatisticsEvent(amountOfBytes, ITextCoreProductData.GetInstance())); } + else { + if (writer.GetOutputStream() is ByteArrayOutputStream) { + long amountOfBytes = ((ByteArrayOutputStream)writer.GetOutputStream()).Length; + manager.OnEvent(new SizeOfPdfStatisticsEvent(amountOfBytes, ITextCoreProductData.GetInstance())); + } + } } catalog.GetPageTree().ClearPageRefs(); - RemoveAllHandlers(); } catch (System.IO.IOException e) { throw new PdfException(KernelExceptionMessageConstant.CANNOT_CLOSE_DOCUMENT, e, this); @@ -906,11 +1056,10 @@ public virtual void Close() { finally { if (writer != null && IsCloseWriter()) { try { - writer.Dispose(); + writer.Finish(); } catch (Exception e) { - ILogger logger = ITextLogManager.GetLogger(typeof(iText.Kernel.Pdf.PdfDocument)); - logger.LogError(e, iText.IO.Logs.IoLogMessageConstant.PDF_WRITER_CLOSING_FAILED); + LOGGER.LogError(e, iText.IO.Logs.IoLogMessageConstant.PDF_WRITER_CLOSING_FAILED); } } if (reader != null && IsCloseReader()) { @@ -918,8 +1067,7 @@ public virtual void Close() { reader.Close(); } catch (Exception e) { - ILogger logger = ITextLogManager.GetLogger(typeof(iText.Kernel.Pdf.PdfDocument)); - logger.LogError(e, iText.IO.Logs.IoLogMessageConstant.PDF_READER_CLOSING_FAILED); + LOGGER.LogError(e, iText.IO.Logs.IoLogMessageConstant.PDF_READER_CLOSING_FAILED); } } } @@ -1034,15 +1182,11 @@ public virtual IList CopyPagesTo(int pageFrom, int pageTo, iText.Kernel /// /// Get the - /// + /// /// - /// - /// the - /// - /// will be null if the document does not have a conformance level specified - /// - public virtual IConformanceLevel GetConformanceLevel() { - return null; + /// the document conformance + public virtual PdfConformance GetConformance() { + return pdfConformance; } /// @@ -1278,8 +1422,7 @@ public virtual IList CopyPagesTo(IList pagesToCopy, iText.Kernel.P } } else { - ILogger logger = ITextLogManager.GetLogger(typeof(iText.Kernel.Pdf.PdfDocument)); - logger.LogWarning(iText.IO.Logs.IoLogMessageConstant.NOT_TAGGED_PAGES_IN_TAGGED_DOCUMENT); + LOGGER.LogWarning(iText.IO.Logs.IoLogMessageConstant.NOT_TAGGED_PAGES_IN_TAGGED_DOCUMENT); } } if (catalog.IsOutlineMode()) { @@ -1502,8 +1645,7 @@ public virtual void AddNamedDestination(String key, PdfObject value) { public virtual void AddNamedDestination(PdfString key, PdfObject value) { CheckClosingStatus(); if (value.IsArray() && ((PdfArray)value).Get(0).IsNumber()) { - ITextLogManager.GetLogger(typeof(iText.Kernel.Pdf.PdfDocument)).LogWarning(iText.IO.Logs.IoLogMessageConstant - .INVALID_DESTINATION_TYPE); + LOGGER.LogWarning(iText.IO.Logs.IoLogMessageConstant.INVALID_DESTINATION_TYPE); } catalog.AddNamedDestination(key, value); } @@ -1554,39 +1696,7 @@ public virtual void AddOutputIntent(PdfOutputIntent outputIntent) { outputIntents.Add(outputIntent.GetPdfObject()); } - /// Checks whether PDF document conforms a specific standard. - /// An object to conform. - /// type of object to conform. - public virtual void CheckIsoConformance(Object obj, IsoKey key) { - CheckIsoConformance(obj, key, null, null); - } - - /// Checks whether PDF document conforms a specific standard. - /// an object to conform. - /// type of object to conform. - /// - /// - /// - /// associated with an object to check. - /// - /// current content stream - public virtual void CheckIsoConformance(Object obj, IsoKey key, PdfResources resources, PdfStream contentStream - ) { - CheckIsoConformance(obj, key, resources, contentStream, null); - } - - /// Checks whether PDF document conforms a specific standard. - /// an object to conform. - /// type of object to conform. - /// - /// - /// - /// associated with an object to check. - /// - /// current content stream. - /// extra data required for the check. - public virtual void CheckIsoConformance(Object obj, IsoKey key, PdfResources resources, PdfStream contentStream - , Object extra) { + public virtual void CheckIsoConformance(IValidationContext validationContext) { if (!this.GetDiContainer().IsRegistered(typeof(ValidationContainer))) { return; } @@ -1594,25 +1704,7 @@ public virtual void CheckIsoConformance(Object obj, IsoKey key, PdfResources res if (container == null) { return; } - container.Validate(obj, key, resources, contentStream, extra); - } - - /// Checks whether PDF document conforms a specific standard. - /// - /// Checks whether PDF document conforms a specific standard. - /// Shall be overridden. - /// - /// - /// a - /// - /// object to conform. - /// - /// - /// - /// - /// associated with an object to check. - /// - public virtual void CheckShowTextIsoConformance(CanvasGraphicsState gState, PdfResources resources) { + container.Validate(validationContext); } /// Adds file attachment at document level. @@ -1644,8 +1736,7 @@ public virtual void AddFileAttachment(String key, PdfFileSpec fs) { /// public virtual void AddAssociatedFile(String description, PdfFileSpec fs) { if (null == ((PdfDictionary)fs.GetPdfObject()).Get(PdfName.AFRelationship)) { - ILogger logger = ITextLogManager.GetLogger(typeof(iText.Kernel.Pdf.PdfDocument)); - logger.LogError(iText.IO.Logs.IoLogMessageConstant.ASSOCIATED_FILE_SPEC_SHALL_INCLUDE_AFRELATIONSHIP); + LOGGER.LogError(iText.IO.Logs.IoLogMessageConstant.ASSOCIATED_FILE_SPEC_SHALL_INCLUDE_AFRELATIONSHIP); } PdfArray afArray = catalog.GetPdfObject().GetAsArray(PdfName.AF); if (afArray == null) { @@ -1695,7 +1786,7 @@ public virtual PdfEncryptedPayloadDocument GetEncryptedPayloadDocument() { } } catch (PdfException e) { - ITextLogManager.GetLogger(GetType()).LogError(e.Message); + LOGGER.LogError(e.Message); } } } @@ -1722,7 +1813,7 @@ public virtual void SetEncryptedPayload(PdfFileSpec fs) { throw new PdfException(KernelExceptionMessageConstant.CANNOT_SET_ENCRYPTED_PAYLOAD_TO_ENCRYPTED_DOCUMENT); } if (!PdfName.EncryptedPayload.Equals(((PdfDictionary)fs.GetPdfObject()).Get(PdfName.AFRelationship))) { - ITextLogManager.GetLogger(GetType()).LogError(iText.IO.Logs.IoLogMessageConstant.ENCRYPTED_PAYLOAD_FILE_SPEC_SHALL_HAVE_AFRELATIONSHIP_FILED_EQUAL_TO_ENCRYPTED_PAYLOAD + LOGGER.LogError(iText.IO.Logs.IoLogMessageConstant.ENCRYPTED_PAYLOAD_FILE_SPEC_SHALL_HAVE_AFRELATIONSHIP_FILED_EQUAL_TO_ENCRYPTED_PAYLOAD ); } PdfEncryptedPayload encryptedPayload = PdfEncryptedPayload.ExtractFrom(fs); @@ -1732,7 +1823,7 @@ public virtual void SetEncryptedPayload(PdfFileSpec fs) { } PdfCollection collection = GetCatalog().GetCollection(); if (collection != null) { - ITextLogManager.GetLogger(GetType()).LogWarning(iText.IO.Logs.IoLogMessageConstant.COLLECTION_DICTIONARY_ALREADY_EXISTS_IT_WILL_BE_MODIFIED + LOGGER.LogWarning(iText.IO.Logs.IoLogMessageConstant.COLLECTION_DICTIONARY_ALREADY_EXISTS_IT_WILL_BE_MODIFIED ); } else { @@ -1892,20 +1983,7 @@ public virtual PdfFont GetFont(PdfDictionary dictionary) { /// on error. /// public virtual PdfFont GetDefaultFont() { - if (defaultFont == null) { - try { - defaultFont = PdfFontFactory.CreateFont(); - if (writer != null) { - defaultFont.MakeIndirect(this); - } - } - catch (System.IO.IOException e) { - ILogger logger = ITextLogManager.GetLogger(typeof(iText.Kernel.Pdf.PdfDocument)); - logger.LogError(e, iText.IO.Logs.IoLogMessageConstant.EXCEPTION_WHILE_CREATING_DEFAULT_FONT); - defaultFont = null; - } - } - return defaultFont; + return defaultFontStrategy.GetFont(); } /// @@ -2020,35 +2098,25 @@ protected internal virtual void StoreDestinationToReaddress(PdfDestination desti )); } - /// Checks whether PDF document conforms to a specific standard. - protected internal virtual void CheckIsoConformance() { - if (!this.GetDiContainer().IsRegistered(typeof(ValidationContainer))) { - return; - } - ValidationContainer container = this.GetDiContainer().GetInstance(); - if (container == null) { - return; - } - ValidationContext context = new ValidationContext().WithPdfDocument(this).WithFonts(GetDocumentFonts()); - container.Validate(context); - } - - /// - /// Mark an object with - /// . - /// - /// an object to mark. - protected internal virtual void MarkObjectAsMustBeFlushed(PdfObject pdfObject) { - if (pdfObject.GetIndirectReference() != null) { - pdfObject.GetIndirectReference().SetState(PdfObject.MUST_BE_FLUSHED); - } - } - /// Flush an object. /// object to flush. /// indicates whether object can be placed into object stream. protected internal virtual void FlushObject(PdfObject pdfObject, bool canBeInObjStm) { - writer.FlushObject(pdfObject, canBeInObjStm); + bool flushAllowed = true; + if (!isClosing && this.GetDiContainer().IsRegistered(typeof(ValidationContainer))) { + ValidationContainer container = this.GetDiContainer().GetInstance(); + if (container != null) { + flushAllowed = container.IsPdfObjectChecked(pdfObject); + } + } + if (isClosing || flushAllowed) { + writer.FlushObject(pdfObject, canBeInObjStm); + } + else { + if (pdfObject.GetIndirectReference() != null) { + pdfObject.GetIndirectReference().SetState(PdfObject.MUST_BE_FLUSHED); + } + } } /// Initializes document. @@ -2060,6 +2128,11 @@ protected internal virtual void FlushObject(PdfObject pdfObject, bool canBeInObj /// otherwise /// protected internal virtual void Open(PdfVersion newPdfVersion) { + if (properties != null) { + foreach (Type aClass in properties.dependencies.Keys) { + diContainer.Register(aClass, properties.dependencies.Get(aClass)); + } + } this.fingerPrint = new FingerPrint(); this.encryptedEmbeddedStreamsHandler = new EncryptedEmbeddedStreamsHandler(this); try { @@ -2091,16 +2164,6 @@ protected internal virtual void Open(PdfVersion newPdfVersion) { } catalog = new PdfCatalog(catalogDictionary); UpdatePdfVersionFromCatalog(); - PdfStream xmpMetadataStream = catalog.GetPdfObject().GetAsStream(PdfName.Metadata); - if (xmpMetadataStream != null) { - xmpMetadata = xmpMetadataStream.GetBytes(); - if (!this.GetType().Equals(typeof(iText.Kernel.Pdf.PdfDocument))) { - // TODO DEVSIX-5292 If somebody extends PdfDocument we have to initialize document info - // and conformance level to provide compatibility. This code block shall be removed - reader.GetPdfAConformanceLevel(); - GetDocumentInfo(); - } - } PdfDictionary str = catalog.GetPdfObject().GetAsDictionary(PdfName.StructTreeRoot); if (str != null) { TryInitTagStructure(str); @@ -2109,9 +2172,15 @@ protected internal virtual void Open(PdfVersion newPdfVersion) { throw new PdfException(KernelExceptionMessageConstant.APPEND_MODE_REQUIRES_A_DOCUMENT_WITHOUT_ERRORS_EVEN_IF_RECOVERY_IS_POSSIBLE ); } + pdfConformance = reader.GetPdfConformance(); } xref.InitFreeReferencesList(this); if (writer != null) { + if (writer.properties.addPdfAXmpMetadata != null || writer.properties.addPdfUaXmpMetadata != null) { + pdfConformance = new PdfConformance(writer.properties.addPdfAXmpMetadata, writer.properties.addPdfUaXmpMetadata + ); + } + EnableByteArrayWritingMode(); if (reader != null && reader.HasXrefStm() && writer.properties.isFullCompression == null) { writer.properties.isFullCompression = true; } @@ -2124,7 +2193,8 @@ protected internal virtual void Open(PdfVersion newPdfVersion) { writer.document = this; if (reader == null) { catalog = new PdfCatalog(this); - info = new PdfDocumentInfo(this).AddCreationDate(); + // initialize document info + GetDocumentInfo().AddCreationDate(); } GetDocumentInfo().AddModDate(); if (trailer == null) { @@ -2132,7 +2202,7 @@ protected internal virtual void Open(PdfVersion newPdfVersion) { } // We keep the original trailer of the document to preserve the original document keys, // but we have to remove all standard keys that can occur in the trailer to avoid invalid pdfs - if (trailer.Size() > 0) { + if (!trailer.IsEmpty()) { foreach (PdfName key in iText.Kernel.Pdf.PdfDocument.PDF_NAMES_TO_REMOVE_FROM_ORIGINAL_TRAILER) { trailer.Remove(key); } @@ -2182,6 +2252,10 @@ protected internal virtual void Open(PdfVersion newPdfVersion) { writer.Write((byte)'\n'); OverrideFullCompressionInWriterProperties(writer.properties, reader.HasXrefStm()); writer.crypto = reader.decrypt; + if (writer.crypto != null) { + writer.crypto.CheckEncryptionRequirements(this); + writer.crypto.ConfigureEncryptionParametersFromWriter(this); + } if (newPdfVersion != null) { // In PDF 1.4, a PDF version can also be specified in the Version entry of the document catalog, // essentially updating the version associated with the file by overriding the one specified in @@ -2214,19 +2288,8 @@ protected internal virtual void Open(PdfVersion newPdfVersion) { if (!embeddedStreamsSavedOnReading && writer.crypto.IsEmbeddedFilesOnly()) { encryptedEmbeddedStreamsHandler.StoreAllEmbeddedStreams(); } - if (writer.crypto.GetCryptoMode() < EncryptionConstants.ENCRYPTION_AES_256) { - VersionConforming.ValidatePdfVersionForDeprecatedFeatureLogWarn(this, PdfVersion.PDF_2_0, VersionConforming - .DEPRECATED_ENCRYPTION_ALGORITHMS); - } - else { - if (writer.crypto.GetCryptoMode() == EncryptionConstants.ENCRYPTION_AES_256) { - PdfNumber r = writer.crypto.GetPdfObject().GetAsNumber(PdfName.R); - if (r != null && r.IntValue() == 5) { - VersionConforming.ValidatePdfVersionForDeprecatedFeatureLogWarn(this, PdfVersion.PDF_2_0, VersionConforming - .DEPRECATED_AES256_REVISION); - } - } - } + writer.crypto.CheckEncryptionRequirements(this); + writer.crypto.ConfigureEncryptionParametersFromWriter(this); } } } @@ -2240,29 +2303,6 @@ protected internal virtual void Open(PdfVersion newPdfVersion) { } } - /// Adds custom XMP metadata extension. - /// Adds custom XMP metadata extension. Useful for PDF/UA, ZUGFeRD, etc. - /// - /// - /// - /// to add custom metadata to. - /// - protected internal virtual void AddCustomMetadataExtensions(XMPMeta xmpMeta) { - } - - /// Flush info dictionary if needed. - /// true if the document is edited in append mode. - protected internal virtual void FlushInfoDictionary(bool appendMode) { - PdfObject infoDictObj = GetDocumentInfo().GetPdfObject(); - if (!appendMode || infoDictObj.IsModified()) { - infoDictObj.Flush(false); - } - // The following operator prevents the possible inconsistency between root and info - // entries existing in the trailer object and corresponding fields. This inconsistency - // may appear when user gets trailer and explicitly sets new root or info dictionaries. - trailer.Put(PdfName.Info, infoDictObj); - } - /// Updates XMP metadata. /// /// Updates XMP metadata. @@ -2272,14 +2312,14 @@ protected internal virtual void UpdateXmpMetadata() { try { // We add PDF producer info in any case, and the valid way to do it for PDF 2.0 in only in metadata, not // in the info dictionary. - if (xmpMetadata != null || writer.properties.addXmpMetadata || pdfVersion.CompareTo(PdfVersion.PDF_2_0) >= - 0) { - SetXmpMetadata(UpdateDefaultXmpMetadata()); + if (GetXmpMetadataBytes() != null || writer.properties.addXmpMetadata || pdfVersion.CompareTo(PdfVersion.PDF_2_0 + ) >= 0) { + XMPMeta xmpMeta = UpdateDefaultXmpMetadata(); + SetXmpMetadata(xmpMeta); } } catch (XMPException e) { - ILogger logger = ITextLogManager.GetLogger(typeof(iText.Kernel.Pdf.PdfDocument)); - logger.LogError(e, iText.IO.Logs.IoLogMessageConstant.EXCEPTION_WHILE_UPDATING_XMPMETADATA); + LOGGER.LogError(e, iText.IO.Logs.IoLogMessageConstant.EXCEPTION_WHILE_UPDATING_XMPMETADATA); } } @@ -2289,13 +2329,9 @@ protected internal virtual void UpdateXmpMetadata() { /// /// the XMPMetadata protected internal virtual XMPMeta UpdateDefaultXmpMetadata() { - XMPMeta xmpMeta = XMPMetaFactory.ParseFromBuffer(GetXmpMetadata(true)); + XMPMeta xmpMeta = GetXmpMetadata(true); XmpMetaInfoConverter.AppendDocumentInfoToMetadata(GetDocumentInfo(), xmpMeta); - if (IsTagged() && writer.properties.addUAXmpMetadata && !IsXmpMetaHasProperty(xmpMeta, XMPConst.NS_PDFUA_ID - , XMPConst.PART)) { - xmpMeta.SetPropertyInteger(XMPConst.NS_PDFUA_ID, XMPConst.PART, 1, new PropertyOptions(PropertyOptions.SEPARATE_NODE - )); - } + PdfConformance.SetConformanceToXmp(xmpMeta, pdfConformance); return xmpMeta; } @@ -2398,8 +2434,7 @@ protected internal virtual void TryInitTagStructure(PdfDictionary str) { catch (Exception e) { structTreeRoot = null; structParentIndex = -1; - ILogger logger = ITextLogManager.GetLogger(typeof(iText.Kernel.Pdf.PdfDocument)); - logger.LogError(e, iText.IO.Logs.IoLogMessageConstant.TAG_STRUCTURE_INIT_FAILED); + LOGGER.LogError(e, iText.IO.Logs.IoLogMessageConstant.TAG_STRUCTURE_INIT_FAILED); } } @@ -2429,6 +2464,21 @@ internal virtual bool HasAcroForm() { } //\endcond + private void EnableByteArrayWritingMode() { + if (properties.appendMode || properties.preserveEncryption) { + if (reader.decrypt != null && reader.decrypt.GetMacContainer() != null) { + writer.EnableByteArrayWritingMode(); + } + } + else { + if (writer.properties.encryptionProperties != null && writer.properties.encryptionProperties.macProperties + != null && writer.properties.pdfVersion != null && PdfVersion.PDF_2_0.CompareTo(writer.properties.pdfVersion + ) <= 0) { + writer.EnableByteArrayWritingMode(); + } + } + } + private void TryFlushTagStructure(bool isAppendMode) { try { if (tagStructureContext != null) { @@ -2605,8 +2655,7 @@ private void ReadDocumentIds() { private void ProcessReadingError(String errorMessage) { if (PdfReader.StrictnessLevel.CONSERVATIVE.IsStricter(reader.GetStrictnessLevel())) { - ILogger logger = ITextLogManager.GetLogger(typeof(iText.Kernel.Pdf.PdfDocument)); - logger.LogError(errorMessage); + LOGGER.LogError(errorMessage); } else { throw new PdfException(errorMessage); @@ -2616,22 +2665,16 @@ private void ProcessReadingError(String errorMessage) { private static void OverrideFullCompressionInWriterProperties(WriterProperties properties, bool readerHasXrefStream ) { if (true == properties.isFullCompression && !readerHasXrefStream) { - ILogger logger = ITextLogManager.GetLogger(typeof(iText.Kernel.Pdf.PdfDocument)); - logger.LogWarning(KernelLogMessageConstant.FULL_COMPRESSION_APPEND_MODE_XREF_TABLE_INCONSISTENCY); + LOGGER.LogWarning(KernelLogMessageConstant.FULL_COMPRESSION_APPEND_MODE_XREF_TABLE_INCONSISTENCY); } else { if (false == properties.isFullCompression && readerHasXrefStream) { - ILogger logger = ITextLogManager.GetLogger(typeof(iText.Kernel.Pdf.PdfDocument)); - logger.LogWarning(KernelLogMessageConstant.FULL_COMPRESSION_APPEND_MODE_XREF_STREAM_INCONSISTENCY); + LOGGER.LogWarning(KernelLogMessageConstant.FULL_COMPRESSION_APPEND_MODE_XREF_STREAM_INCONSISTENCY); } } properties.isFullCompression = readerHasXrefStream; } - private static bool IsXmpMetaHasProperty(XMPMeta xmpMeta, String schemaNS, String propName) { - return xmpMeta.GetProperty(schemaNS, propName) != null; - } - private class DestinationMutationInfo { private readonly PdfDestination originalDestination; diff --git a/itext/itext.kernel/itext/kernel/pdf/PdfDocumentInfo.cs b/itext/itext.kernel/itext/kernel/pdf/PdfDocumentInfo.cs index 99bf3cadf9..98020a9dfe 100644 --- a/itext/itext.kernel/itext/kernel/pdf/PdfDocumentInfo.cs +++ b/itext/itext.kernel/itext/kernel/pdf/PdfDocumentInfo.cs @@ -31,7 +31,7 @@ public class PdfDocumentInfo { PdfName.Subject, PdfName.Keywords, PdfName.Creator, PdfName.Producer, PdfName.Trapped }; //\endcond - private PdfDictionary infoDictionary; + private readonly PdfDictionary infoDictionary; //\cond DO_NOT_DOCUMENT /// Create a PdfDocumentInfo based on the passed PdfDictionary. @@ -44,14 +44,6 @@ internal PdfDocumentInfo(PdfDictionary pdfObject, PdfDocument pdfDocument) { } //\endcond -//\cond DO_NOT_DOCUMENT - /// Create a default, empty PdfDocumentInfo and link it to the passed PdfDocument - /// document the info will belong to - internal PdfDocumentInfo(PdfDocument pdfDocument) - : this(new PdfDictionary(), pdfDocument) { - } -//\endcond - public virtual iText.Kernel.Pdf.PdfDocumentInfo SetTitle(String title) { return Put(PdfName.Title, new PdfString(title, PdfEncodings.UNICODE_BIG)); } diff --git a/itext/itext.kernel/itext/kernel/pdf/PdfEncryption.cs b/itext/itext.kernel/itext/kernel/pdf/PdfEncryption.cs index 43dbdc8b30..d68e809f64 100644 --- a/itext/itext.kernel/itext/kernel/pdf/PdfEncryption.cs +++ b/itext/itext.kernel/itext/kernel/pdf/PdfEncryption.cs @@ -30,6 +30,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Kernel.Crypto; using iText.Kernel.Crypto.Securityhandler; using iText.Kernel.Exceptions; +using iText.Kernel.Mac; namespace iText.Kernel.Pdf { public class PdfEncryption : PdfObjectWrapper { @@ -41,13 +42,19 @@ public class PdfEncryption : PdfObjectWrapper { private const int AES_256 = 5; + private const int AES_GCM = 6; + private const int DEFAULT_KEY_LENGTH = 40; + private const int MAC_ENABLED = ~(1 << 12); + + private const int MAC_DISABLED = 1 << 12; + private static long seq = SystemUtil.GetTimeBasedSeed(); private int cryptoMode; - private long? permissions; + private int? permissions; private bool encryptMetadata; @@ -57,6 +64,8 @@ public class PdfEncryption : PdfObjectWrapper { private SecurityHandler securityHandler; + private AbstractMacIntegrityProtector macContainer; + /// Creates the encryption. /// /// the user password. Can be null or of zero length, which is equal to @@ -119,13 +128,20 @@ public class PdfEncryption : PdfObjectWrapper { /// /// of the target document for encryption /// + /// + /// + /// + /// class for MAC integrity protection + /// public PdfEncryption(byte[] userPassword, byte[] ownerPassword, int permissions, int encryptionType, byte[] - documentId, PdfVersion version) + documentId, PdfVersion version, AbstractMacIntegrityProtector macContainer) : base(new PdfDictionary()) { + this.macContainer = macContainer; this.documentId = documentId; if (version != null && version.CompareTo(PdfVersion.PDF_2_0) >= 0) { permissions = FixAccessibilityPermissionPdf20(permissions); } + permissions = ConfigureAccessibilityPermissionsForMac(permissions); int revision = SetCryptoMode(encryptionType); switch (revision) { case STANDARD_ENCRYPTION_40: { @@ -159,6 +175,14 @@ public PdfEncryption(byte[] userPassword, byte[] ownerPassword, int permissions, securityHandler = handlerAes256; break; } + + case AES_GCM: { + StandardHandlerUsingAesGcm handlerAesGcm = new StandardHandlerUsingAesGcm(this.GetPdfObject(), userPassword + , ownerPassword, permissions, encryptMetadata, embeddedFilesOnly); + this.permissions = handlerAesGcm.GetPermissions(); + securityHandler = handlerAesGcm; + break; + } } } @@ -222,12 +246,20 @@ public PdfEncryption(byte[] userPassword, byte[] ownerPassword, int permissions, /// /// of the target document for encryption /// - public PdfEncryption(IX509Certificate[] certs, int[] permissions, int encryptionType, PdfVersion version) + /// + /// + /// + /// class for MAC integrity protection + /// + public PdfEncryption(IX509Certificate[] certs, int[] permissions, int encryptionType, PdfVersion version, + AbstractMacIntegrityProtector macContainer) : base(new PdfDictionary()) { - if (version != null && version.CompareTo(PdfVersion.PDF_2_0) >= 0) { - for (int i = 0; i < permissions.Length; i++) { + this.macContainer = macContainer; + for (int i = 0; i < permissions.Length; i++) { + if (version != null && version.CompareTo(PdfVersion.PDF_2_0) >= 0) { permissions[i] = FixAccessibilityPermissionPdf20(permissions[i]); } + permissions[i] = ConfigureAccessibilityPermissionsForMac(permissions[i]); } int revision = SetCryptoMode(encryptionType); switch (revision) { @@ -254,9 +286,35 @@ public PdfEncryption(IX509Certificate[] certs, int[] permissions, int encryption ); break; } + + case AES_GCM: { + securityHandler = new PubSecHandlerUsingAesGcm(this.GetPdfObject(), certs, permissions, encryptMetadata, embeddedFilesOnly + ); + break; + } } } + /// + /// Creates + /// + /// instance based on already existing standard encryption dictionary. + /// + /// + /// + /// + /// , which represents encryption dictionary + /// + /// + /// + /// byte[] + /// , which represents encryption password + /// + /// + /// original file ID, the first element in + /// + /// key of trailer + /// public PdfEncryption(PdfDictionary pdfDict, byte[] password, byte[] documentId) : base(pdfDict) { SetForbidRelease(); @@ -294,9 +352,46 @@ public PdfEncryption(PdfDictionary pdfDict, byte[] password, byte[] documentId) securityHandler = aes256Handler; break; } + + case AES_GCM: { + StandardHandlerUsingAesGcm aesGcmHandler = new StandardHandlerUsingAesGcm(this.GetPdfObject(), password); + permissions = aesGcmHandler.GetPermissions(); + encryptMetadata = aesGcmHandler.IsEncryptMetadata(); + securityHandler = aesGcmHandler; + break; + } } } + /// + /// Creates + /// + /// instance based on already existing public encryption dictionary. + /// + /// + /// + /// + /// , which represents encryption dictionary + /// + /// + /// the recipient private + /// + /// to the certificate + /// + /// + /// the recipient + /// + /// , which serves as recipient identifier + /// + /// + /// the certificate key provider id for + /// + /// + /// + /// + /// + /// the external decryption process to be used + /// public PdfEncryption(PdfDictionary pdfDict, IPrivateKey certificateKey, IX509Certificate certificate) : base(pdfDict) { SetForbidRelease(); @@ -325,6 +420,12 @@ public PdfEncryption(PdfDictionary pdfDict, IPrivateKey certificateKey, IX509Cer ); break; } + + case AES_GCM: { + securityHandler = new PubSecHandlerUsingAesGcm(this.GetPdfObject(), certificateKey, certificate, encryptMetadata + ); + break; + } } } @@ -350,30 +451,16 @@ public static byte[] GenerateNewDocumentId() { /// /// the first id /// whether the document has been changed or not - /// PdfObject containing the two entries. + /// PdfObject containing the two entries public static PdfObject CreateInfoId(byte[] id, bool modified) { if (modified) { - return CreateInfoId(id, GenerateNewDocumentId()); + return CreateInfoId(id, GenerateNewDocumentId(), false); } else { - return CreateInfoId(id, id); + return CreateInfoId(id, id, false); } } - /// Creates a PdfLiteral that contains an array of two id entries. - /// - /// Creates a PdfLiteral that contains an array of two id entries. These entries are both hexadecimal - /// strings containing 16 hex characters. The first entry is the original id, the second entry - /// should be different from the first one if the document has changed. - /// - /// the first id - /// the second id - /// PdfObject containing the two entries. - [System.ObsoleteAttribute(@"Use CreateInfoId(byte[], byte[], bool) instead")] - public static PdfObject CreateInfoId(byte[] firstId, byte[] secondId) { - return CreateInfoId(firstId, secondId, false); - } - /// Creates a PdfLiteral that contains an array of two id entries. /// /// Creates a PdfLiteral that contains an array of two id entries. These entries are both hexadecimal @@ -395,12 +482,12 @@ public static PdfObject CreateInfoId(byte[] firstId, byte[] secondId, bool prese } ByteBuffer buf = new ByteBuffer(90); buf.Append('[').Append('<'); - for (int k = 0; k < firstId.Length; ++k) { - buf.AppendHex(firstId[k]); + foreach (byte value in firstId) { + buf.AppendHex(value); } buf.Append('>').Append('<'); - for (int k = 0; k < secondId.Length; ++k) { - buf.AppendHex(secondId[k]); + foreach (byte b in secondId) { + buf.AppendHex(b); } buf.Append('>').Append(']'); return new PdfLiteral(buf.ToByteArray()); @@ -419,7 +506,7 @@ private static byte[] PadByteArrayTo16(byte[] documentId) { /// See ISO 32000-1, Table 22 for more details. /// /// the encryption permissions, an unsigned 32-bit quantity. - public virtual long? GetPermissions() { + public virtual int? GetPermissions() { return permissions; } @@ -430,6 +517,13 @@ public virtual int GetCryptoMode() { return cryptoMode; } + /// Gets encryption algorithm. + /// the encryption algorithm + /// + public virtual int GetEncryptionAlgorithm() { + return cryptoMode & EncryptionConstants.ENCRYPTION_MASK; + } + public virtual bool IsMetadataEncrypted() { return encryptMetadata; } @@ -581,6 +675,12 @@ private int SetCryptoMode(int mode, int length) { break; } + case EncryptionConstants.ENCRYPTION_AES_GCM: { + SetKeyLength(256); + revision = AES_GCM; + break; + } + default: { throw new PdfException(KernelExceptionMessageConstant.NO_VALID_ENCRYPTION_MODE); } @@ -656,6 +756,35 @@ private int ReadAndSetCryptoModeForStdHandler(PdfDictionary encDict) { break; } + case 7: { + // (ISO/TS 32003) The security handler defines the use of encryption + // and decryption in the same way as when the value of R is 6, and declares at least + // one crypt filter using the AESV4 method. + PdfDictionary cfDic = encDict.GetAsDictionary(PdfName.CF); + if (cfDic == null) { + throw new PdfException(KernelExceptionMessageConstant.CF_NOT_FOUND_ENCRYPTION); + } + cfDic = (PdfDictionary)cfDic.Get(PdfName.StdCF); + if (cfDic == null) { + throw new PdfException(KernelExceptionMessageConstant.STDCF_NOT_FOUND_ENCRYPTION); + } + if (PdfName.AESV4.Equals(cfDic.Get(PdfName.CFM))) { + cryptoMode = EncryptionConstants.ENCRYPTION_AES_GCM; + length = 256; + } + else { + throw new PdfException(KernelExceptionMessageConstant.NO_COMPATIBLE_ENCRYPTION_FOUND); + } + PdfBoolean em7 = encDict.GetAsBoolean(PdfName.EncryptMetadata); + if (em7 != null && !em7.GetValue()) { + cryptoMode |= EncryptionConstants.DO_NOT_ENCRYPT_METADATA; + } + if (embeddedFilesOnlyMode) { + cryptoMode |= EncryptionConstants.EMBEDDED_FILES_ONLY; + } + break; + } + default: { throw new PdfException(KernelExceptionMessageConstant.UNKNOWN_ENCRYPTION_TYPE_R).SetMessageParams(rValue); } @@ -666,7 +795,7 @@ private int ReadAndSetCryptoModeForStdHandler(PdfDictionary encDict) { private int ReadAndSetCryptoModeForPubSecHandler(PdfDictionary encDict) { int cryptoMode; - int length = 0; + int length; PdfNumber vValue = encDict.GetAsNumber(PdfName.V); if (vValue == null) { throw new PdfException(KernelExceptionMessageConstant.ILLEGAL_V_VALUE); @@ -729,6 +858,35 @@ private int ReadAndSetCryptoModeForPubSecHandler(PdfDictionary encDict) { break; } + case 6: { + // (ISO/TS 32003) The security handler defines the use of encryption + // and decryption in the same way as when the value of V is 5, and declares at least + // one crypt filter using the AESV4 method. + PdfDictionary cfDic = encDict.GetAsDictionary(PdfName.CF); + if (cfDic == null) { + throw new PdfException(KernelExceptionMessageConstant.CF_NOT_FOUND_ENCRYPTION); + } + cfDic = (PdfDictionary)cfDic.Get(PdfName.DefaultCryptFilter); + if (cfDic == null) { + throw new PdfException(KernelExceptionMessageConstant.DEFAULT_CRYPT_FILTER_NOT_FOUND_ENCRYPTION); + } + if (PdfName.AESV4.Equals(cfDic.Get(PdfName.CFM))) { + cryptoMode = EncryptionConstants.ENCRYPTION_AES_GCM; + length = 256; + } + else { + throw new PdfException(KernelExceptionMessageConstant.NO_COMPATIBLE_ENCRYPTION_FOUND); + } + PdfBoolean encrM = cfDic.GetAsBoolean(PdfName.EncryptMetadata); + if (encrM != null && !encrM.GetValue()) { + cryptoMode |= EncryptionConstants.DO_NOT_ENCRYPT_METADATA; + } + if (embeddedFilesOnlyMode) { + cryptoMode |= EncryptionConstants.EMBEDDED_FILES_ONLY; + } + break; + } + default: { throw new PdfException(KernelExceptionMessageConstant.UNKNOWN_ENCRYPTION_TYPE_V, vValue); } @@ -736,6 +894,15 @@ private int ReadAndSetCryptoModeForPubSecHandler(PdfDictionary encDict) { return SetCryptoMode(cryptoMode, length); } + private int ConfigureAccessibilityPermissionsForMac(int permissions) { + if (macContainer == null) { + return permissions | MAC_DISABLED; + } + else { + return permissions & MAC_ENABLED; + } + } + //\cond DO_NOT_DOCUMENT internal static bool ReadEmbeddedFilesOnlyFromEncryptDictionary(PdfDictionary encDict) { PdfName embeddedFilesFilter = encDict.GetAsName(PdfName.EFF); @@ -754,7 +921,7 @@ internal static bool ReadEmbeddedFilesOnlyFromEncryptDictionary(PdfDictionary en } //\endcond - private int FixAccessibilityPermissionPdf20(int permissions) { + private static int FixAccessibilityPermissionPdf20(int permissions) { // This bit was previously used to determine whether // content could be extracted for the purposes of accessibility, // however, that restriction has been deprecated in PDF 2.0. PDF @@ -763,5 +930,143 @@ private int FixAccessibilityPermissionPdf20(int permissions) { // earlier specifications. return permissions | EncryptionConstants.ALLOW_SCREENREADERS; } + +//\cond DO_NOT_DOCUMENT + internal virtual void CheckEncryptionRequirements(PdfDocument document) { + if (macContainer != null) { + if (document.GetPdfVersion() == null || document.GetPdfVersion().CompareTo(PdfVersion.PDF_2_0) < 0) { + throw new PdfException(KernelExceptionMessageConstant.MAC_FOR_PDF_2); + } + if (this.GetPdfObject().GetAsNumber(PdfName.V) != null && this.GetPdfObject().GetAsNumber(PdfName.V).IntValue + () < 5) { + throw new PdfException(KernelExceptionMessageConstant.MAC_FOR_ENCRYPTION_5); + } + } + int encryption = GetEncryptionAlgorithm(); + if (encryption < EncryptionConstants.ENCRYPTION_AES_256) { + VersionConforming.ValidatePdfVersionForDeprecatedFeatureLogWarn(document, PdfVersion.PDF_2_0, VersionConforming + .DEPRECATED_ENCRYPTION_ALGORITHMS); + } + else { + if (encryption == EncryptionConstants.ENCRYPTION_AES_256) { + PdfNumber r = GetPdfObject().GetAsNumber(PdfName.R); + if (r != null && r.IntValue() == 5) { + VersionConforming.ValidatePdfVersionForDeprecatedFeatureLogWarn(document, PdfVersion.PDF_2_0, VersionConforming + .DEPRECATED_AES256_REVISION); + } + } + else { + if (encryption == EncryptionConstants.ENCRYPTION_AES_GCM) { + VersionConforming.ValidatePdfVersionForNotSupportedFeatureLogError(document, PdfVersion.PDF_2_0, VersionConforming + .NOT_SUPPORTED_AES_GCM); + } + } + } + } +//\endcond + +//\cond DO_NOT_DOCUMENT + internal virtual void ConfigureEncryptionParametersFromWriter(PdfDocument document) { + if (macContainer != null) { + macContainer.SetFileEncryptionKey(securityHandler.GetMkey().Length == 0 ? securityHandler.GetNextObjectKey + () : securityHandler.GetMkey()); + document.GetDiContainer().GetInstance().LocateMacContainer(macContainer); + document.GetCatalog().AddDeveloperExtension(PdfDeveloperExtension.ISO_32004); + PdfString kdfSalt = GetPdfObject().GetAsString(PdfName.KDFSalt); + if (kdfSalt == null) { + GetPdfObject().Put(PdfName.KDFSalt, new PdfString(macContainer.GetKdfSalt()).SetHexWriting(true)); + GetPdfObject().SetModified(); + } + } + else { + document.GetCatalog().RemoveDeveloperExtension(PdfDeveloperExtension.ISO_32004); + } + if (GetEncryptionAlgorithm() == EncryptionConstants.ENCRYPTION_AES_GCM) { + document.GetCatalog().AddDeveloperExtension(PdfDeveloperExtension.ISO_32003); + } + else { + document.GetCatalog().RemoveDeveloperExtension(PdfDeveloperExtension.ISO_32003); + } + } +//\endcond + +//\cond DO_NOT_DOCUMENT + internal virtual AbstractMacIntegrityProtector GetMacContainer() { + return macContainer; + } +//\endcond + +//\cond DO_NOT_DOCUMENT + internal virtual void ConfigureEncryptionParametersFromReader(PdfDocument document, PdfDictionary trailer) { + PdfVersion sourceVersion = document.GetReader().headerPdfVersion; + PdfVersion destVersion = sourceVersion; + if (document.GetWriter() != null && document.GetWriter().GetProperties().pdfVersion != null) { + destVersion = document.GetWriter().GetProperties().pdfVersion; + } + try { + if (trailer.GetAsDictionary(PdfName.AuthCode) != null) { + macContainer = document.GetDiContainer().GetInstance().CreateMacIntegrityProtector(document + , trailer.GetAsDictionary(PdfName.AuthCode)); + macContainer.SetFileEncryptionKey(securityHandler.GetMkey().Length == 0 ? securityHandler.GetNextObjectKey + () : securityHandler.GetMkey()); + PdfString kdfSalt = GetPdfObject().GetAsString(PdfName.KDFSalt); + if (kdfSalt != null) { + macContainer.SetKdfSalt(kdfSalt.GetValueBytes()); + } + macContainer.ValidateMacToken(); + // Disable MAC for writing if explicitly requested. In append mode we cannot disable it because it will + // remove MAC protection from all previous revisions also for knowledgeable attackers + // TODO DEVSIX-8635 - Verify MAC permission and embed MAC in stamping mode for public key encryption + if (document.properties.disableMac && !document.properties.appendMode && securityHandler is StandardSecurityHandler + ) { + macContainer = null; + UpdateMacPermission(); + } + } + else { + if (PdfVersion.PDF_2_0.CompareTo(destVersion) <= 0 && permissions != null && (permissions & MAC_DISABLED) + == 0) { + // TODO DEVSIX-8635 - Verify MAC permission and embed MAC in stamping mode for public key encryption + throw new MacValidationException(KernelExceptionMessageConstant.MAC_PERMS_WITHOUT_MAC); + } + else { + if (!document.properties.disableMac && !document.properties.appendMode && securityHandler is StandardSecurityHandler + ) { + // TODO DEVSIX-8635 - Verify MAC permission and embed MAC in stamping mode for public key encryption + // This is the branch responsible for embedding MAC into the documents without MAC + // Do not embed MAC in append mode as it does not add extra security + PdfNumber vValue = GetPdfObject().GetAsNumber(PdfName.V); + if (vValue == null) { + throw new PdfException(KernelExceptionMessageConstant.ILLEGAL_V_VALUE); + } + int v = vValue.IntValue(); + // We do not support MAC for increasing PDF version to 2.0 (old encryption do not support it) + // and decreasing from 2.0 (not supported by the spec) + // v >= 5 stands for supported encryption algorithms for MAC being used + if (PdfVersion.PDF_2_0.CompareTo(destVersion) <= 0 && PdfVersion.PDF_2_0.CompareTo(sourceVersion) <= 0 && + v >= 5) { + macContainer = document.GetDiContainer().GetInstance().CreateMacIntegrityProtector(document + , EncryptionProperties.DEFAULT_MAC_PROPERTIES); + UpdateMacPermission(); + } + } + } + } + } + catch (MacValidationException exception) { + document.GetDiContainer().GetInstance().HandleMacValidationError(exception); + } + } +//\endcond + + private void UpdateMacPermission() { + // We don't parse permissions on reading for PubSec currently + if (permissions != null) { + permissions = ConfigureAccessibilityPermissionsForMac(permissions.Value); + if (securityHandler is StandardSecurityHandler) { + ((StandardSecurityHandler)securityHandler).SetPermissions(permissions.Value, this.GetPdfObject()); + } + } + } } } diff --git a/itext/itext.kernel/itext/kernel/pdf/PdfName.cs b/itext/itext.kernel/itext/kernel/pdf/PdfName.cs index a6663e7324..e2dde52a84 100644 --- a/itext/itext.kernel/itext/kernel/pdf/PdfName.cs +++ b/itext/itext.kernel/itext/kernel/pdf/PdfName.cs @@ -122,6 +122,8 @@ public class PdfName : PdfPrimitiveObject, IComparable public static readonly iText.Kernel.Pdf.PdfName AESV3 = CreateDirectName("AESV3"); + public static readonly iText.Kernel.Pdf.PdfName AESV4 = CreateDirectName("AESV4"); + public static readonly iText.Kernel.Pdf.PdfName AF = CreateDirectName("AF"); public static readonly iText.Kernel.Pdf.PdfName AFRelationship = CreateDirectName("AFRelationship"); @@ -200,8 +202,12 @@ public class PdfName : PdfPrimitiveObject, IComparable public static readonly iText.Kernel.Pdf.PdfName AsIs = CreateDirectName("AsIs"); + public static readonly iText.Kernel.Pdf.PdfName AttachedToSig = CreateDirectName("AttachedToSig"); + public static readonly iText.Kernel.Pdf.PdfName AuthEvent = CreateDirectName("AuthEvent"); + public static readonly iText.Kernel.Pdf.PdfName AuthCode = CreateDirectName("AuthCode"); + public static readonly iText.Kernel.Pdf.PdfName Author = CreateDirectName("Author"); public static readonly iText.Kernel.Pdf.PdfName B = CreateDirectName("B"); @@ -886,6 +892,8 @@ public class PdfName : PdfPrimitiveObject, IComparable public static readonly iText.Kernel.Pdf.PdfName K = CreateDirectName("K"); + public static readonly iText.Kernel.Pdf.PdfName KDFSalt = CreateDirectName("KDFSalt"); + public static readonly iText.Kernel.Pdf.PdfName Keywords = CreateDirectName("Keywords"); public static readonly iText.Kernel.Pdf.PdfName Kids = CreateDirectName("Kids"); @@ -976,6 +984,10 @@ public class PdfName : PdfPrimitiveObject, IComparable public static readonly iText.Kernel.Pdf.PdfName M = CreateDirectName("M"); + public static readonly iText.Kernel.Pdf.PdfName MAC = CreateDirectName("MAC"); + + public static readonly iText.Kernel.Pdf.PdfName MACLocation = CreateDirectName("MACLocation"); + public static readonly iText.Kernel.Pdf.PdfName MacExpertEncoding = CreateDirectName("MacExpertEncoding"); public static readonly iText.Kernel.Pdf.PdfName MacRomanEncoding = CreateDirectName("MacRomanEncoding"); @@ -1456,6 +1468,8 @@ public class PdfName : PdfPrimitiveObject, IComparable public static readonly iText.Kernel.Pdf.PdfName Signed = CreateDirectName("Signed"); + public static readonly iText.Kernel.Pdf.PdfName SigObjRef = CreateDirectName("SigObjRef"); + public static readonly iText.Kernel.Pdf.PdfName SigRef = CreateDirectName("SigRef"); public static readonly iText.Kernel.Pdf.PdfName Simplex = CreateDirectName("Simplex"); @@ -1494,6 +1508,8 @@ public class PdfName : PdfPrimitiveObject, IComparable public static readonly iText.Kernel.Pdf.PdfName Squiggly = CreateDirectName("Squiggly"); + public static readonly iText.Kernel.Pdf.PdfName Standalone = CreateDirectName("Standalone"); + public static readonly iText.Kernel.Pdf.PdfName St = CreateDirectName("St"); public static readonly iText.Kernel.Pdf.PdfName Stamp = CreateDirectName("Stamp"); @@ -1826,7 +1842,7 @@ public class PdfName : PdfPrimitiveObject, IComparable protected internal String value = null; /// map strings to all known static names - public static IDictionary staticNames; + public static readonly IDictionary staticNames; static PdfName() { staticNames = PdfNameLoader.LoadNames(); diff --git a/itext/itext.kernel/itext/kernel/pdf/PdfObject.cs b/itext/itext.kernel/itext/kernel/pdf/PdfObject.cs index 7dbef09345..1ca9f748a9 100644 --- a/itext/itext.kernel/itext/kernel/pdf/PdfObject.cs +++ b/itext/itext.kernel/itext/kernel/pdf/PdfObject.cs @@ -24,6 +24,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons; using iText.Kernel.Exceptions; using iText.Kernel.Utils; +using iText.Kernel.Validation.Context; namespace iText.Kernel.Pdf { public abstract class PdfObject { @@ -70,11 +71,11 @@ public abstract class PdfObject { /// protected internal const short ORIGINAL_OBJECT_STREAM = 1 << 4; - /// For internal usage only. + /// Marks objects that shall be written to the output document. /// - /// For internal usage only. Marks objects that shall be written to the output document. - /// Option is needed to build the correct PDF objects tree when closing the document. - /// As a result it avoids writing unused (removed) objects. + /// Marks objects that shall be written to the output document. Shouldn't be used on purpose + /// since this flag is handled internally: option is needed to build the correct PDF objects + /// tree when closing the document. As a result it avoids writing unused (removed) objects. /// protected internal const short MUST_BE_FLUSHED = 1 << 5; @@ -152,7 +153,7 @@ public void Flush(bool canBeInObjStm) { logger.LogInformation(iText.IO.Logs.IoLogMessageConstant.PDF_OBJECT_FLUSHING_NOT_PERFORMED); return; } - document.CheckIsoConformance(this, IsoKey.PDF_OBJECT); + document.CheckIsoConformance(new PdfObjectValidationContext(this)); document.FlushObject(this, canBeInObjStm && GetObjectType() != STREAM && GetObjectType() != INDIRECT_REFERENCE && GetIndirectReference().GetGenNumber() == 0); } diff --git a/itext/itext.kernel/itext/kernel/pdf/PdfOutline.cs b/itext/itext.kernel/itext/kernel/pdf/PdfOutline.cs index 06fd0f5637..94fa09ce69 100644 --- a/itext/itext.kernel/itext/kernel/pdf/PdfOutline.cs +++ b/itext/itext.kernel/itext/kernel/pdf/PdfOutline.cs @@ -35,10 +35,10 @@ namespace iText.Kernel.Pdf { /// public class PdfOutline { /// A flag for displaying the outline item’s text with italic font. - public static int FLAG_ITALIC = 1; + public const int FLAG_ITALIC = 1; /// A flag for displaying the outline item’s text with bold font. - public static int FLAG_BOLD = 2; + public const int FLAG_BOLD = 2; private IList children = new List(); diff --git a/itext/itext.kernel/itext/kernel/pdf/PdfOutputStream.cs b/itext/itext.kernel/itext/kernel/pdf/PdfOutputStream.cs index 8354e35b1e..0b6638f918 100644 --- a/itext/itext.kernel/itext/kernel/pdf/PdfOutputStream.cs +++ b/itext/itext.kernel/itext/kernel/pdf/PdfOutputStream.cs @@ -30,7 +30,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Kernel.Pdf.Filters; namespace iText.Kernel.Pdf { - public class PdfOutputStream : OutputStream { + public class PdfOutputStream : HighPrecisionOutputStream { private static readonly byte[] stream = ByteUtils.GetIsoBytes("stream\n"); private static readonly byte[] endstream = ByteUtils.GetIsoBytes("\nendstream"); diff --git a/itext/itext.kernel/itext/kernel/pdf/PdfPage.cs b/itext/itext.kernel/itext/kernel/pdf/PdfPage.cs index f6079d0203..49a637e39c 100644 --- a/itext/itext.kernel/itext/kernel/pdf/PdfPage.cs +++ b/itext/itext.kernel/itext/kernel/pdf/PdfPage.cs @@ -25,16 +25,18 @@ You should have received a copy of the GNU Affero General Public License using Microsoft.Extensions.Logging; using iText.Commons; using iText.Commons.Utils; -using iText.Kernel.Events; using iText.Kernel.Exceptions; using iText.Kernel.Geom; using iText.Kernel.Pdf.Action; using iText.Kernel.Pdf.Annot; +using iText.Kernel.Pdf.Event; using iText.Kernel.Pdf.Filespec; +using iText.Kernel.Pdf.Layer; using iText.Kernel.Pdf.Tagging; using iText.Kernel.Pdf.Tagutils; using iText.Kernel.Pdf.Xobject; using iText.Kernel.Utils; +using iText.Kernel.Validation.Context; using iText.Kernel.XMP; using iText.Kernel.XMP.Options; @@ -297,7 +299,9 @@ public virtual PdfStream NewContentStreamBefore() { /// /// Creates new /// - /// object and puts it at the end of Contents array + /// object and puts it at the end of + /// Contents + /// array /// (if Contents object is /// /// it will be replaced with one-element array). @@ -540,6 +544,24 @@ public virtual iText.Kernel.Pdf.PdfPage CopyTo(PdfDocument toDocument, IPdfPageE return CopyTo(page, toDocument, copier); } + /// Get all pdf layers stored under this page's annotations/xobjects/resources. + /// + /// Get all pdf layers stored under this page's annotations/xobjects/resources. + /// Note that it will include all layers, even those already stored under /OCProperties entry in catalog. + /// To get only unique layers, you can simply exclude ocgs, which already present in catalog. + /// + /// set of pdf layers, associated with this page. + public virtual ICollection GetPdfLayers() { + ICollection ocgs = OcgPropertiesCopier.GetOCGsFromPage(this); + ICollection result = new LinkedHashSet(); + foreach (PdfIndirectReference ocg in ocgs) { + if (ocg.GetRefersTo() != null && ocg.GetRefersTo().IsDictionary()) { + result.Add(new PdfLayer((PdfDictionary)ocg.GetRefersTo())); + } + } + return result; + } + /// Copies page as FormXObject to the specified document. /// a document to copy to. /// @@ -645,7 +667,7 @@ public virtual void Flush(bool flushResourcesContentStreams) { } } if (flushResourcesContentStreams) { - GetDocument().CheckIsoConformance(this, IsoKey.PAGE); + GetDocument().CheckIsoConformance(new PdfPageValidationContext(this)); FlushResourcesContentStreams(); } PdfArray annots = GetAnnots(false); @@ -1531,38 +1553,6 @@ public virtual iText.Kernel.Pdf.PdfPage Remove(PdfName key) { return this; } - /// - /// This flag is meaningful for the case, when page rotation is applied and ignorePageRotationForContent - /// is set to true. - /// - /// - /// This flag is meaningful for the case, when page rotation is applied and ignorePageRotationForContent - /// is set to true. NOTE: It is needed for the internal usage. - ///

    - /// This flag defines if inverse matrix (which rotates content into the opposite direction from page rotation - /// direction in order to give the impression of the not rotated text) is already applied to the page content stream. - /// See - /// - ///
    - /// true, if inverse matrix is already applied, false otherwise. - public virtual bool IsPageRotationInverseMatrixWritten() { - return pageRotationInverseMatrixWritten; - } - - /// NOTE: For internal usage! Use this method only if you know what you are doing. - /// - /// NOTE: For internal usage! Use this method only if you know what you are doing. - ///

    - /// This method is called when inverse matrix (which rotates content into the opposite direction from page rotation - /// direction in order to give the impression of the not rotated text) is applied to the page content stream. - /// See - /// - ///
    - public virtual void SetPageRotationInverseMatrixWritten() { - // this method specifically return void to discourage it's unintended usage - pageRotationInverseMatrixWritten = true; - } - /// Adds file associated with PDF page and identifies the relationship between them. /// /// Adds file associated with PDF page and identifies the relationship between them. @@ -1644,6 +1634,49 @@ internal virtual void ReleaseInstanceFields() { } //\endcond +//\cond DO_NOT_DOCUMENT + /// + /// Checks if page rotation inverse matrix (which rotates content into the opposite direction from page rotation + /// direction in order to give the impression of the not rotated text) is already applied to the page content stream. + /// + /// + /// Checks if page rotation inverse matrix (which rotates content into the opposite direction from page rotation + /// direction in order to give the impression of the not rotated text) is already applied to the page content stream. + /// See + /// + /// and + /// . + /// + /// + /// + /// + /// if inverse matrix is already applied, + /// + /// otherwise + /// + internal virtual bool IsPageRotationInverseMatrixWritten() { + return pageRotationInverseMatrixWritten; + } +//\endcond + +//\cond DO_NOT_DOCUMENT + /// + /// Specifies that page rotation inverse matrix (which rotates content into the opposite direction from page rotation + /// direction in order to give the impression of the not rotated text) is applied to the page content stream. + /// + /// + /// Specifies that page rotation inverse matrix (which rotates content into the opposite direction from page rotation + /// direction in order to give the impression of the not rotated text) is applied to the page content stream. + /// See + /// + /// and + /// . + /// + internal virtual void SetPageRotationInverseMatrixWritten() { + pageRotationInverseMatrixWritten = true; + } +//\endcond + protected internal override bool IsWrappedObjectMustBeIndirect() { return true; } diff --git a/itext/itext.kernel/itext/kernel/pdf/PdfPagesTree.cs b/itext/itext.kernel/itext/kernel/pdf/PdfPagesTree.cs index b78c4cf6fc..28f93c57e7 100644 --- a/itext/itext.kernel/itext/kernel/pdf/PdfPagesTree.cs +++ b/itext/itext.kernel/itext/kernel/pdf/PdfPagesTree.cs @@ -24,7 +24,9 @@ You should have received a copy of the GNU Affero General Public License using System.Collections.Generic; using Microsoft.Extensions.Logging; using iText.Commons; +using iText.Commons.Datastructures; using iText.Commons.Utils; +using iText.Kernel.DI.Pagetree; using iText.Kernel.Exceptions; namespace iText.Kernel.Pdf { @@ -41,13 +43,13 @@ internal class PdfPagesTree { private readonly int leafSize = DEFAULT_LEAF_SIZE; - private PdfPagesTree.NullUnlimitedList pageRefs; + private ISimpleList pageRefs; private IList parents; - private PdfPagesTree.NullUnlimitedList pages; + private ISimpleList pages; - private PdfDocument document; + private readonly PdfDocument document; private bool generated = false; @@ -63,14 +65,15 @@ internal class PdfPagesTree { /// public PdfPagesTree(PdfCatalog pdfCatalog) { this.document = pdfCatalog.GetDocument(); - this.pageRefs = new PdfPagesTree.NullUnlimitedList(); this.parents = new List(); - this.pages = new PdfPagesTree.NullUnlimitedList(); + IPageTreeListFactory pageTreeFactory = document.GetDiContainer().GetInstance(); if (pdfCatalog.GetPdfObject().ContainsKey(PdfName.Pages)) { PdfDictionary pages = pdfCatalog.GetPdfObject().GetAsDictionary(PdfName.Pages); if (pages == null) { throw new PdfException(KernelExceptionMessageConstant.INVALID_PAGE_STRUCTURE_PAGES_MUST_BE_PDF_DICTIONARY); } + this.pages = pageTreeFactory.CreateList(pages); + this.pageRefs = pageTreeFactory.CreateList(pages); this.root = new PdfPages(0, int.MaxValue, pages, null); parents.Add(this.root); for (int i = 0; i < this.root.GetCount(); i++) { @@ -81,6 +84,8 @@ public PdfPagesTree(PdfCatalog pdfCatalog) { else { this.root = null; this.parents.Add(new PdfPages(0, this.document)); + this.pages = pageTreeFactory.CreateList(null); + this.pageRefs = pageTreeFactory.CreateList(null); } } @@ -523,116 +528,6 @@ private void CorrectPdfPagesFromProperty(int index, int correction) { } } } - -//\cond DO_NOT_DOCUMENT - /// - /// The class represents a list which allows null elements, but doesn't allocate a memory for them, in the rest of - /// cases it behaves like usual - /// - /// and should have the same complexity (because keys are unique - /// integers, so collisions are impossible). - /// - /// - /// The class represents a list which allows null elements, but doesn't allocate a memory for them, in the rest of - /// cases it behaves like usual - /// - /// and should have the same complexity (because keys are unique - /// integers, so collisions are impossible). Class doesn't implement - /// List - /// interface because it provides - /// only methods which are in use in - /// - /// class. - /// - /// elements of the list - internal sealed class NullUnlimitedList { - private readonly IDictionary map = new Dictionary(); - - private int size = 0; - - // O(1) - public void Add(T element) { - if (element == null) { - size++; - return; - } - map.Put(size++, element); - } - - // In worth scenario O(n^2) but it is mostly impossible because keys shouldn't have - // collisions at all (they are integers). So in average should be O(n). - public void Add(int index, T element) { - if (index < 0 || index > size) { - return; - } - size++; - // Shifts the element currently at that position (if any) and any - // subsequent elements to the right (adds one to their indices). - T previous = map.Get(index); - for (int i = index + 1; i < size; i++) { - T currentToAdd = previous; - previous = map.Get(i); - this.Set(i, currentToAdd); - } - this.Set(index, element); - } - - // average O(1), worth O(n) (mostly impossible in case when keys are integers) - public T Get(int index) { - return map.Get(index); - } - - // average O(1), worth O(n) (mostly impossible in case when keys are integers) - public void Set(int index, T element) { - if (element == null) { - map.JRemove(index); - } - else { - map.Put(index, element); - } - } - - // O(n) - public int IndexOf(T element) { - if (element == null) { - for (int i = 0; i < size; i++) { - if (!map.ContainsKey(i)) { - return i; - } - } - return -1; - } - foreach (KeyValuePair entry in map) { - if (element.Equals(entry.Value)) { - return entry.Key; - } - } - return -1; - } - - // In worth scenario O(n^2) but it is mostly impossible because keys shouldn't have - // collisions at all (they are integers). So in average should be O(n). - public void Remove(int index) { - if (index < 0 || index >= size) { - return; - } - map.JRemove(index); - // Shifts any subsequent elements to the left (subtracts one from their indices). - T previous = map.Get(size - 1); - for (int i = size - 2; i >= index; i--) { - T current = previous; - previous = map.Get(i); - this.Set(i, current); - } - map.JRemove(--size); - } - - // O(1) - public int Size() { - return size; - } - } -//\endcond } //\endcond } diff --git a/itext/itext.kernel/itext/kernel/pdf/PdfReader.cs b/itext/itext.kernel/itext/kernel/pdf/PdfReader.cs index 4c0eb3f76c..6a364a79c6 100644 --- a/itext/itext.kernel/itext/kernel/pdf/PdfReader.cs +++ b/itext/itext.kernel/itext/kernel/pdf/PdfReader.cs @@ -65,8 +65,6 @@ public class PdfReader : IDisposable { //indicate nearest first Indirect reference object which includes current reading the object, using for PdfString decrypt private PdfIndirectReference currentIndirectReference; - private XMPMeta xmpMeta; - private PdfReader.XrefProcessor xrefProcessor = new PdfReader.XrefProcessor(); protected internal PdfTokenizer tokens; @@ -85,8 +83,6 @@ public class PdfReader : IDisposable { protected internal PdfDocument pdfDocument; - protected internal PdfAConformanceLevel pdfAConformanceLevel; - protected internal ReaderProperties properties; protected internal bool encrypted = false; @@ -99,6 +95,10 @@ public class PdfReader : IDisposable { protected internal bool xrefStm = false; + private XMPMeta xmpMeta; + + private PdfConformance pdfConformance; + /// Constructs a new PdfReader. /// source of bytes for the reader /// properties of the created reader @@ -615,8 +615,8 @@ public virtual bool IsOpenedWithFullPermission() { /// . /// See ISO 32000-1, Table 22 for more details. /// - /// the encryption permissions, an unsigned 32-bit quantity. - public virtual long GetPermissions() { + /// the encryption permissions. + public virtual int GetPermissions() { /* !pdfDocument.getXref().isReadingCompleted() can be used for encryption properties as well, * because decrypt object is initialized in private readDecryptObj method which is called in our code * in the next line after the setting isReadingCompleted line. This means that there's no way for users @@ -625,9 +625,9 @@ public virtual long GetPermissions() { if (pdfDocument == null || !pdfDocument.GetXref().IsReadingCompleted()) { throw new PdfException(KernelExceptionMessageConstant.DOCUMENT_HAS_NOT_BEEN_READ_YET); } - long perm = 0; + int perm = 0; if (encrypted && decrypt.GetPermissions() != null) { - perm = (long)decrypt.GetPermissions(); + perm = decrypt.GetPermissions().Value; } return perm; } @@ -651,37 +651,29 @@ public virtual int GetCryptoMode() { } } - /// Gets the declared PDF/A conformance level of the source document that is being read. + /// Gets the declared PDF conformance of the source document that is being read. /// - /// Gets the declared PDF/A conformance level of the source document that is being read. + /// Gets the declared PDF conformance of the source document that is being read. /// Note that this information is provided via XMP metadata and is not verified by iText. - /// - /// is lazy initialized. + /// Conformance is lazy initialized. /// It will be initialized during the first call of this method. /// - /// - /// conformance level of the source document, or - /// - /// if no PDF/A - /// conformance level information is specified. - /// - public virtual PdfAConformanceLevel GetPdfAConformanceLevel() { - if (pdfAConformanceLevel == null) { + /// conformance of the source document + public virtual PdfConformance GetPdfConformance() { + if (pdfConformance == null) { if (pdfDocument == null || !pdfDocument.GetXref().IsReadingCompleted()) { throw new PdfException(KernelExceptionMessageConstant.DOCUMENT_HAS_NOT_BEEN_READ_YET); } try { if (xmpMeta == null && pdfDocument.GetXmpMetadata() != null) { - xmpMeta = XMPMetaFactory.ParseFromBuffer(pdfDocument.GetXmpMetadata()); - } - if (xmpMeta != null) { - pdfAConformanceLevel = PdfAConformanceLevel.GetConformanceLevel(xmpMeta); + xmpMeta = pdfDocument.GetXmpMetadata(); } + pdfConformance = PdfConformance.GetConformance(xmpMeta); } catch (XMPException) { } } - return pdfAConformanceLevel; + return pdfConformance; } /// Computes user password if standard encryption handler is used with Standard40, Standard128 or AES128 encryption algorithm. @@ -778,6 +770,22 @@ public virtual bool IsEncrypted() { return encrypted; } + /// + /// Gets a copy of + /// + /// used to create this instance of + /// . + /// + /// + /// a copy of + /// + /// used to create this instance of + /// + /// + public virtual ReaderProperties GetPropertiesCopy() { + return new ReaderProperties(properties); + } + /// Parses the entire PDF protected internal virtual void ReadPdf() { String version = tokens.CheckPdfHeader(); @@ -804,8 +812,7 @@ protected internal virtual void ReadPdf() { } catch (Exception ex) { if (PdfReader.StrictnessLevel.CONSERVATIVE.IsStricter(this.GetStrictnessLevel())) { - ILogger logger = ITextLogManager.GetLogger(typeof(iText.Kernel.Pdf.PdfReader)); - logger.LogError(ex, iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT); + LogXrefException(ex); RebuildXref(); } else { @@ -917,8 +924,8 @@ protected internal virtual PdfObject ReadReference(bool readAsDirect) { return CreatePdfNullInstance(readAsDirect); } else { - throw new PdfException(KernelExceptionMessageConstant.INVALID_INDIRECT_REFERENCE, MessageFormatUtil.Format - ("{0} {1} R", reference.GetObjNumber(), reference.GetGenNumber())); + throw new PdfException(MessageFormatUtil.Format(KernelExceptionMessageConstant.INVALID_INDIRECT_REFERENCE, + reference.GetObjNumber(), reference.GetGenNumber()), reference); } } } @@ -1566,6 +1573,7 @@ private void ReadDecryptObj() { , filter)); } } + decrypt.ConfigureEncryptionParametersFromReader(pdfDocument, trailer); } private PdfObject ReadObject(PdfIndirectReference reference, bool fixXref) { @@ -1737,6 +1745,23 @@ private void ProcessXref(PdfXrefTable xrefTable) { } } + private static void LogXrefException(Exception ex) { + ILogger logger = ITextLogManager.GetLogger(typeof(iText.Kernel.Pdf.PdfReader)); + if (ex.InnerException != null) { + logger.LogError(MessageFormatUtil.Format(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE + , ex.InnerException.Message)); + } + else { + if (ex.Message != null) { + logger.LogError(MessageFormatUtil.Format(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT_WITH_CAUSE + , ex.Message)); + } + else { + logger.LogError(iText.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT); + } + } + } + protected internal class ReusableRandomAccessSource : IRandomAccessSource { private ByteBuffer buffer; diff --git a/itext/itext.kernel/itext/kernel/pdf/PdfResources.cs b/itext/itext.kernel/itext/kernel/pdf/PdfResources.cs index 947e5e1b1b..6cad98579b 100644 --- a/itext/itext.kernel/itext/kernel/pdf/PdfResources.cs +++ b/itext/itext.kernel/itext/kernel/pdf/PdfResources.cs @@ -25,6 +25,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Utils; using iText.Kernel.Font; using iText.Kernel.Pdf.Colorspace; +using iText.Kernel.Pdf.Colorspace.Shading; using iText.Kernel.Pdf.Extgstate; using iText.Kernel.Pdf.Xobject; @@ -335,16 +336,16 @@ public virtual PdfPattern GetPattern(PdfName name) { /// /// Adds - /// + /// /// object to the resources. /// /// /// the - /// + /// /// to add. /// /// added shading resource name. - public virtual PdfName AddShading(PdfShading shading) { + public virtual PdfName AddShading(AbstractPdfShading shading) { return AddResource(shading, shadingNamesGen); } @@ -363,9 +364,9 @@ public virtual PdfName AddShading(PdfDictionary shading) { return AddResource(shading, shadingNamesGen); } - public virtual PdfShading GetShading(PdfName name) { + public virtual AbstractPdfShading GetShading(PdfName name) { PdfObject shading = GetResourceObject(PdfName.Shading, name); - return shading is PdfDictionary ? PdfShading.MakeShading((PdfDictionary)shading) : null; + return shading is PdfDictionary ? AbstractPdfShading.MakeShading((PdfDictionary)shading) : null; } protected internal virtual bool IsReadOnly() { diff --git a/itext/itext.kernel/itext/kernel/pdf/PdfRevisionsReader.cs b/itext/itext.kernel/itext/kernel/pdf/PdfRevisionsReader.cs index 73fdedabcf..320e3de431 100644 --- a/itext/itext.kernel/itext/kernel/pdf/PdfRevisionsReader.cs +++ b/itext/itext.kernel/itext/kernel/pdf/PdfRevisionsReader.cs @@ -74,7 +74,7 @@ public virtual IList GetAllRevisions() { RandomAccessFileOrArray raf = reader.GetSafeFile(); WindowRandomAccessSource source = new WindowRandomAccessSource(raf.CreateSourceView(), 0, raf.Length()); using (Stream inputStream = new RASInputStream(source)) { - using (PdfReader newReader = new PdfReader(inputStream)) { + using (PdfReader newReader = new PdfReader(inputStream, reader.GetPropertiesCopy())) { using (PdfDocument newDocument = new PdfDocument(newReader, new DocumentProperties().SetEventCountingMetaInfo (metaInfo))) { newDocument.GetXref().UnmarkReadingCompleted(); diff --git a/itext/itext.kernel/itext/kernel/pdf/PdfUAConformanceLevel.cs b/itext/itext.kernel/itext/kernel/pdf/PdfUAConformance.cs similarity index 53% rename from itext/itext.kernel/itext/kernel/pdf/PdfUAConformanceLevel.cs rename to itext/itext.kernel/itext/kernel/pdf/PdfUAConformance.cs index 61be74685a..d3b4608b29 100644 --- a/itext/itext.kernel/itext/kernel/pdf/PdfUAConformanceLevel.cs +++ b/itext/itext.kernel/itext/kernel/pdf/PdfUAConformance.cs @@ -20,41 +20,37 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ +using System; + namespace iText.Kernel.Pdf { - /// - /// Implementation of - /// - /// interface for PDF/UA conformance level. - /// + /// PDF/UA is a conformance for PDF files that ensures the files are accessible to all users. /// - /// Implementation of - /// - /// interface for PDF/UA conformance level. - /// - /// PDF/UA is a conformance level for PDF files that ensures the files are accessible. - /// It contains an enumeration of all the PDF/UA conformance levels currently supported by iText. + /// PDF/UA is a conformance for PDF files that ensures the files are accessible to all users. + /// It contains an enumeration of all the PDF/UA conformance currently supported by iText. /// - public class PdfUAConformanceLevel : IConformanceLevel { - /// PDF/UA conformance level PDF/UA-1. - public static readonly iText.Kernel.Pdf.PdfUAConformanceLevel PDFUA_1 = new iText.Kernel.Pdf.PdfUAConformanceLevel - (1); + public sealed class PdfUAConformance { + /// PDF/UA-1 conformance + public static readonly iText.Kernel.Pdf.PdfUAConformance PDF_UA_1 = new iText.Kernel.Pdf.PdfUAConformance( + "1"); - private readonly int version; + private readonly String part; +//\cond DO_NOT_DOCUMENT /// /// Creates a new - /// + /// /// instance. /// - /// the version of the PDF/UA conformance level - private PdfUAConformanceLevel(int version) { - this.version = version; + /// the part of the PDF/UA conformance + internal PdfUAConformance(String part) { + this.part = part; } +//\endcond - /// Get the version of the PDF/UA conformance level. - /// the version of the PDF/UA conformance level - public virtual int GetVersion() { - return version; + /// Get the part of the PDF/UA conformance. + /// the part of the PDF/UA conformance + public String GetPart() { + return this.part; } } } diff --git a/itext/itext.kernel/itext/kernel/pdf/PdfWriter.cs b/itext/itext.kernel/itext/kernel/pdf/PdfWriter.cs index a109520257..d4c5ae5529 100644 --- a/itext/itext.kernel/itext/kernel/pdf/PdfWriter.cs +++ b/itext/itext.kernel/itext/kernel/pdf/PdfWriter.cs @@ -27,13 +27,16 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons; using iText.Commons.Utils; using iText.IO.Source; +using iText.Kernel.Exceptions; +using iText.Kernel.Mac; +using iText.Kernel.Pdf.Event; using iText.Kernel.Utils; namespace iText.Kernel.Pdf { public class PdfWriter : PdfOutputStream { - private static readonly byte[] obj = ByteUtils.GetIsoBytes(" obj\n"); + private static readonly byte[] OBJ = ByteUtils.GetIsoBytes(" obj\n"); - private static readonly byte[] endobj = ByteUtils.GetIsoBytes("\nendobj\n"); + private static readonly byte[] ENDOBJ = ByteUtils.GetIsoBytes("\nendobj\n"); protected internal WriterProperties properties; @@ -55,11 +58,13 @@ public class PdfWriter : PdfOutputStream { /// It stores hashes of the indirect reference from the source document and the corresponding /// indirect references of the copied objects from the new document. /// - private IDictionary copiedObjects = new LinkedDictionary(); + private readonly IDictionary copiedObjects = new LinkedDictionary + (); /// Is used in smart mode to serialize and store serialized objects content. - private SmartModePdfObjectsSerializer smartModeSerializer = new SmartModePdfObjectsSerializer(); + private readonly SmartModePdfObjectsSerializer smartModeSerializer = new SmartModePdfObjectsSerializer(); + + private Stream originalOutputStream; /// Create a PdfWriter writing to the passed File and with default writer properties. /// File to write to. @@ -73,6 +78,25 @@ public PdfWriter(Stream os) : this(os, new WriterProperties()) { } + /// + /// Creates + /// + /// instance, which writes to the passed + /// + /// , + /// using provided + /// . + /// + /// + /// + /// + /// in which writing should happen + /// + /// + /// + /// + /// to be used during the writing + /// public PdfWriter(Stream os, WriterProperties properties) : base(new CountOutputStream(FileUtil.WrapWithBufferedOutputStream(os))) { this.properties = properties; @@ -125,6 +149,12 @@ public virtual iText.Kernel.Pdf.PdfWriter SetCompressionLevel(int compressionLev return this; } + /// Gets defined pdf version for the document. + /// version for the document + public virtual PdfVersion GetPdfVersion() { + return properties.pdfVersion; + } + /// Gets the writer properties. /// /// The @@ -156,17 +186,43 @@ public virtual iText.Kernel.Pdf.PdfWriter SetSmartMode(bool smartMode) { return this; } + /// + /// Initializes + /// + /// object if any encryption is specified in + /// . + /// + /// + /// + /// + /// version of the document in question + /// protected internal virtual void InitCryptoIfSpecified(PdfVersion version) { EncryptionProperties encryptProps = properties.encryptionProperties; + // Suppress MAC properties for PDF version < 2.0 and old deprecated encryption algorithms + // if default ones have been passed to WriterProperties + int encryptionAlgorithm = crypto == null ? (encryptProps.encryptionAlgorithm & EncryptionConstants.ENCRYPTION_MASK + ) : crypto.GetEncryptionAlgorithm(); + if (document.properties.disableMac) { + encryptProps.macProperties = null; + } + if (encryptProps.macProperties == EncryptionProperties.DEFAULT_MAC_PROPERTIES) { + if (version == null || version.CompareTo(PdfVersion.PDF_2_0) < 0 || encryptionAlgorithm < EncryptionConstants + .ENCRYPTION_AES_256) { + encryptProps.macProperties = null; + } + } + AbstractMacIntegrityProtector mac = encryptProps.macProperties == null ? null : document.GetDiContainer(). + GetInstance().CreateMacIntegrityProtector(document, encryptProps.macProperties); if (properties.IsStandardEncryptionUsed()) { crypto = new PdfEncryption(encryptProps.userPassword, encryptProps.ownerPassword, encryptProps.standardEncryptPermissions , encryptProps.encryptionAlgorithm, ByteUtils.GetIsoBytes(this.document.GetOriginalDocumentId().GetValue - ()), version); + ()), version, mac); } else { if (properties.IsPublicKeyEncryptionUsed()) { crypto = new PdfEncryption(encryptProps.publicCertificates, encryptProps.publicKeyEncryptPermissions, encryptProps - .encryptionAlgorithm, version); + .encryptionAlgorithm, version, mac); } } } @@ -293,9 +349,9 @@ protected internal virtual void WriteToBody(PdfObject pdfObj) { .GetGenNumber()); } WriteInteger(pdfObj.GetIndirectReference().GetObjNumber()).WriteSpace().WriteInteger(pdfObj.GetIndirectReference - ().GetGenNumber()).WriteBytes(obj); + ().GetGenNumber()).WriteBytes(OBJ); Write(pdfObj); - WriteBytes(endobj); + WriteBytes(ENDOBJ); } /// Writes PDF header. @@ -370,6 +426,19 @@ protected internal virtual void FlushModifiedWaitingObjects(ICollectionGets the current object stream. /// object stream. @@ -410,6 +479,28 @@ internal virtual void FlushCopiedObjects(long docId) { } //\endcond +//\cond DO_NOT_DOCUMENT + internal virtual void EnableByteArrayWritingMode() { + if (IsByteArrayWritingMode()) { + throw new PdfException("Byte array writing mode is already enabled"); + } + else { + this.originalOutputStream = this.outputStream; + this.outputStream = new ByteArrayOutputStream(); + } + } +//\endcond + + private void CompleteByteArrayWritingMode() { + byte[] baos = ((ByteArrayOutputStream)GetOutputStream()).ToArray(); + originalOutputStream.Write(baos, 0, baos.Length); + originalOutputStream.Dispose(); + } + + private bool IsByteArrayWritingMode() { + return originalOutputStream != null; + } + private void MarkArrayContentToFlush(PdfArray array) { for (int i = 0; i < array.Size(); i++) { MarkObjectToFlush(array.Get(i, false)); diff --git a/itext/itext.kernel/itext/kernel/pdf/PdfXrefTable.cs b/itext/itext.kernel/itext/kernel/pdf/PdfXrefTable.cs index e4fef2114f..db481d0c72 100644 --- a/itext/itext.kernel/itext/kernel/pdf/PdfXrefTable.cs +++ b/itext/itext.kernel/itext/kernel/pdf/PdfXrefTable.cs @@ -25,11 +25,12 @@ You should have received a copy of the GNU Affero General Public License using System.Text; using Microsoft.Extensions.Logging; using iText.Commons; -using iText.Commons.Actions.Data; +using iText.Commons.Actions; using iText.Commons.Utils; using iText.IO.Source; -using iText.Kernel.Actions.Data; +using iText.Kernel.Actions.Events; using iText.Kernel.Exceptions; +using iText.Kernel.Validation.Context; namespace iText.Kernel.Pdf { /// A representation of a cross-referenced table of a PDF document. @@ -184,28 +185,6 @@ public virtual PdfIndirectReference Get(int index) { return xref[index]; } - /// Convenience method to write the fingerprint preceding the trailer. - /// - /// Convenience method to write the fingerprint preceding the trailer. - /// The fingerprint contains information on iText products used in the generation or manipulation - /// of an outputted PDF file. - /// - /// pdfDocument to write the fingerprint to - protected internal static void WriteKeyInfo(PdfDocument document) { - PdfWriter writer = document.GetWriter(); - ICollection products = document.GetFingerPrint().GetProducts(); - if (products.IsEmpty()) { - writer.WriteString(MessageFormatUtil.Format("%iText-{0}-no-registered-products\n", ITextCoreProductData.GetInstance - ().GetVersion())); - } - else { - foreach (ProductData productData in products) { - writer.WriteString(MessageFormatUtil.Format("%iText-{0}-{1}\n", productData.GetPublicProductName(), productData - .GetVersion())); - } - } - } - /// Creates next available indirect reference. /// /// is the current @@ -290,7 +269,7 @@ protected internal virtual void WriteXrefTableAndTrailer(PdfDocument document, P xref = null; return; } - document.CheckIsoConformance(this, IsoKey.XREF_TABLE); + document.CheckIsoConformance(new XrefTableValidationContext(this)); long startxref = writer.GetCurrentPos(); long xRefStmPos = -1; if (xrefStream != null) { @@ -303,7 +282,9 @@ protected internal virtual void WriteXrefTableAndTrailer(PdfDocument document, P int offsetSize = GetOffsetSize(Math.Max(startxref, Size())); xrefStream.Put(PdfName.W, new PdfArray(JavaUtil.ArraysAsList((PdfObject)new PdfNumber(1), new PdfNumber(offsetSize ), new PdfNumber(2)))); - xrefStream.Put(PdfName.Info, document.GetDocumentInfo().GetPdfObject()); + if (document.GetTrailer().Get(PdfName.Info) != null) { + xrefStream.Put(PdfName.Info, document.GetTrailer().Get(PdfName.Info)); + } xrefStream.Put(PdfName.Root, document.GetCatalog().GetPdfObject()); PdfArray index = new PdfArray(); foreach (int? section in sections) { @@ -400,7 +381,7 @@ protected internal virtual void WriteXrefTableAndTrailer(PdfDocument document, P writer.Write(document.GetTrailer()); writer.Write('\n'); } - WriteKeyInfo(document); + EventManager.GetInstance().OnEvent(new AddFingerPrintEvent(document)); writer.WriteString("startxref\n").WriteLong(startxref).WriteString("\n%%EOF\n"); xref = null; freeReferencesLinkedList.Clear(); diff --git a/itext/itext.kernel/itext/kernel/pdf/ReaderProperties.cs b/itext/itext.kernel/itext/kernel/pdf/ReaderProperties.cs index 80490c493a..5a81800442 100644 --- a/itext/itext.kernel/itext/kernel/pdf/ReaderProperties.cs +++ b/itext/itext.kernel/itext/kernel/pdf/ReaderProperties.cs @@ -22,21 +22,38 @@ You should have received a copy of the GNU Affero General Public License */ using iText.Commons.Bouncycastle.Cert; using iText.Commons.Bouncycastle.Crypto; +using iText.Commons.Utils; namespace iText.Kernel.Pdf { + /// The class representing various properties used to read PDF documents. public class ReaderProperties { - //added by ujihara for decryption protected internal byte[] password; - //added by Aiken Sam for certificate decryption protected internal IPrivateKey certificateKey; - //added by Aiken Sam for certificate decryption protected internal IX509Certificate certificate; - //added by Aiken Sam for certificate decryption protected internal MemoryLimitsAwareHandler memoryLimitsAwareHandler; + /// + /// Creates an instance of + /// . + /// + public ReaderProperties() { + } + +//\cond DO_NOT_DOCUMENT + // Empty constructor + internal ReaderProperties(iText.Kernel.Pdf.ReaderProperties readerProperties) { + this.password = readerProperties.password == null ? null : JavaUtil.ArraysCopyOf(readerProperties.password + , readerProperties.password.Length); + this.certificateKey = readerProperties.certificateKey; + this.certificate = readerProperties.certificate; + this.memoryLimitsAwareHandler = readerProperties.memoryLimitsAwareHandler == null ? null : readerProperties + .memoryLimitsAwareHandler.CreateNewInstance(); + } +//\endcond + /// Defines the password which will be used if the document is encrypted with standard encryption. /// /// Defines the password which will be used if the document is encrypted with standard encryption. @@ -48,7 +65,7 @@ public class ReaderProperties { /// /// instance ///
    - public virtual ReaderProperties SetPassword(byte[] password) { + public virtual iText.Kernel.Pdf.ReaderProperties SetPassword(byte[] password) { ClearEncryptionParams(); this.password = password; return this; @@ -74,8 +91,8 @@ public virtual ReaderProperties SetPassword(byte[] password) { /// /// instance /// - public virtual ReaderProperties SetPublicKeySecurityParams(IX509Certificate certificate, IPrivateKey certificateKey - ) { + public virtual iText.Kernel.Pdf.ReaderProperties SetPublicKeySecurityParams(IX509Certificate certificate, + IPrivateKey certificateKey) { ClearEncryptionParams(); this.certificate = certificate; this.certificateKey = certificateKey; @@ -97,18 +114,12 @@ public virtual ReaderProperties SetPublicKeySecurityParams(IX509Certificate cert /// /// instance /// - public virtual ReaderProperties SetPublicKeySecurityParams(IX509Certificate certificate) { + public virtual iText.Kernel.Pdf.ReaderProperties SetPublicKeySecurityParams(IX509Certificate certificate) { ClearEncryptionParams(); this.certificate = certificate; return this; } - private void ClearEncryptionParams() { - this.password = null; - this.certificate = null; - this.certificateKey = null; - } - /// Sets the memory handler which will be used to handle decompressed PDF streams. /// the memory handler which will be used to handle decompressed PDF streams /// @@ -117,10 +128,16 @@ private void ClearEncryptionParams() { /// /// instance /// - public virtual ReaderProperties SetMemoryLimitsAwareHandler(MemoryLimitsAwareHandler memoryLimitsAwareHandler + public virtual iText.Kernel.Pdf.ReaderProperties SetMemoryLimitsAwareHandler(MemoryLimitsAwareHandler memoryLimitsAwareHandler ) { this.memoryLimitsAwareHandler = memoryLimitsAwareHandler; return this; } + + private void ClearEncryptionParams() { + this.password = null; + this.certificate = null; + this.certificateKey = null; + } } } diff --git a/itext/itext.kernel/itext/kernel/pdf/StampingProperties.cs b/itext/itext.kernel/itext/kernel/pdf/StampingProperties.cs index cdfdc07918..797a416c55 100644 --- a/itext/itext.kernel/itext/kernel/pdf/StampingProperties.cs +++ b/itext/itext.kernel/itext/kernel/pdf/StampingProperties.cs @@ -26,6 +26,8 @@ public class StampingProperties : DocumentProperties { protected internal bool preserveEncryption = false; + protected internal bool disableMac = false; + public StampingProperties() { } @@ -33,7 +35,15 @@ public StampingProperties(iText.Kernel.Pdf.StampingProperties other) : base(other) { this.appendMode = other.appendMode; this.preserveEncryption = other.preserveEncryption; + this.disableMac = other.disableMac; + } + +//\cond DO_NOT_DOCUMENT + internal StampingProperties(DocumentProperties documentProperties) + : base(documentProperties) { + this.dependencies = documentProperties.dependencies; } +//\endcond /// Defines if the document will be edited in append mode. /// @@ -60,5 +70,22 @@ public virtual iText.Kernel.Pdf.StampingProperties PreserveEncryption() { this.preserveEncryption = true; return this; } + + /// Disables MAC token in the output PDF-2.0 document. + /// + /// Disables MAC token in the output PDF-2.0 document. + /// By default, MAC token will be embedded. + /// This property does not remove MAC token from existing document in append mode because it removes MAC protection + /// from all previous revisions also. + /// + /// + /// this + /// + /// instance + /// + public virtual iText.Kernel.Pdf.StampingProperties DisableMac() { + this.disableMac = true; + return this; + } } } diff --git a/itext/itext.kernel/itext/kernel/pdf/VersionConforming.cs b/itext/itext.kernel/itext/kernel/pdf/VersionConforming.cs index fa8a420c9c..58d43a1f19 100644 --- a/itext/itext.kernel/itext/kernel/pdf/VersionConforming.cs +++ b/itext/itext.kernel/itext/kernel/pdf/VersionConforming.cs @@ -34,6 +34,8 @@ public class VersionConforming { public const String DEPRECATED_XFA_FORMS = "XFA is deprecated in PDF 2.0. The XFA form will not be written to the document"; + public const String NOT_SUPPORTED_AES_GCM = "Advanced Encryption Standard-Galois/Counter Mode " + "(AES-GCM) encryption algorithm is supported starting from PDF 2.0."; + private static readonly ILogger logger = ITextLogManager.GetLogger(typeof(VersionConforming)); public static bool ValidatePdfVersionForDictEntry(PdfDocument document, PdfVersion expectedVersion, PdfName @@ -69,5 +71,26 @@ public static bool ValidatePdfVersionForDeprecatedFeatureLogError(PdfDocument do return false; } } + + /// Logs error message in case provided PDF document version is earlier than specified expected starting version. + /// + /// PDF document to check version for + /// starting version since which new feature is supported + /// error message to log + /// + /// boolean value specifying whether validation passed ( + /// + /// ) or failed ( + /// + /// ) + /// + public static bool ValidatePdfVersionForNotSupportedFeatureLogError(PdfDocument document, PdfVersion expectedStartVersion + , String notSupportedFeatureLogMessage) { + if (document.GetPdfVersion().CompareTo(expectedStartVersion) >= 0) { + return true; + } + logger.LogError(notSupportedFeatureLogMessage); + return false; + } } } diff --git a/itext/itext.kernel/itext/kernel/pdf/WriterProperties.cs b/itext/itext.kernel/itext/kernel/pdf/WriterProperties.cs index eba08ea1d1..a3f989fc02 100644 --- a/itext/itext.kernel/itext/kernel/pdf/WriterProperties.cs +++ b/itext/itext.kernel/itext/kernel/pdf/WriterProperties.cs @@ -22,6 +22,7 @@ You should have received a copy of the GNU Affero General Public License */ using iText.Bouncycastleconnector; using iText.Commons.Bouncycastle.Cert; +using iText.Kernel.Mac; namespace iText.Kernel.Pdf { public class WriterProperties { @@ -39,7 +40,9 @@ public class WriterProperties { protected internal bool addXmpMetadata; - protected internal bool addUAXmpMetadata; + protected internal PdfAConformance addPdfAXmpMetadata = null; + + protected internal PdfUAConformance addPdfUaXmpMetadata = null; protected internal PdfVersion pdfVersion; @@ -53,7 +56,6 @@ public class WriterProperties { public WriterProperties() { smartMode = false; - addUAXmpMetadata = false; compressionLevel = CompressionConstants.DEFAULT_COMPRESSION; isFullCompression = null; encryptionProperties = new EncryptionProperties(); @@ -113,6 +115,54 @@ public virtual iText.Kernel.Pdf.WriterProperties AddXmpMetadata() { return this; } + /// Adds PDF/A XMP metadata to the PDF document. + /// + /// Adds PDF/A XMP metadata to the PDF document. + /// + /// This method calls + /// + /// implicitly. + /// + /// NOTE: Calling this method only affects the XMP metadata, but doesn't enable any additional checks that the + /// created document meets all PDF/A requirements. When using this method make sure you are familiar with PDF/A + /// document requirements. If you are not sure, use dedicated iText PDF/A module to create valid PDF/A documents. + /// + /// the PDF/A conformance which will be added to XMP metadata + /// + /// this + /// + /// instance + /// + public virtual iText.Kernel.Pdf.WriterProperties AddPdfAXmpMetadata(PdfAConformance aConformance) { + this.addPdfAXmpMetadata = aConformance; + AddXmpMetadata(); + return this; + } + + /// Adds PDF/UA XMP metadata to the PDF document. + /// + /// Adds PDF/UA XMP metadata to the PDF document. + /// + /// This method calls + /// + /// implicitly. + /// + /// NOTE: Calling this method only affects the XMP metadata, but doesn't enable any additional checks that the + /// created document meets all PDF/UA requirements. When using this method make sure you are familiar with PDF/UA + /// document requirements. If you are not sure, use dedicated iText PDF/UA module to create valid PDF/UA documents. + /// + /// the PDF/UA conformance which will be added to XMP metadata + /// + /// this + /// + /// instance + /// + public virtual iText.Kernel.Pdf.WriterProperties AddPdfUaXmpMetadata(PdfUAConformance uaConformance) { + this.addPdfUaXmpMetadata = uaConformance; + AddXmpMetadata(); + return this; + } + /// Defines the level of compression for the document. /// /// Defines the level of compression for the document. @@ -213,7 +263,83 @@ public virtual iText.Kernel.Pdf.WriterProperties SetFullCompressionMode(bool ful /// public virtual iText.Kernel.Pdf.WriterProperties SetStandardEncryption(byte[] userPassword, byte[] ownerPassword , int permissions, int encryptionAlgorithm) { - encryptionProperties.SetStandardEncryption(userPassword, ownerPassword, permissions, encryptionAlgorithm); + return SetStandardEncryption(userPassword, ownerPassword, permissions, encryptionAlgorithm, EncryptionProperties + .DEFAULT_MAC_PROPERTIES); + } + + /// Sets the encryption options for the document. + /// + /// the user password. Can be null or of zero length, which is equal to + /// omitting the user password + /// + /// + /// the owner password. If it's null or empty, iText will generate + /// a random string to be used as the owner password + /// + /// + /// the user permissions + /// The open permissions for the document can be + /// + /// , + /// + /// , + /// + /// , + /// + /// , + /// + /// , + /// + /// , + /// + /// and + /// . + /// The permissions can be combined by ORing them + /// + /// + /// the type of encryption. It can be one of + /// + /// , + /// + /// , + /// + /// or + /// . + /// Optionally + /// + /// can be ORed + /// to output the metadata in cleartext. + /// + /// can be ORed as well. + /// Please be aware that the passed encryption types may override permissions: + /// + /// implicitly sets + /// + /// and + /// + /// as false; + /// + /// implicitly sets + /// + /// as false; + /// + /// + /// + /// + /// class to configure MAC integrity protection properties. + /// Pass + /// + /// if you want to disable MAC protection for any reason + /// + /// + /// this + /// + /// instance + /// + public virtual iText.Kernel.Pdf.WriterProperties SetStandardEncryption(byte[] userPassword, byte[] ownerPassword + , int permissions, int encryptionAlgorithm, MacProperties macProperties) { + encryptionProperties.SetStandardEncryption(userPassword, ownerPassword, permissions, encryptionAlgorithm, + macProperties); return this; } @@ -277,18 +403,93 @@ public virtual iText.Kernel.Pdf.WriterProperties SetStandardEncryption(byte[] us /// public virtual iText.Kernel.Pdf.WriterProperties SetPublicKeyEncryption(IX509Certificate[] certs, int[] permissions , int encryptionAlgorithm) { + return SetPublicKeyEncryption(certs, permissions, encryptionAlgorithm, EncryptionProperties.DEFAULT_MAC_PROPERTIES + ); + } + + /// Sets the certificate encryption options for the document. + /// + /// Sets the certificate encryption options for the document. An array of one or more public certificates + /// must be provided together with an array of the same size for the permissions for each certificate. + /// + /// the public certificates to be used for the encryption + /// + /// the user permissions for each of the certificates + /// The open permissions for the document can be + /// + /// , + /// + /// , + /// + /// , + /// + /// , + /// + /// , + /// + /// , + /// + /// and + /// . + /// The permissions can be combined by ORing them + /// + /// + /// the type of encryption. It can be one of + /// + /// , + /// + /// , + /// + /// or + /// . + /// Optionally + /// + /// can be ORed + /// to output the metadata in cleartext. + /// + /// can be ORed as well. + /// Please be aware that the passed encryption types may override permissions: + /// + /// implicitly sets + /// + /// and + /// + /// as false; + /// + /// implicitly sets + /// + /// as false; + /// + /// + /// + /// + /// class to configure MAC integrity protection properties. + /// Pass + /// + /// if you want to disable MAC protection for any reason + /// + /// + /// this + /// + /// instance + /// + public virtual iText.Kernel.Pdf.WriterProperties SetPublicKeyEncryption(IX509Certificate[] certs, int[] permissions + , int encryptionAlgorithm, MacProperties macProperties) { BouncyCastleFactoryCreator.GetFactory().IsEncryptionFeatureSupported(encryptionAlgorithm, true); - encryptionProperties.SetPublicKeyEncryption(certs, permissions, encryptionAlgorithm); + encryptionProperties.SetPublicKeyEncryption(certs, permissions, encryptionAlgorithm, macProperties); return this; } /// The /ID entry of a document contains an array with two entries. /// - /// The /ID entry of a document contains an array with two entries. The first one (initial id) represents the initial document id. + /// The /ID entry of a document contains an array with two entries. + /// The first one (initial id) represents the initial document id. /// It's a permanent identifier based on the contents of the file at the time it was originally created /// and does not change when the file is incrementally updated. - /// To help ensure the uniqueness of file identifiers, it is recommend to be computed by means of a message digest algorithm such as MD5. - /// iText will by default keep the existing initial id. But if you'd like you can set this id yourself using this setter. + /// To help ensure the uniqueness of file identifiers, + /// it is recommended to be computed by means of a message digest algorithm such as MD5. + /// iText will by default keep the existing initial id. + /// But if you'd like you can set this id yourself using this setter. /// /// the new initial document id /// @@ -318,25 +519,6 @@ public virtual iText.Kernel.Pdf.WriterProperties SetModifiedDocumentId(PdfString return this; } - /// This method marks the document as PDF/UA and sets related flags is XMPMetaData. - /// - /// This method marks the document as PDF/UA and sets related flags is XMPMetaData. - /// This method calls - /// - /// implicitly. - /// NOTE: iText does not validate PDF/UA, which means we don't check if created PDF meets all PDF/UA requirements. - /// Don't use this method if you are not familiar with PDF/UA specification in order to avoid creation of non-conformant PDF/UA file. - /// - /// - /// this - /// - /// instance - /// - public virtual iText.Kernel.Pdf.WriterProperties AddUAXmpMetadata() { - this.addUAXmpMetadata = true; - return AddXmpMetadata(); - } - //\cond DO_NOT_DOCUMENT internal virtual bool IsStandardEncryptionUsed() { return encryptionProperties.IsStandardEncryptionUsed(); diff --git a/itext/itext.kernel/itext/kernel/pdf/XmpMetaInfoConverter.cs b/itext/itext.kernel/itext/kernel/pdf/XmpMetaInfoConverter.cs index eef1c76e82..d5e1c5452f 100644 --- a/itext/itext.kernel/itext/kernel/pdf/XmpMetaInfoConverter.cs +++ b/itext/itext.kernel/itext/kernel/pdf/XmpMetaInfoConverter.cs @@ -34,10 +34,9 @@ private XmpMetaInfoConverter() { } //\cond DO_NOT_DOCUMENT - internal static void AppendMetadataToInfo(byte[] xmpMetadata, PdfDocumentInfo info) { - if (xmpMetadata != null) { + internal static void AppendMetadataToInfo(XMPMeta meta, PdfDocumentInfo info) { + if (meta != null) { try { - XMPMeta meta = XMPMetaFactory.ParseFromBuffer(xmpMetadata); XMPProperty title = meta.GetLocalizedText(XMPConst.NS_DC, PdfConst.Title, XMPConst.X_DEFAULT, XMPConst.X_DEFAULT ); if (title != null) { diff --git a/itext/itext.kernel/itext/kernel/pdf/canvas/PdfCanvas.cs b/itext/itext.kernel/itext/kernel/pdf/canvas/PdfCanvas.cs index 28cc67c692..057d1e4272 100644 --- a/itext/itext.kernel/itext/kernel/pdf/canvas/PdfCanvas.cs +++ b/itext/itext.kernel/itext/kernel/pdf/canvas/PdfCanvas.cs @@ -36,10 +36,12 @@ You should have received a copy of the GNU Affero General Public License using iText.Kernel.Pdf; using iText.Kernel.Pdf.Canvas.Wmf; using iText.Kernel.Pdf.Colorspace; +using iText.Kernel.Pdf.Colorspace.Shading; using iText.Kernel.Pdf.Extgstate; using iText.Kernel.Pdf.Layer; using iText.Kernel.Pdf.Tagutils; using iText.Kernel.Pdf.Xobject; +using iText.Kernel.Validation.Context; namespace iText.Kernel.Pdf.Canvas { /// PdfCanvas class represents an algorithm for writing data into content stream. @@ -248,10 +250,10 @@ public PdfCanvas(PdfPage page, bool wrapOldContent) page.NewContentStreamBefore().GetOutputStream().WriteBytes(ByteUtils.GetIsoBytes("q\n")); contentStream.GetOutputStream().WriteBytes(ByteUtils.GetIsoBytes("Q\n")); } - if (page.GetRotation() != 0 && page.IsIgnorePageRotationForContent() && (wrapOldContent || !page.IsPageRotationInverseMatrixWritten - ())) { + if (page.GetRotation() != 0 && page.IsIgnorePageRotationForContent() && (wrapOldContent || !PageContentRotationHelper + .IsPageRotationInverseMatrixWritten(page))) { ApplyRotation(page); - page.SetPageRotationInverseMatrixWritten(); + PageContentRotationHelper.SetPageRotationInverseMatrixWritten(page); } this.drawingOnPage = true; } @@ -316,7 +318,7 @@ public virtual void Release() { /// Saves graphics state. /// current canvas. public virtual iText.Kernel.Pdf.Canvas.PdfCanvas SaveState() { - document.CheckIsoConformance('q', IsoKey.CANVAS_STACK); + document.CheckIsoConformance(new CanvasStackValidationContext('q')); gsStack.Push(currentGs); currentGs = new CanvasGraphicsState(currentGs); contentStream.GetOutputStream().WriteBytes(q); @@ -326,7 +328,7 @@ public virtual iText.Kernel.Pdf.Canvas.PdfCanvas SaveState() { /// Restores graphics state. /// current canvas. public virtual iText.Kernel.Pdf.Canvas.PdfCanvas RestoreState() { - document.CheckIsoConformance('Q', IsoKey.CANVAS_STACK); + document.CheckIsoConformance(new CanvasStackValidationContext('Q')); if (gsStack.IsEmpty()) { throw new PdfException(KernelExceptionMessageConstant.UNBALANCED_SAVE_RESTORE_STATE_OPERATORS); } @@ -636,33 +638,33 @@ public virtual iText.Kernel.Pdf.Canvas.PdfCanvas ShowText(GlyphLine text) { public virtual iText.Kernel.Pdf.Canvas.PdfCanvas ShowText(GlyphLine text, IEnumerator iterator) { CheckDefaultDeviceGrayBlackColor(GetColorKeyForText()); - document.CheckIsoConformance(currentGs, IsoKey.FONT_GLYPHS, null, contentStream); + document.CheckIsoConformance(new FontGlyphsGStateValidationContext(currentGs, contentStream)); this.CheckIsoConformanceWritingOnContent(); PdfFont font; if ((font = currentGs.GetFont()) == null) { throw new PdfException(KernelExceptionMessageConstant.FONT_AND_SIZE_MUST_BE_SET_BEFORE_WRITING_ANY_TEXT, currentGs ); } - document.CheckIsoConformance(text.ToString(), IsoKey.FONT, null, null, currentGs.GetFont()); + document.CheckIsoConformance(new FontValidationContext(text.ToString(), currentGs.GetFont())); float fontSize = FontProgram.ConvertTextSpaceToGlyphSpace(currentGs.GetFontSize()); float charSpacing = currentGs.GetCharSpacing(); float scaling = currentGs.GetHorizontalScaling() / 100f; IList glyphLineParts = EnumeratorToList(iterator); for (int partIndex = 0; partIndex < glyphLineParts.Count; ++partIndex) { GlyphLine.GlyphLinePart glyphLinePart = glyphLineParts[partIndex]; - if (glyphLinePart.actualText != null) { + if (glyphLinePart.GetActualText() != null) { PdfDictionary properties = new PdfDictionary(); - properties.Put(PdfName.ActualText, new PdfString(glyphLinePart.actualText, PdfEncodings.UNICODE_BIG).SetHexWriting - (true)); + properties.Put(PdfName.ActualText, new PdfString(glyphLinePart.GetActualText(), PdfEncodings.UNICODE_BIG). + SetHexWriting(true)); BeginMarkedContent(PdfName.Span, properties); } else { - if (glyphLinePart.reversed) { + if (glyphLinePart.IsReversed()) { BeginMarkedContent(PdfName.ReversedChars); } } - int sub = glyphLinePart.start; - for (int i = glyphLinePart.start; i < glyphLinePart.end; i++) { + int sub = glyphLinePart.GetStart(); + for (int i = glyphLinePart.GetStart(); i < glyphLinePart.GetEnd(); i++) { Glyph glyph = text.Get(i); if (glyph.HasOffsets()) { if (i - 1 - sub >= 0) { @@ -726,21 +728,21 @@ public virtual iText.Kernel.Pdf.Canvas.PdfCanvas ShowText(GlyphLine text, IEnume sub = i + 1; } } - if (glyphLinePart.end - sub > 0) { - font.WriteText(text, sub, glyphLinePart.end - 1, contentStream.GetOutputStream()); + if (glyphLinePart.GetEnd() - sub > 0) { + font.WriteText(text, sub, glyphLinePart.GetEnd() - 1, contentStream.GetOutputStream()); contentStream.GetOutputStream().WriteBytes(Tj); } - if (glyphLinePart.actualText != null) { + if (glyphLinePart.GetActualText() != null) { EndMarkedContent(); } else { - if (glyphLinePart.reversed) { + if (glyphLinePart.IsReversed()) { EndMarkedContent(); } } - if (glyphLinePart.end > sub && partIndex + 1 < glyphLineParts.Count) { - contentStream.GetOutputStream().WriteFloat(GetSubrangeWidth(text, sub, glyphLinePart.end - 1), true).WriteSpace - ().WriteFloat(0).WriteSpace().WriteBytes(Td); + if (glyphLinePart.GetEnd() > sub && partIndex + 1 < glyphLineParts.Count) { + contentStream.GetOutputStream().WriteFloat(GetSubrangeWidth(text, sub, glyphLinePart.GetEnd() - 1), true). + WriteSpace().WriteFloat(0).WriteSpace().WriteBytes(Td); } } return this; @@ -809,7 +811,7 @@ private float GetWordSpacingAddition(Glyph glyph) { /// current canvas. public virtual iText.Kernel.Pdf.Canvas.PdfCanvas ShowText(PdfArray textArray) { CheckDefaultDeviceGrayBlackColor(GetColorKeyForText()); - document.CheckIsoConformance(currentGs, IsoKey.FONT_GLYPHS, null, contentStream); + document.CheckIsoConformance(new FontGlyphsGStateValidationContext(currentGs, contentStream)); this.CheckIsoConformanceWritingOnContent(); if (currentGs.GetFont() == null) { throw new PdfException(KernelExceptionMessageConstant.FONT_AND_SIZE_MUST_BE_SET_BEFORE_WRITING_ANY_TEXT, currentGs @@ -822,7 +824,7 @@ public virtual iText.Kernel.Pdf.Canvas.PdfCanvas ShowText(PdfArray textArray) { text.Append(obj); } } - document.CheckIsoConformance(text.ToString(), IsoKey.FONT, null, null, currentGs.GetFont()); + document.CheckIsoConformance(new FontValidationContext(text.ToString(), currentGs.GetFont())); contentStream.GetOutputStream().WriteBytes(ByteUtils.GetIsoBytes("[")); foreach (PdfObject obj in textArray) { if (obj.IsString()) { @@ -1102,7 +1104,7 @@ public virtual iText.Kernel.Pdf.Canvas.PdfCanvas Circle(double x, double y, doub /// Paints a shading object and adds it to the resources of this canvas /// a shading object to be painted /// current canvas. - public virtual iText.Kernel.Pdf.Canvas.PdfCanvas PaintShading(PdfShading shading) { + public virtual iText.Kernel.Pdf.Canvas.PdfCanvas PaintShading(AbstractPdfShading shading) { PdfName shadingName = resources.AddShading(shading); contentStream.GetOutputStream().Write((PdfObject)shadingName).WriteSpace().WriteBytes(sh); return this; @@ -1368,7 +1370,7 @@ public virtual iText.Kernel.Pdf.Canvas.PdfCanvas SetLineDash(float[] array, floa /// a PdfName containing a color metric /// current canvas. public virtual iText.Kernel.Pdf.Canvas.PdfCanvas SetRenderingIntent(PdfName renderingIntent) { - document.CheckIsoConformance(renderingIntent, IsoKey.RENDERING_INTENT); + document.CheckIsoConformance(new RenderingIntentValidationContext(renderingIntent)); if (renderingIntent.Equals(currentGs.GetRenderingIntent())) { return this; } @@ -1494,8 +1496,12 @@ public virtual iText.Kernel.Pdf.Canvas.PdfCanvas SetColor(PdfColorSpace colorSpa } } } - document.CheckIsoConformance(currentGs, fill ? IsoKey.FILL_COLOR : IsoKey.STROKE_COLOR, resources, contentStream - ); + if (fill) { + document.CheckIsoConformance(new FillColorValidationContext(currentGs, resources, contentStream)); + } + else { + document.CheckIsoConformance(new StrokeColorValidationContext(currentGs, resources, contentStream)); + } return this; } @@ -1692,6 +1698,7 @@ public virtual iText.Kernel.Pdf.Canvas.PdfCanvas EndLayer() { /// public virtual PdfXObject AddImageWithTransformationMatrix(ImageData image, float a, float b, float c, float d, float e, float f) { + CheckIsoConformanceWritingOnContent(); return AddImageWithTransformationMatrix(image, a, b, c, d, e, f, false); } @@ -1723,6 +1730,7 @@ public virtual PdfXObject AddImageWithTransformationMatrix(ImageData image, floa /// public virtual PdfXObject AddImageWithTransformationMatrix(ImageData image, float a, float b, float c, float d, float e, float f, bool asInline) { + CheckIsoConformanceWritingOnContent(); if (image.GetOriginalType() == ImageType.WMF) { WmfImageHelper wmf = new WmfImageHelper(image); PdfXObject xObject = wmf.CreateFormXObject(document); @@ -1771,6 +1779,7 @@ public virtual PdfXObject AddImageWithTransformationMatrix(ImageData image, floa /// "/> public virtual PdfXObject AddImageFittedIntoRectangle(ImageData image, iText.Kernel.Geom.Rectangle rect, bool asInline) { + CheckIsoConformanceWritingOnContent(); return AddImageWithTransformationMatrix(image, rect.GetWidth(), 0, 0, rect.GetHeight(), rect.GetX(), rect. GetY(), asInline); } @@ -1790,6 +1799,7 @@ public virtual PdfXObject AddImageFittedIntoRectangle(ImageData image, iText.Ker /// true if to add image as in-line /// the created imageXObject or null in case of in-line image (asInline = true) public virtual PdfXObject AddImageAt(ImageData image, float x, float y, bool asInline) { + CheckIsoConformanceWritingOnContent(); if (image.GetOriginalType() == ImageType.WMF) { WmfImageHelper wmf = new WmfImageHelper(image); PdfXObject xObject = wmf.CreateFormXObject(document); @@ -1833,6 +1843,7 @@ public virtual PdfXObject AddImageAt(ImageData image, float x, float y, bool asI /// public virtual iText.Kernel.Pdf.Canvas.PdfCanvas AddXObjectWithTransformationMatrix(PdfXObject xObject, float a, float b, float c, float d, float e, float f) { + CheckIsoConformanceWritingOnContent(); if (xObject is PdfFormXObject) { return AddFormWithTransformationMatrix((PdfFormXObject)xObject, a, b, c, d, e, f, true); } @@ -1856,6 +1867,7 @@ public virtual iText.Kernel.Pdf.Canvas.PdfCanvas AddXObjectWithTransformationMat /// the vertical position of the xObject /// the current canvas public virtual iText.Kernel.Pdf.Canvas.PdfCanvas AddXObjectAt(PdfXObject xObject, float x, float y) { + CheckIsoConformanceWritingOnContent(); if (xObject is PdfFormXObject) { return AddFormAt((PdfFormXObject)xObject, x, y); } @@ -1883,6 +1895,7 @@ public virtual iText.Kernel.Pdf.Canvas.PdfCanvas AddXObjectAt(PdfXObject xObject /// "/> public virtual iText.Kernel.Pdf.Canvas.PdfCanvas AddXObjectFittedIntoRectangle(PdfXObject xObject, iText.Kernel.Geom.Rectangle rect) { + CheckIsoConformanceWritingOnContent(); if (xObject is PdfFormXObject) { return AddFormFittedIntoRectangle((PdfFormXObject)xObject, rect); } @@ -1916,6 +1929,7 @@ public virtual iText.Kernel.Pdf.Canvas.PdfCanvas AddXObjectFittedIntoRectangle(P /// the xObject to add /// the current canvas public virtual iText.Kernel.Pdf.Canvas.PdfCanvas AddXObject(PdfXObject xObject) { + CheckIsoConformanceWritingOnContent(); if (xObject is PdfFormXObject) { return AddFormWithTransformationMatrix((PdfFormXObject)xObject, 1, 0, 0, 1, 0, 0, false); } @@ -1938,7 +1952,7 @@ public virtual iText.Kernel.Pdf.Canvas.PdfCanvas SetExtGState(PdfExtGState extGS } PdfName name = resources.AddExtGState(extGState); contentStream.GetOutputStream().Write(name).WriteSpace().WriteBytes(gs); - document.CheckIsoConformance(currentGs, IsoKey.EXTENDED_GRAPHICS_STATE, null, contentStream); + document.CheckIsoConformance(new ExtendedGStateValidationContext(currentGs, contentStream)); return this; } @@ -1981,7 +1995,7 @@ public virtual iText.Kernel.Pdf.Canvas.PdfCanvas BeginMarkedContent(PdfName tag, } Tuple2 tuple2 = new Tuple2(tag, properties); if (this.drawingOnPage) { - document.CheckIsoConformance(tagStructureStack, IsoKey.CANVAS_BEGIN_MARKED_CONTENT, null, null, tuple2); + document.CheckIsoConformance(new CanvasBmcValidationContext(tagStructureStack, tuple2)); } tagStructureStack.Push(tuple2); return this; @@ -2110,12 +2124,14 @@ public virtual PdfStream GetContentStream() { /// an element of the transformation matrix protected internal virtual void AddInlineImage(PdfImageXObject imageXObject, float a, float b, float c, float d, float e, float f) { - document.CheckIsoConformance(imageXObject.GetPdfObject(), IsoKey.INLINE_IMAGE, resources, contentStream); + document.CheckIsoConformance(new InlineImageValidationContext(imageXObject.GetPdfObject(), resources)); + CheckIsoConformanceWritingOnContent(); SaveState(); ConcatMatrix(a, b, c, d, e, f); PdfOutputStream os = contentStream.GetOutputStream(); os.WriteBytes(BI); byte[] imageBytes = imageXObject.GetPdfObject().GetBytes(false); + SaveColorSpaceToPageResourcesIfNeeded(imageXObject.GetPdfObject()); foreach (KeyValuePair entry in imageXObject.GetPdfObject().EntrySet()) { PdfName key = entry.Key; if (!PdfName.Type.Equals(key) && !PdfName.Subtype.Equals(key) && !PdfName.Length.Equals(key)) { @@ -2132,6 +2148,22 @@ protected internal virtual void AddInlineImage(PdfImageXObject imageXObject, flo RestoreState(); } + private void SaveColorSpaceToPageResourcesIfNeeded(PdfStream image) { + PdfObject colorSpace = image.Get(PdfName.ColorSpace); + //The colour space specified by the ColorSpace (or CS) entry shall be one of the standard device colour spaces + //(DeviceGray, DeviceRGB, or DeviceCMYK). + if (colorSpace == null || colorSpace.Equals(PdfName.DeviceGray) || colorSpace.Equals(PdfName.DeviceRGB) || + colorSpace.Equals(PdfName.DeviceCMYK)) { + return; + } + //PDF 1.2: the value of the ColorSpace entry may also be the name of a colour space in the ColorSpace + //subdictionary of the current resource dictionary. In this case, the name may designate any colour space + //that can be used with an image XObject. + PdfName name = resources.AddColorSpace(colorSpace); + image.Remove(PdfName.ColorSpace); + image.Put(PdfName.ColorSpace, name); + } + /// /// Adds /// @@ -2286,19 +2318,19 @@ private PdfStream EnsureStreamDataIsReadyToBeProcessed(PdfStream stream) { /// /// the text to write. private void ShowTextInt(String text) { - document.CheckIsoConformance(currentGs, IsoKey.FONT_GLYPHS, null, contentStream); + document.CheckIsoConformance(new FontGlyphsGStateValidationContext(currentGs, contentStream)); if (currentGs.GetFont() == null) { throw new PdfException(KernelExceptionMessageConstant.FONT_AND_SIZE_MUST_BE_SET_BEFORE_WRITING_ANY_TEXT, currentGs ); } this.CheckIsoConformanceWritingOnContent(); - document.CheckIsoConformance(text, IsoKey.FONT, null, null, currentGs.GetFont()); + document.CheckIsoConformance(new FontValidationContext(text, currentGs.GetFont())); currentGs.GetFont().WriteText(text, contentStream.GetOutputStream()); } private void CheckIsoConformanceWritingOnContent() { if (this.drawingOnPage) { - document.CheckIsoConformance(tagStructureStack, IsoKey.CANVAS_WRITING_CONTENT); + document.CheckIsoConformance(new CanvasWritingContentValidationContext(tagStructureStack)); } } @@ -2385,13 +2417,13 @@ private void CheckDefaultDeviceGrayBlackColor(PdfCanvas.CheckColorMode checkColo // But it's still important to do not check fill color if it's not used and vice versa if (currentGs.GetFillColor() == DeviceGray.BLACK && (checkColorMode == PdfCanvas.CheckColorMode.FILL || checkColorMode == PdfCanvas.CheckColorMode.FILL_AND_STROKE)) { - document.CheckIsoConformance(currentGs, IsoKey.FILL_COLOR, resources, contentStream); + document.CheckIsoConformance(new FillColorValidationContext(currentGs, resources, contentStream)); defaultDeviceGrayBlackColorCheckRequired = false; } else { if (currentGs.GetStrokeColor() == DeviceGray.BLACK && (checkColorMode == PdfCanvas.CheckColorMode.STROKE || checkColorMode == PdfCanvas.CheckColorMode.FILL_AND_STROKE)) { - document.CheckIsoConformance(currentGs, IsoKey.STROKE_COLOR, resources, contentStream); + document.CheckIsoConformance(new StrokeColorValidationContext(currentGs, resources, contentStream)); defaultDeviceGrayBlackColorCheckRequired = false; } } diff --git a/itext/itext.kernel/itext/kernel/pdf/canvas/parser/ParserGraphicsState.cs b/itext/itext.kernel/itext/kernel/pdf/canvas/parser/ParserGraphicsState.cs index f5fa2a54e1..506c22c1ab 100644 --- a/itext/itext.kernel/itext/kernel/pdf/canvas/parser/ParserGraphicsState.cs +++ b/itext/itext.kernel/itext/kernel/pdf/canvas/parser/ParserGraphicsState.cs @@ -62,6 +62,7 @@ public override void UpdateCtm(Matrix newCtm) { /// Intersects the current clipping path with the given path. /// /// Intersects the current clipping path with the given path. + /// /// Note: Coordinates of the given path should be in /// the transformed user space. /// @@ -80,17 +81,19 @@ public virtual void Clip(Path path, int fillingRule) { Path pathCopy = new Path(path); pathCopy.CloseAllSubpaths(); Clipper clipper = new Clipper(); - ClipperBridge.AddPath(clipper, clippingPath, PolyType.SUBJECT); - ClipperBridge.AddPath(clipper, pathCopy, PolyType.CLIP); + ClipperBridge clipperBridge = new ClipperBridge(clippingPath, pathCopy); + clipperBridge.AddPath(clipper, clippingPath, PolyType.SUBJECT); + clipperBridge.AddPath(clipper, pathCopy, PolyType.CLIP); PolyTree resultTree = new PolyTree(); clipper.Execute(ClipType.INTERSECTION, resultTree, PolyFillType.NON_ZERO, ClipperBridge.GetFillType(fillingRule )); - clippingPath = ClipperBridge.ConvertToPath(resultTree); + clippingPath = clipperBridge.ConvertToPath(resultTree); } /// Getter for the current clipping path. /// /// Getter for the current clipping path. + /// /// Note: The returned clipping path is in the transformed user space, so /// if you want to get it in default user space, apply transformation matrix ( /// @@ -104,6 +107,7 @@ public virtual Path GetClippingPath() { /// Sets the current clipping path to the specified path. /// /// Sets the current clipping path to the specified path. + /// /// Note:This method doesn't modify existing clipping path, /// it simply replaces it with the new one instead. /// diff --git a/itext/itext.kernel/itext/kernel/pdf/canvas/parser/clipperlib/ClipperBridge.cs b/itext/itext.kernel/itext/kernel/pdf/canvas/parser/clipperlib/ClipperBridge.cs index 822f43841d..54a4d5d66b 100644 --- a/itext/itext.kernel/itext/kernel/pdf/canvas/parser/clipperlib/ClipperBridge.cs +++ b/itext/itext.kernel/itext/kernel/pdf/canvas/parser/clipperlib/ClipperBridge.cs @@ -28,12 +28,12 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Kernel.Pdf.Canvas.Parser.ClipperLib { /// - /// This class contains variety of methods allowing to convert iText - /// abstractions into the abstractions of the Clipper library and vise versa. + /// This class contains a variety of methods allowing the conversion of iText + /// abstractions into abstractions of the Clipper library, and vice versa. /// /// - /// This class contains variety of methods allowing to convert iText - /// abstractions into the abstractions of the Clipper library and vise versa. + /// This class contains a variety of methods allowing the conversion of iText + /// abstractions into abstractions of the Clipper library, and vice versa. /// /// For example: /// @@ -55,6 +55,8 @@ namespace iText.Kernel.Pdf.Canvas.Parser.ClipperLib { /// /// public sealed class ClipperBridge { + private const long MAX_ALLOWED_VALUE = 0x3FFFFFFFFFFFFFL; + /// /// Since the clipper library uses integer coordinates, we should convert /// our floating point numbers into fixed point numbers by multiplying by @@ -64,15 +66,97 @@ public sealed class ClipperBridge { /// Since the clipper library uses integer coordinates, we should convert /// our floating point numbers into fixed point numbers by multiplying by /// this coefficient. Vary it to adjust the preciseness of the calculations. + /// + /// Note that if this value is specified, it will be used for all ClipperBridge instances and + /// dynamic float multiplier calculation will be disabled. + /// + public static double? floatMultiplier; + + private double approximatedFloatMultiplier = Math.Pow(10, 14); + + /// + /// Creates new + /// + /// instance with default float multiplier value which is 10^14. + /// + /// + /// Creates new + /// + /// instance with default float multiplier value which is 10^14. + /// + /// Since the clipper library uses integer coordinates, we should convert our floating point numbers into fixed + /// point numbers by multiplying by float multiplier coefficient. It is possible to vary it to adjust the preciseness + /// of the calculations: if static + /// + /// is specified, it will be used for all ClipperBridge + /// instances and default value will be ignored. /// - public static double floatMultiplier = Math - //TODO DEVSIX-5770 make this constant a single non-static configuration - .Pow(10, 14); + public ClipperBridge() { + } + + // Empty constructor. + /// + /// Creates new + /// + /// instance with adjusted float multiplier value. + /// + /// + /// Creates new + /// + /// instance with adjusted float multiplier value. This instance will work + /// correctly with the provided paths only. + /// + /// Since the clipper library uses integer coordinates, we should convert our floating point numbers into fixed + /// point numbers by multiplying by float multiplier coefficient. It is calculated automatically, however + /// it is possible to vary it to adjust the preciseness of the calculations: if static + /// + /// is + /// specified, it will be used for all ClipperBridge instances and automatic calculation won't work. + /// + /// paths to calculate multiplier coefficient to convert floating point numbers into fixed point numbers + /// + public ClipperBridge(params Path[] paths) { + if (floatMultiplier == null) { + IList pointsList = new List(); + foreach (Path path in paths) { + foreach (Subpath subpath in path.GetSubpaths()) { + if (!subpath.IsSinglePointClosed() && !subpath.IsSinglePointOpen()) { + pointsList.AddAll(subpath.GetPiecewiseLinearApproximation()); + } + } + } + CalculateFloatMultiplier(pointsList.ToArray(new Point[0])); + } + } - private ClipperBridge() { + /// + /// Creates new + /// + /// instance with adjusted float multiplier value. + /// + /// + /// Creates new + /// + /// instance with adjusted float multiplier value. This instance will work + /// correctly with the provided point only. + /// + /// Since the clipper library uses integer coordinates, we should convert our floating point numbers into fixed + /// point numbers by multiplying by float multiplier coefficient. It is calculated automatically, however + /// it is possible to vary it to adjust the preciseness of the calculations: if static + /// + /// is + /// specified, it will be used for all ClipperBridge instances and automatic calculation won't work. + /// + /// + /// points to calculate multiplier coefficient to convert floating point numbers + /// into fixed point numbers + /// + public ClipperBridge(params Point[][] points) { + if (floatMultiplier == null) { + CalculateFloatMultiplier(points); + } } - //empty constructor /// /// Converts Clipper library /// @@ -90,7 +174,7 @@ private ClipperBridge() { /// /// object /// - public static Path ConvertToPath(PolyTree result) { + public Path ConvertToPath(PolyTree result) { Path path = new Path(); PolyNode node = result.GetFirst(); while (node != null) { @@ -122,7 +206,7 @@ public static Path ConvertToPath(PolyTree result) { /// See /// . /// - public static void AddPath(Clipper clipper, Path path, PolyType polyType) { + public void AddPath(Clipper clipper, Path path, PolyType polyType) { foreach (Subpath subpath in path.GetSubpaths()) { if (!subpath.IsSinglePointClosed() && !subpath.IsSinglePointOpen()) { IList linearApproxPoints = subpath.GetPiecewiseLinearApproximation(); @@ -186,7 +270,7 @@ public static void AddPath(Clipper clipper, Path path, PolyType polyType) { /// /// s of the path. /// - public static IList AddPath(ClipperOffset offset, Path path, JoinType joinType, EndType endType) { + public IList AddPath(ClipperOffset offset, Path path, JoinType joinType, EndType endType) { IList degenerateSubpaths = new List(); foreach (Subpath subpath in path.GetSubpaths()) { if (subpath.IsDegenerate()) { @@ -226,10 +310,10 @@ public static IList AddPath(ClipperOffset offset, Path path, JoinType j /// /// objects. /// - public static IList ConvertToFloatPoints(IList points) { + public IList ConvertToFloatPoints(IList points) { IList convertedPoints = new List(points.Count); foreach (IntPoint point in points) { - convertedPoints.Add(new Point(point.X / floatMultiplier, point.Y / floatMultiplier)); + convertedPoints.Add(new Point(point.X / GetFloatMultiplier(), point.Y / GetFloatMultiplier())); } return convertedPoints; } @@ -251,10 +335,11 @@ public static IList ConvertToFloatPoints(IList points) { /// /// objects. /// - public static IList ConvertToLongPoints(IList points) { + public IList ConvertToLongPoints(IList points) { IList convertedPoints = new List(points.Count); foreach (Point point in points) { - convertedPoints.Add(new IntPoint(floatMultiplier * point.GetX(), floatMultiplier * point.GetY())); + convertedPoints.Add(new IntPoint(GetFloatMultiplier() * point.GetX(), GetFloatMultiplier() * point.GetY()) + ); } return convertedPoints; } @@ -372,7 +457,7 @@ public static PolyFillType GetFillType(int fillingRule) { /// path is a subject of clipping or a part of the clipping polygon. /// /// true if polygon path was successfully added, false otherwise. - public static bool AddPolygonToClipper(Clipper clipper, Point[] polyVertices, PolyType polyType) { + public bool AddPolygonToClipper(Clipper clipper, Point[] polyVertices, PolyType polyType) { return clipper.AddPath(new List(ConvertToLongPoints(new List(JavaUtil.ArraysAsList(polyVertices )))), polyType, true); } @@ -418,7 +503,7 @@ public static bool AddPolygonToClipper(Clipper clipper, Point[] polyVertices, Po /// to clipper path and added to the clipper instance. /// /// true if polyline path was successfully added, false otherwise. - public static bool AddPolylineSubjectToClipper(Clipper clipper, Point[] lineVertices) { + public bool AddPolylineSubjectToClipper(Clipper clipper, Point[] lineVertices) { return clipper.AddPath(new List(ConvertToLongPoints(new List(JavaUtil.ArraysAsList(lineVertices )))), PolyType.SUBJECT, false); } @@ -434,9 +519,8 @@ public static bool AddPolylineSubjectToClipper(Clipper clipper, Point[] lineVert /// object representing the rectangle. /// /// the width of the rectangle. - public static float LongRectCalculateWidth(IntRect rect) { - return (float)(Math.Abs(rect.left - rect.right) / iText.Kernel.Pdf.Canvas.Parser.ClipperLib.ClipperBridge. - floatMultiplier); + public float LongRectCalculateWidth(IntRect rect) { + return (float)(Math.Abs(rect.left - rect.right) / GetFloatMultiplier()); } /// @@ -450,13 +534,21 @@ public static float LongRectCalculateWidth(IntRect rect) { /// object representing the rectangle. /// /// the height of the rectangle. - public static float LongRectCalculateHeight(IntRect rect) { - return (float)(Math.Abs(rect.top - rect.bottom) / iText.Kernel.Pdf.Canvas.Parser.ClipperLib.ClipperBridge. - floatMultiplier); + public float LongRectCalculateHeight(IntRect rect) { + return (float)(Math.Abs(rect.top - rect.bottom) / GetFloatMultiplier()); + } + + /// Gets multiplier coefficient for converting our floating point numbers into fixed point numbers. + /// multiplier coefficient for converting our floating point numbers into fixed point numbers + public double GetFloatMultiplier() { + if (floatMultiplier == null) { + return approximatedFloatMultiplier; + } + return (double)floatMultiplier; } //\cond DO_NOT_DOCUMENT - internal static void AddContour(Path path, IList contour, bool close) { + internal void AddContour(Path path, IList contour, bool close) { IList floatContour = ConvertToFloatPoints(contour); Point point = floatContour[0]; path.MoveTo((float)point.GetX(), (float)point.GetY()); @@ -469,5 +561,20 @@ internal static void AddContour(Path path, IList contour, bool close) } } //\endcond + + private void CalculateFloatMultiplier(params Point[][] points) { + double maxPoint = 0; + foreach (Point[] pointsArray in points) { + foreach (Point point in pointsArray) { + maxPoint = Math.Max(maxPoint, Math.Abs(point.GetX())); + maxPoint = Math.Max(maxPoint, Math.Abs(point.GetY())); + } + } + // The significand of the double type is approximately 15 to 17 decimal digits for most platforms. + double epsilon = 1E-16; + if (maxPoint > epsilon) { + this.approximatedFloatMultiplier = Math.Floor(MAX_ALLOWED_VALUE / maxPoint); + } + } } } diff --git a/itext/itext.kernel/itext/kernel/pdf/canvas/parser/data/TextRenderInfo.cs b/itext/itext.kernel/itext/kernel/pdf/canvas/parser/data/TextRenderInfo.cs index 2f6ca883c8..dbe79fd3c3 100644 --- a/itext/itext.kernel/itext/kernel/pdf/canvas/parser/data/TextRenderInfo.cs +++ b/itext/itext.kernel/itext/kernel/pdf/canvas/parser/data/TextRenderInfo.cs @@ -100,11 +100,11 @@ public virtual String GetText() { if (text == null) { GlyphLine gl = gs.GetFont().DecodeIntoGlyphLine(@string); if (!IsReversedChars()) { - text = gl.ToUnicodeString(gl.start, gl.end); + text = gl.ToUnicodeString(gl.GetStart(), gl.GetEnd()); } else { - StringBuilder sb = new StringBuilder(gl.end - gl.start); - for (int i = gl.end - 1; i >= gl.start; i--) { + StringBuilder sb = new StringBuilder(gl.GetEnd() - gl.GetStart()); + for (int i = gl.GetEnd() - 1; i >= gl.GetStart(); i--) { sb.Append(gl.Get(i).GetUnicodeChars()); } text = sb.ToString(); @@ -528,7 +528,7 @@ private PdfString[] SplitString(PdfString @string) { // Number of bytes forming one glyph can be arbitrary from [1; 4] range IList strings = new List(); GlyphLine glyphLine = gs.GetFont().DecodeIntoGlyphLine(@string); - for (int i = glyphLine.start; i < glyphLine.end; i++) { + for (int i = glyphLine.GetStart(); i < glyphLine.GetEnd(); i++) { strings.Add(new PdfString(gs.GetFont().ConvertToBytes(glyphLine.Get(i)))); } return strings.ToArray(new PdfString[strings.Count]); diff --git a/itext/itext.kernel/itext/kernel/pdf/canvas/parser/listener/DefaultPdfTextLocation.cs b/itext/itext.kernel/itext/kernel/pdf/canvas/parser/listener/DefaultPdfTextLocation.cs index 51b56b049b..f7c3ea37b1 100644 --- a/itext/itext.kernel/itext/kernel/pdf/canvas/parser/listener/DefaultPdfTextLocation.cs +++ b/itext/itext.kernel/itext/kernel/pdf/canvas/parser/listener/DefaultPdfTextLocation.cs @@ -26,44 +26,51 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Kernel.Pdf.Canvas.Parser.Listener { /// This class acts as a default implementation of IPdfTextLocation public class DefaultPdfTextLocation : IPdfTextLocation { - private int pageNr; - private Rectangle rectangle; private String text; - public DefaultPdfTextLocation(int pageNr, Rectangle rect, String text) { - this.pageNr = pageNr; + /// Creates new pdf text location. + /// text rectangle on pdf canvas + /// actual text on designated area of canvas + public DefaultPdfTextLocation(Rectangle rect, String text) { this.rectangle = rect; this.text = text; } + /// public virtual Rectangle GetRectangle() { return rectangle; } + /// Sets text rectangle (occupied area) for this pdf text location. + /// new text rectangle + /// + /// this + /// DefaultPdfTextLocation + /// instance + /// public virtual iText.Kernel.Pdf.Canvas.Parser.Listener.DefaultPdfTextLocation SetRectangle(Rectangle rectangle ) { this.rectangle = rectangle; return this; } + /// public virtual String GetText() { return text; } + /// Sets text for this pdf text location. + /// new text + /// + /// this + /// DefaultPdfTextLocation + /// instance + /// public virtual iText.Kernel.Pdf.Canvas.Parser.Listener.DefaultPdfTextLocation SetText(String text) { this.text = text; return this; } - - public virtual int GetPageNumber() { - return pageNr; - } - - public virtual iText.Kernel.Pdf.Canvas.Parser.Listener.DefaultPdfTextLocation SetPageNr(int pageNr) { - this.pageNr = pageNr; - return this; - } } } diff --git a/itext/itext.kernel/itext/kernel/pdf/canvas/parser/listener/IPdfTextLocation.cs b/itext/itext.kernel/itext/kernel/pdf/canvas/parser/listener/IPdfTextLocation.cs index a3bea88439..d755e60b33 100644 --- a/itext/itext.kernel/itext/kernel/pdf/canvas/parser/listener/IPdfTextLocation.cs +++ b/itext/itext.kernel/itext/kernel/pdf/canvas/parser/listener/IPdfTextLocation.cs @@ -38,9 +38,5 @@ public interface IPdfTextLocation { /// the text String GetText(); - - /// Get the page number of the page on which the text is located - /// the page number, or 0 if no page number was set - int GetPageNumber(); } } diff --git a/itext/itext.kernel/itext/kernel/pdf/canvas/parser/listener/RegexBasedLocationExtractionStrategy.cs b/itext/itext.kernel/itext/kernel/pdf/canvas/parser/listener/RegexBasedLocationExtractionStrategy.cs index 5c5382d900..1bfeba95c8 100644 --- a/itext/itext.kernel/itext/kernel/pdf/canvas/parser/listener/RegexBasedLocationExtractionStrategy.cs +++ b/itext/itext.kernel/itext/kernel/pdf/canvas/parser/listener/RegexBasedLocationExtractionStrategy.cs @@ -31,12 +31,33 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Kernel.Pdf.Canvas.Parser.Listener { /// This class is designed to search for the occurrences of a regular expression and return the resultant rectangles. /// + /// + /// This class is designed to search for the occurrences of a regular expression and return the resultant rectangles. + /// Do note that this class holds all text locations and can't be used for processing multiple pages. + /// If you want to extract text from several pages of pdf document you have to create a new instance + /// of + /// + /// for each page. + /// + /// Here is an example of usage with new instance per each page: + /// + /// PdfDocument document = new PdfDocument(new PdfReader("...")); + /// for (int i = 1; i <= document.getNumberOfPages(); ++i) { + /// RegexBasedLocationExtractionStrategy extractionStrategy = new RegexBasedLocationExtractionStrategy(""); + /// PdfCanvasProcessor processor = new PdfCanvasProcessor(extractionStrategy); + /// processor.processPageContent(document.getPage(i)); + /// for (IPdfTextLocation location : extractionStrategy.getResultantLocations()) { + /// //process locations ... + /// } + /// } + /// + /// public class RegexBasedLocationExtractionStrategy : ILocationExtractionStrategy { private const float EPS = 1.0E-4F; - private Regex pattern; + private readonly Regex pattern; - private IList parseResult = new List(); + private readonly IList parseResult = new List(); public RegexBasedLocationExtractionStrategy(String regex) { this.pattern = iText.Commons.Utils.StringUtil.RegexCompile(regex); @@ -46,6 +67,7 @@ public RegexBasedLocationExtractionStrategy(Regex pattern) { this.pattern = pattern; } + /// public virtual ICollection GetResultantLocations() { // align characters in "logical" order JavaCollectionsUtil.Sort(parseResult, new TextChunkLocationBasedComparator(new DefaultTextChunkLocationComparator @@ -59,7 +81,7 @@ public virtual ICollection GetResultantLocations() { int? endIndex = GetEndIndex(txt.indexMap, mat.End() - 1); if (startIndex != null && endIndex != null && startIndex <= endIndex) { foreach (Rectangle r in ToRectangles(parseResult.SubList(startIndex.Value, endIndex.Value + 1))) { - retval.Add(new DefaultPdfTextLocation(0, r, mat.Group(0))); + retval.Add(new DefaultPdfTextLocation(r, mat.Group(0))); } } } @@ -74,27 +96,14 @@ public virtual ICollection GetResultantLocations() { return retval; } - private void RemoveDuplicates(IList sortedList) { - IPdfTextLocation lastItem = null; - int orgSize = sortedList.Count; - for (int i = orgSize - 1; i >= 0; i--) { - IPdfTextLocation currItem = sortedList[i]; - Rectangle currRect = currItem.GetRectangle(); - if (lastItem != null && currRect.EqualsWithEpsilon(lastItem.GetRectangle())) { - sortedList.Remove(currItem); - } - lastItem = currItem; - } - } - + /// public virtual void EventOccurred(IEventData data, EventType type) { - if (data is TextRenderInfo) { - parseResult.AddAll(ToCRI((TextRenderInfo)data)); - } + parseResult.AddAll(ToCRI((TextRenderInfo)data)); } + /// public virtual ICollection GetSupportedEvents() { - return null; + return JavaCollectionsUtil.Singleton(EventType.RENDER_TEXT); } /// @@ -197,6 +206,19 @@ protected internal virtual IList ToRectangles(IList sortedList) { + IPdfTextLocation lastItem = null; + int orgSize = sortedList.Count; + for (int i = orgSize - 1; i >= 0; i--) { + IPdfTextLocation currItem = sortedList[i]; + Rectangle currRect = currItem.GetRectangle(); + if (lastItem != null && currRect.EqualsWithEpsilon(lastItem.GetRectangle())) { + sortedList.Remove(currItem); + } + lastItem = currItem; + } + } + private static int? GetStartIndex(IDictionary indexMap, int index, String txt) { while (!indexMap.ContainsKey(index) && index < txt.Length) { index++; diff --git a/itext/itext.kernel/itext/kernel/pdf/canvas/parser/util/InlineImageParsingUtils.cs b/itext/itext.kernel/itext/kernel/pdf/canvas/parser/util/InlineImageParsingUtils.cs index e55d99d9fb..279259f97a 100644 --- a/itext/itext.kernel/itext/kernel/pdf/canvas/parser/util/InlineImageParsingUtils.cs +++ b/itext/itext.kernel/itext/kernel/pdf/canvas/parser/util/InlineImageParsingUtils.cs @@ -23,6 +23,9 @@ You should have received a copy of the GNU Affero General Public License using System; using System.Collections.Generic; using System.IO; +using Microsoft.Extensions.Logging; +using iText.Commons; +using iText.Commons.Utils; using iText.IO.Source; using iText.Kernel.Exceptions; using iText.Kernel.Pdf; @@ -31,7 +34,8 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Kernel.Pdf.Canvas.Parser.Util { /// Utility methods to help with processing of inline images public sealed class InlineImageParsingUtils { - private static readonly byte[] EI = new byte[] { (byte)'E', (byte)'I' }; + private static readonly ILogger LOGGER = ITextLogManager.GetLogger(typeof(iText.Kernel.Pdf.Canvas.Parser.Util.InlineImageParsingUtils + )); private InlineImageParsingUtils() { } @@ -142,12 +146,20 @@ internal static int GetComponentsPerPixel(PdfName colorSpaceName, PdfDictionary } } else { - if (PdfName.Indexed.Equals(colorSpace.GetAsName(0))) { + if (PdfName.Indexed.Equals(colorSpace.GetAsName(0)) || PdfName.CalGray.Equals(colorSpace.GetAsName(0)) || + PdfName.Pattern.Equals(colorSpace.GetAsName(0)) || PdfName.Separation.Equals(colorSpace.GetAsName(0))) { return 1; } + if (PdfName.CalRGB.Equals(colorSpace.GetAsName(0)) || PdfName.Lab.Equals(colorSpace.GetAsName(0))) { + return 3; + } if (PdfName.ICCBased.Equals(colorSpace.GetAsName(0))) { return colorSpace.GetAsStream(1).GetAsNumber(PdfName.N).IntValue(); } + if (PdfName.DeviceN.Equals(colorSpace.GetAsName(0))) { + //Checking colorants dict size + return colorSpace.GetAsArray(1).Size(); + } } } throw new InlineImageParsingUtils.InlineImageParseException(KernelExceptionMessageConstant.UNEXPECTED_COLOR_SPACE @@ -174,10 +186,10 @@ private static PdfDictionary ParseDictionary(PdfCanvasParser ps) { } dict.Put(resolvedKey, GetAlternateValue(resolvedKey, value)); } - int ch = ps.GetTokeniser().Read(); - if (!PdfTokenizer.IsWhitespace(ch)) { - throw new InlineImageParsingUtils.InlineImageParseException(KernelExceptionMessageConstant.UNEXPECTED_CHARACTER_FOUND_AFTER_ID_IN_INLINE_IMAGE - ).SetMessageParams(ch); + int ch = ps.GetTokeniser().Peek(); + //ASCIIHexDecode and ASCII85Decode are not required to have a whitespace after ID operator + if (PdfTokenizer.IsWhitespace(ch)) { + ps.GetTokeniser().Read(); } return dict; } @@ -303,46 +315,99 @@ private static byte[] ParseUnfilteredSamples(PdfDictionary imageDictionary, PdfD private static byte[] ParseSamples(PdfDictionary imageDictionary, PdfDictionary colorSpaceDic, PdfCanvasParser ps) { // by the time we get to here, we have already parsed the ID operator + //If image is unfiltered then we can calculate exact number of bytes it occupies if (!imageDictionary.ContainsKey(PdfName.Filter) && ImageColorSpaceIsKnown(imageDictionary, colorSpaceDic) ) { return ParseUnfilteredSamples(imageDictionary, colorSpaceDic, ps); } - // read all content until we reach an EI operator followed by whitespace. - // then decode the content stream to check that bytes that were parsed are really all image bytes - MemoryStream baos = new MemoryStream(); - int ch; - int found = 0; - PdfTokenizer tokeniser = ps.GetTokeniser(); - while ((ch = tokeniser.Read()) != -1) { - if (ch == 'E') { - // probably some bytes were preserved so write them - baos.Write(EI, 0, found); - // just preserve 'E' and do not write it immediately - found = 1; - } - else { - if (found == 1 && ch == 'I') { - // just preserve 'EI' and do not write it immediately - found = 2; - } - else { - if (found == 2 && PdfTokenizer.IsWhitespace(ch)) { - byte[] tmp = baos.ToArray(); - if (InlineImageStreamBytesAreComplete(tmp, imageDictionary)) { - return tmp; - } - } - // probably some bytes were preserved so write them - baos.Write(EI, 0, found); - baos.Write(ch); - found = 0; + PdfTokenizer tokenizer = ps.GetTokeniser(); + MemoryStream imageStream = new MemoryStream(); + int lastByte = tokenizer.Read(); + int currentByte = tokenizer.Read(); + // PDF spec is unclear about how to parse inline images. Should a whitespace + // appear before EI or not, so reading until EI or EOF. + while (currentByte != -1) { + if (lastByte == 'E' && currentByte == 'I' && PdfTokenizer.IsWhitespace(tokenizer.Peek()) && !FollowedByBinaryData + (tokenizer)) { + byte[] image = imageStream.ToArray(); + //Try to decode inline image as an additional safeguard and also to check for unsupported encodings + if (InlineImageStreamBytesAreComplete(image, imageDictionary)) { + return image; } } + imageStream.Write(lastByte); + lastByte = currentByte; + currentByte = tokenizer.Read(); } + //If EOF was encountered than image was not parsed throw new InlineImageParsingUtils.InlineImageParseException(KernelExceptionMessageConstant.CANNOT_FIND_IMAGE_DATA_OR_EI ); } + /// Check whether next several bytes of tokenizer contain binary data. + /// + /// Check whether next several bytes of tokenizer contain binary data. + /// This method probes 10 bytes and tries to find pdf operator in them. + /// + /// pdf tokenizer. + /// true if next 10 bytes is binary data, false if they're most likely pdf operators. + private static bool FollowedByBinaryData(PdfTokenizer tokenizer) { + byte[] testSequence = new byte[10]; + tokenizer.Peek(testSequence); + // We don't need to cleanup possible zeroes at the end, they aer whitespaces + // so can't break our logic in followedByBinaryData(byteArr) + bool isBinaryData = false; + int operatorStart = -1; + int operatorEnd = -1; + for (int i = 0; i < testSequence.Length; ++i) { + byte b = testSequence[i]; + //Checking for ASCII and Unicode common control characters except spaces: + // 0x00 0x10 + //0x00 NUL DLE + //0x01 SOH DC1 + //0x02 STX DC2 + //0x03 ETX DC3 + //0x04 EOT DC4 + //0x05 ENQ NAK + //0x06 ACK SYN + //0x07 BEL ETB + //0x08 BS CAN + //0x09 HT EM + //0x0A LF SUB + //0x0B VT ESC + //0x0C FF FS + //0x0D CR GS + //0x0E SO RS + //0x0F SI US + //0x7F DEL -> we have binary data + // Also if we have any byte > 0x7f (byte < 0) than we treat it also as binary data + // because pdf operators are in range 0x0 - 0x7f + if (b < 0x20 && !PdfTokenizer.IsWhitespace(b)) { + isBinaryData = true; + break; + } + // try to find PDF operator start and end + if (operatorStart == -1 && !PdfTokenizer.IsWhitespace(b)) { + operatorStart = i; + } + if (operatorStart != -1 && PdfTokenizer.IsWhitespace(b)) { + operatorEnd = i; + break; + } + } + if (operatorEnd == -1 && operatorStart != -1) { + operatorEnd = testSequence.Length; + } + //checking for any ASCII sequence here having less than 3 bytes length, because it most likely a pdf operator. + if (operatorEnd - operatorStart > 3) { + isBinaryData = true; + } + //if no operator start & end was found than it means only whitespaces were encountered or eof was reached + //earlier, so returning false in that case, it's highly unlikely inline image will have a lot of whitespaces in + //its data. + return isBinaryData; + } + private static bool ImageColorSpaceIsKnown(PdfDictionary imageDictionary, PdfDictionary colorSpaceDic) { PdfName cs = imageDictionary.GetAsName(PdfName.ColorSpace); if (cs == null || cs.Equals(PdfName.DeviceGray) || cs.Equals(PdfName.DeviceRGB) || cs.Equals(PdfName.DeviceCMYK @@ -367,14 +432,33 @@ private static bool InlineImageStreamBytesAreComplete(byte[] samples, PdfDiction try { IDictionary filters = new Dictionary(FilterHandlers.GetDefaultFilterHandlers ()); - filters.Put(PdfName.JBIG2Decode, new DoNothingFilter()); + // According to pdf spec JPXDecode and JBIG2Decode are unsupported for inline images encoding + filters.Put(PdfName.JPXDecode, new InlineImageParsingUtils.UnsupportedFilter(PdfName.JPXDecode.GetValue()) + ); + filters.Put(PdfName.JBIG2Decode, new InlineImageParsingUtils.UnsupportedFilter(PdfName.JBIG2Decode.GetValue + ())); filters.Put(PdfName.FlateDecode, new FlateDecodeStrictFilter()); PdfReader.DecodeBytes(samples, imageDictionary, filters); + return true; } catch (Exception) { return false; } - return true; + } + + private class UnsupportedFilter : IFilterHandler { + private readonly String name; + + public UnsupportedFilter(String name) { + this.name = name; + } + + public virtual byte[] Decode(byte[] b, PdfName filterName, PdfObject decodeParams, PdfDictionary streamDictionary + ) { + LOGGER.LogError(MessageFormatUtil.Format(KernelExceptionMessageConstant.UNSUPPORTED_ENCODING_FOR_INLINE_IMAGE + , name)); + throw new NotSupportedException(); + } } } } diff --git a/itext/itext.kernel/itext/kernel/pdf/canvas/wmf/MetaDo.cs b/itext/itext.kernel/itext/kernel/pdf/canvas/wmf/MetaDo.cs index de10bcd3da..28078b0083 100644 --- a/itext/itext.kernel/itext/kernel/pdf/canvas/wmf/MetaDo.cs +++ b/itext/itext.kernel/itext/kernel/pdf/canvas/wmf/MetaDo.cs @@ -177,10 +177,10 @@ public class MetaDo { public const int META_CREATEREGION = 0x06FF; /// PdfCanvas of the MetaDo object. - public PdfCanvas cb; + private readonly PdfCanvas cb; /// The InputMeta instance containing the data. - public InputMeta @in; + private readonly InputMeta @in; //\cond DO_NOT_DOCUMENT internal int left; diff --git a/itext/itext.kernel/itext/kernel/pdf/canvas/wmf/MetaState.cs b/itext/itext.kernel/itext/kernel/pdf/canvas/wmf/MetaState.cs index 8b73d579eb..677e374556 100644 --- a/itext/itext.kernel/itext/kernel/pdf/canvas/wmf/MetaState.cs +++ b/itext/itext.kernel/itext/kernel/pdf/canvas/wmf/MetaState.cs @@ -54,68 +54,68 @@ public class MetaState { public const int WINDING = 2; /// Stack of saved states. - public Stack savedStates; + private Stack savedStates; /// List of MetaObjects. - public IList MetaObjects; + private IList metaObjects; /// Current Point. - public Point currentPoint; + private Point currentPoint; /// Current Pen. - public MetaPen currentPen; + private MetaPen currentPen; /// Current Brush. - public MetaBrush currentBrush; + private MetaBrush currentBrush; /// Current Font. - public MetaFont currentFont; + private MetaFont currentFont; /// The current background color. /// The current background color. Default value is DeviceRgb#WHITE. - public Color currentBackgroundColor = ColorConstants.WHITE; + private Color currentBackgroundColor = ColorConstants.WHITE; /// Current text color. /// Current text color. Default value is DeviceRgb#BLACK. - public Color currentTextColor = ColorConstants.BLACK; + private Color currentTextColor = ColorConstants.BLACK; /// The current background mode. /// The current background mode. Default value is OPAQUE. - public int backgroundMode = OPAQUE; + private int backgroundMode = OPAQUE; /// Current polygon fill mode. /// Current polygon fill mode. Default value is ALTERNATE. - public int polyFillMode = ALTERNATE; + private int polyFillMode = ALTERNATE; /// Curent line join. /// Curent line join. Default value is 1. - public int lineJoin = 1; + private int lineJoin = 1; /// Current text alignment. - public int textAlign; + private int textAlign; /// Current offset for Wx. - public int offsetWx; + private int offsetWx; /// Current offset for Wy. - public int offsetWy; + private int offsetWy; /// Current extent for Wx. - public int extentWx; + private int extentWx; /// Current extent for Wy. - public int extentWy; + private int extentWy; /// Current x value for scaling. - public float scalingX; + private float scalingX; /// Current y value for scaling. - public float scalingY; + private float scalingY; /// Creates new MetaState public MetaState() { savedStates = new Stack(); - MetaObjects = new List(); + metaObjects = new List(); currentPoint = new Point(0, 0); currentPen = new MetaPen(); currentBrush = new MetaBrush(); @@ -132,7 +132,7 @@ public MetaState(iText.Kernel.Pdf.Canvas.Wmf.MetaState state) { /// state to copy public virtual void SetMetaState(iText.Kernel.Pdf.Canvas.Wmf.MetaState state) { savedStates = state.savedStates; - MetaObjects = state.MetaObjects; + metaObjects = state.metaObjects; currentPoint = state.currentPoint; currentPen = state.currentPen; currentBrush = state.currentBrush; @@ -154,20 +154,20 @@ public virtual void SetMetaState(iText.Kernel.Pdf.Canvas.Wmf.MetaState state) { /// Add a MetaObject to the State. /// MetaObject to be added public virtual void AddMetaObject(MetaObject @object) { - for (int k = 0; k < MetaObjects.Count; ++k) { - if (MetaObjects[k] == null) { - MetaObjects[k] = @object; + for (int k = 0; k < metaObjects.Count; ++k) { + if (metaObjects[k] == null) { + metaObjects[k] = @object; return; } } - MetaObjects.Add(@object); + metaObjects.Add(@object); } /// Select the MetaObject at the specified index and prepare the PdfCanvas. /// position of the MetaObject /// PdfCanvas to prepare public virtual void SelectMetaObject(int index, PdfCanvas cb) { - MetaObject obj = MetaObjects[index]; + MetaObject obj = metaObjects[index]; if (obj == null) { return; } @@ -236,7 +236,7 @@ public virtual void SelectMetaObject(int index, PdfCanvas cb) { /// Deletes the MetaObject at the specified index. /// index of the MetaObject to delete public virtual void DeleteMetaObject(int index) { - MetaObjects[index] = null; + metaObjects[index] = null; } /// Saves the state of this MetaState object. diff --git a/itext/itext.kernel/itext/kernel/pdf/colorspace/PdfPattern.cs b/itext/itext.kernel/itext/kernel/pdf/colorspace/PdfPattern.cs index b28109e1fc..ce55ed1028 100644 --- a/itext/itext.kernel/itext/kernel/pdf/colorspace/PdfPattern.cs +++ b/itext/itext.kernel/itext/kernel/pdf/colorspace/PdfPattern.cs @@ -23,6 +23,7 @@ You should have received a copy of the GNU Affero General Public License using System; using iText.Kernel.Geom; using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Colorspace.Shading; namespace iText.Kernel.Pdf.Colorspace { /// @@ -440,11 +441,11 @@ public Shading(PdfDictionary pdfObject) /// Creates a new instance of Shading Pattern. /// /// the - /// + /// /// that specifies the details of a particular /// gradient fill /// - public Shading(PdfShading shading) + public Shading(AbstractPdfShading shading) : base(new PdfDictionary()) { GetPdfObject().Put(PdfName.Type, PdfName.Pattern); GetPdfObject().Put(PdfName.PatternType, new PdfNumber(2)); @@ -453,11 +454,11 @@ public Shading(PdfShading shading) /// /// Gets the dictionary of the pattern's - /// . + /// . /// /// /// the dictionary of the pattern's - /// + /// /// public virtual PdfDictionary GetShading() { return (PdfDictionary)GetPdfObject().Get(PdfName.Shading); @@ -465,15 +466,15 @@ public virtual PdfDictionary GetShading() { /// /// Sets the - /// + /// /// that specifies the details of a particular gradient fill. /// /// /// the - /// + /// /// that specifies the details of a particular gradient fill /// - public virtual void SetShading(PdfShading shading) { + public virtual void SetShading(AbstractPdfShading shading) { GetPdfObject().Put(PdfName.Shading, shading.GetPdfObject()); SetModified(); } @@ -481,7 +482,7 @@ public virtual void SetShading(PdfShading shading) { /// Sets the dictionary which specifies the details of a particular gradient fill. /// /// the dictionary of the pattern's - /// + /// /// public virtual void SetShading(PdfDictionary shading) { GetPdfObject().Put(PdfName.Shading, shading); diff --git a/itext/itext.kernel/itext/kernel/pdf/colorspace/PdfShading.cs b/itext/itext.kernel/itext/kernel/pdf/colorspace/PdfShading.cs deleted file mode 100644 index a3ed2dbba5..0000000000 --- a/itext/itext.kernel/itext/kernel/pdf/colorspace/PdfShading.cs +++ /dev/null @@ -1,1955 +0,0 @@ -/* -This file is part of the iText (R) project. -Copyright (c) 1998-2024 Apryse Group NV -Authors: Apryse Software. - -This program is offered under a commercial and under the AGPL license. -For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. - -AGPL licensing: -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . -*/ -using System; -using iText.Kernel.Exceptions; -using iText.Kernel.Pdf; -using iText.Kernel.Pdf.Function; - -namespace iText.Kernel.Pdf.Colorspace { - /// The abstract PdfShading class that represents the Shading Dictionary PDF object. - public abstract class PdfShading : PdfObjectWrapper { -//\cond DO_NOT_DOCUMENT - /// constants of shading type (see ISO-320001 Table 78) - internal sealed class ShadingType { - /// The int value of function-based shading type - public const int FUNCTION_BASED = 1; - - /// The int value of axial shading type - public const int AXIAL = 2; - - /// The int value of radial shading type - public const int RADIAL = 3; - - /// The int value of free-form Gouraud-shaded triangle mesh shading type - public const int FREE_FORM_GOURAUD_SHADED_TRIANGLE_MESH = 4; - - /// The int value of lattice-form Gouraud-shaded triangle mesh shading type - public const int LATTICE_FORM_GOURAUD_SHADED_TRIANGLE_MESH = 5; - - /// The int value of coons patch meshes shading type - public const int COONS_PATCH_MESH = 6; - - /// The int value of tensor-product patch meshes shading type - public const int TENSOR_PRODUCT_PATCH_MESH = 7; - - private ShadingType() { - } - } -//\endcond - - /// - /// Creates the - /// - /// object from the existing - /// - /// with corresponding type. - /// - /// - /// - /// - /// from which the - /// - /// object will be created. - /// - /// - /// Created - /// - /// object. - /// - public static PdfShading MakeShading(PdfDictionary shadingDictionary) { - if (!shadingDictionary.ContainsKey(PdfName.ShadingType)) { - throw new PdfException(KernelExceptionMessageConstant.SHADING_TYPE_NOT_FOUND); - } - if (!shadingDictionary.ContainsKey(PdfName.ColorSpace)) { - throw new PdfException(KernelExceptionMessageConstant.COLOR_SPACE_NOT_FOUND); - } - PdfShading shading; - switch (shadingDictionary.GetAsNumber(PdfName.ShadingType).IntValue()) { - case PdfShading.ShadingType.FUNCTION_BASED: { - shading = new PdfShading.FunctionBased(shadingDictionary); - break; - } - - case PdfShading.ShadingType.AXIAL: { - shading = new PdfShading.Axial(shadingDictionary); - break; - } - - case PdfShading.ShadingType.RADIAL: { - shading = new PdfShading.Radial(shadingDictionary); - break; - } - - case PdfShading.ShadingType.FREE_FORM_GOURAUD_SHADED_TRIANGLE_MESH: { - if (!shadingDictionary.IsStream()) { - throw new PdfException(KernelExceptionMessageConstant.UNEXPECTED_SHADING_TYPE); - } - shading = new PdfShading.FreeFormGouraudShadedTriangleMesh((PdfStream)shadingDictionary); - break; - } - - case PdfShading.ShadingType.LATTICE_FORM_GOURAUD_SHADED_TRIANGLE_MESH: { - if (!shadingDictionary.IsStream()) { - throw new PdfException(KernelExceptionMessageConstant.UNEXPECTED_SHADING_TYPE); - } - shading = new PdfShading.LatticeFormGouraudShadedTriangleMesh((PdfStream)shadingDictionary); - break; - } - - case PdfShading.ShadingType.COONS_PATCH_MESH: { - if (!shadingDictionary.IsStream()) { - throw new PdfException(KernelExceptionMessageConstant.UNEXPECTED_SHADING_TYPE); - } - shading = new PdfShading.CoonsPatchMesh((PdfStream)shadingDictionary); - break; - } - - case PdfShading.ShadingType.TENSOR_PRODUCT_PATCH_MESH: { - if (!shadingDictionary.IsStream()) { - throw new PdfException(KernelExceptionMessageConstant.UNEXPECTED_SHADING_TYPE); - } - shading = new PdfShading.TensorProductPatchMesh((PdfStream)shadingDictionary); - break; - } - - default: { - throw new PdfException(KernelExceptionMessageConstant.UNEXPECTED_SHADING_TYPE); - } - } - return shading; - } - - /// - /// Creates the - /// - /// object from the existing - /// . - /// - /// - /// - /// - /// from which the - /// - /// object will be created. - /// - protected internal PdfShading(PdfDictionary pdfObject) - : base(pdfObject) { - } - - /// - /// Creates the - /// - /// object from the existing - /// - /// , - /// using provided type and colorspace. - /// - /// - /// - /// - /// from which the - /// - /// object will be created. - /// - /// - /// type with which this - /// - /// object will be created. - /// - /// - /// - /// - /// with which this - /// - /// object will be created. - /// - protected internal PdfShading(PdfDictionary pdfObject, int type, PdfColorSpace colorSpace) - : base(pdfObject) { - GetPdfObject().Put(PdfName.ShadingType, new PdfNumber(type)); - if (colorSpace is PdfSpecialCs.Pattern) { - throw new ArgumentException("colorSpace"); - } - GetPdfObject().Put(PdfName.ColorSpace, colorSpace.GetPdfObject()); - } - - /// Gets the shading type. - /// - /// int value of - /// . - /// - public virtual int GetShadingType() { - return (int)GetPdfObject().GetAsInt(PdfName.ShadingType); - } - - /// Gets the color space in which colour values shall be expressed. - /// - /// - /// - /// Color space - /// - public virtual PdfObject GetColorSpace() { - return GetPdfObject().Get(PdfName.ColorSpace); - } - - /// - /// Gets the function PdfObject that represents color transitions - /// across the shading geometry. - /// - /// - /// - /// - /// Function - /// - public virtual PdfObject GetFunction() { - return GetPdfObject().Get(PdfName.Function); - } - - /// - /// Sets the function that represents color transitions - /// across the shading geometry as one object. - /// - /// - /// The - /// - /// to set. - /// - public virtual void SetFunction(IPdfFunction function) { - GetPdfObject().Put(PdfName.Function, function.GetAsPdfObject()); - SetModified(); - } - - /// - /// Sets the function object that represents color transitions - /// across the shading geometry as an array of functions. - /// - /// - /// The array of - /// - /// to be set. - /// - public virtual void SetFunction(IPdfFunction[] functions) { - PdfArray arr = new PdfArray(); - foreach (IPdfFunction func in functions) { - arr.Add(func.GetAsPdfObject()); - } - GetPdfObject().Put(PdfName.Function, arr); - SetModified(); - } - - /// - /// To manually flush a - /// PdfObject - /// behind this wrapper, you have to ensure - /// that this object is added to the document, i.e. it has an indirect reference. - /// - /// - /// To manually flush a - /// PdfObject - /// behind this wrapper, you have to ensure - /// that this object is added to the document, i.e. it has an indirect reference. - /// Basically this means that before flushing you need to explicitly call - /// . - /// For example: wrapperInstance.makeIndirect(document).flush(); - /// Note that not every wrapper require this, only those that have such warning in documentation. - /// - public override void Flush() { - base.Flush(); - } - - /// - protected internal override bool IsWrappedObjectMustBeIndirect() { - return true; - } - - /// - /// The class that extends - /// - /// class and is in charge of Shading Dictionary with function-based type, - /// that defines color at every point in the domain by a specified mathematical function. - /// - public class FunctionBased : PdfShading { - /// - /// Creates the new instance of the class from the existing - /// . - /// - /// - /// from which this - /// - /// will be created - /// - protected internal FunctionBased(PdfDictionary pdfDictionary) - : base(pdfDictionary) { - } - - /// Creates the new instance of the class. - /// - /// the - /// - /// object in which colour values shall be expressed. - /// - /// - /// the - /// - /// , that is used to calculate color transitions. - /// - public FunctionBased(PdfColorSpace colorSpace, IPdfFunction function) - : this(colorSpace.GetPdfObject(), function) { - } - - /// Creates the new instance of the class. - /// - /// the - /// - /// , that represents color space in which colour values shall be expressed. - /// - /// - /// the - /// - /// , that is used to calculate color transitions. - /// - public FunctionBased(PdfObject colorSpace, IPdfFunction function) - : base(new PdfDictionary(), PdfShading.ShadingType.FUNCTION_BASED, PdfColorSpace.MakeColorSpace(colorSpace - )) { - SetFunction(function); - } - - /// - /// Gets the - /// - /// domain rectangle object that establishes an internal coordinate space - /// for the shading that is independent of the target coordinate space in which it shall be painted. - /// - /// - /// - /// - /// domain rectangle. - /// - public virtual PdfArray GetDomain() { - return GetPdfObject().GetAsArray(PdfName.Domain); - } - - /// - /// Sets the - /// - /// domain rectangle object that establishes an internal coordinate space - /// for the shading that is independent of the target coordinate space in which it shall be painted. - /// - /// the Xmin coordinate of rectangle. - /// the Xmax coordinate of rectangle. - /// the Ymin coordinate of rectangle. - /// the Ymax coordinate of rectangle. - public virtual void SetDomain(float xmin, float xmax, float ymin, float ymax) { - SetDomain(new PdfArray(new float[] { xmin, xmax, ymin, ymax })); - } - - /// - /// Sets the - /// - /// domain rectangle object that establishes an internal coordinate space - /// for the shading that is independent of the target coordinate space in which it shall be painted. - /// - /// - /// the - /// - /// domain rectangle object to be set. - /// - public virtual void SetDomain(PdfArray domain) { - GetPdfObject().Put(PdfName.Domain, domain); - SetModified(); - } - - /// - /// Gets the - /// - /// of floats that represents the transformation matrix that maps the domain rectangle - /// into a corresponding figure in the target coordinate space. - /// - /// - /// the - /// - /// of transformation matrix (identical matrix by default). - /// - public virtual PdfArray GetMatrix() { - PdfArray matrix = GetPdfObject().GetAsArray(PdfName.Matrix); - if (matrix == null) { - matrix = new PdfArray(new float[] { 1, 0, 0, 1, 0, 0 }); - SetMatrix(matrix); - } - return matrix; - } - - /// - /// Sets the array of floats that represents the transformation matrix that maps the domain rectangle - /// into a corresponding figure in the target coordinate space. - /// - /// - /// the - /// float[] - /// of transformation matrix to be set. - /// - public virtual void SetMatrix(float[] matrix) { - SetMatrix(new PdfArray(matrix)); - } - - /// - /// Sets the array of floats that represents the transformation matrix that maps the domain rectangle - /// into a corresponding figure in the target coordinate space. - /// - /// - /// the - /// - /// transformation matrix object to be set. - /// - public virtual void SetMatrix(PdfArray matrix) { - GetPdfObject().Put(PdfName.Matrix, matrix); - SetModified(); - } - } - - /// - /// The class that extends - /// - /// class and is in charge of Shading Dictionary with axial type, - /// that define a colour blend that varies along a linear axis between two endpoints - /// and extends indefinitely perpendicular to that axis. - /// - public class Axial : PdfShading { - /// - /// Creates the new instance of the class from the existing - /// . - /// - /// - /// from which this - /// - /// will be created - /// - protected internal Axial(PdfDictionary pdfDictionary) - : base(pdfDictionary) { - } - - /// Creates the new instance of the class. - /// - /// the - /// - /// object in which colour values shall be expressed. - /// The special Pattern space isn't excepted. - /// - /// the start coordinate of X axis expressed in the shading's target coordinate space. - /// the start coordinate of Y axis expressed in the shading's target coordinate space. - /// - /// the - /// float[] - /// that represents the color in the start point. - /// - /// the end coordinate of X axis expressed in the shading's target coordinate space. - /// the end coordinate of Y axis expressed in the shading's target coordinate space. - /// - /// the - /// float[] - /// that represents the color in the end point. - /// - public Axial(PdfColorSpace cs, float x0, float y0, float[] color0, float x1, float y1, float[] color1) - : base(new PdfDictionary(), PdfShading.ShadingType.AXIAL, cs) { - SetCoords(x0, y0, x1, y1); - IPdfFunction func = new PdfType2Function(new float[] { 0, 1 }, null, color0, color1, 1); - SetFunction(func); - } - - /// Creates the new instance of the class. - /// - /// the - /// - /// object in which colour values shall be expressed. - /// The special Pattern space isn't excepted. - /// - /// the start coordinate of X axis expressed in the shading's target coordinate space. - /// the start coordinate of Y axis expressed in the shading's target coordinate space. - /// - /// the - /// float[] - /// that represents the color in the start point. - /// - /// the end coordinate of X axis expressed in the shading's target coordinate space. - /// the end coordinate of Y axis expressed in the shading's target coordinate space. - /// - /// the - /// float[] - /// that represents the color in the end point. - /// - /// - /// the array of two booleans that specified whether to extend the shading - /// beyond the starting and ending points of the axis, respectively. - /// - public Axial(PdfColorSpace cs, float x0, float y0, float[] color0, float x1, float y1, float[] color1, bool - [] extend) - : this(cs, x0, y0, color0, x1, y1, color1) { - if (extend == null || extend.Length != 2) { - throw new ArgumentException("extend"); - } - SetExtend(extend[0], extend[1]); - } - - /// Creates the new instance of the class. - /// - /// the - /// - /// object in which colour values shall be expressed. - /// The special Pattern space isn't excepted. - /// - /// - /// the - /// - /// of four numbers [x0 y0 x1 y1] that specified the starting - /// and the endings coordinates of thew axis, expressed in the shading's target coordinate space. - /// - /// - /// the - /// - /// object, that is used to calculate color transitions. - /// - public Axial(PdfColorSpace cs, PdfArray coords, IPdfFunction function) - : this(cs, coords, null, function) { - } - - /// Creates the new instance of the class. - /// - /// the - /// - /// object in which colour values shall be expressed. - /// The special Pattern space isn't excepted. - /// - /// - /// the - /// - /// of four numbers [x0 y0 x1 y1] that specified - /// the starting and the endings coordinates of thew axis, expressed - /// in the shading's target coordinate space. - /// - /// - /// the - /// - /// of two numbers [t0 t1] specifying the limiting values - /// of a parametric variable t which is considered to vary linearly between - /// these two values and becomes the input argument to the colour function. - /// - /// - /// the - /// - /// object, that is used to calculate color transitions. - /// - public Axial(PdfColorSpace cs, PdfArray coords, PdfArray domain, IPdfFunction function) - : base(new PdfDictionary(), PdfShading.ShadingType.AXIAL, cs) { - SetCoords(coords); - if (domain != null) { - SetDomain(domain); - } - SetFunction(function); - } - - /// - /// Gets the Coords object - a - /// - /// of four numbers [x0 y0 x1 y1] that specified the starting - /// and the endings coordinates of thew axis, expressed in the shading's target coordinate space. - /// - /// - /// the - /// - /// Coords object. - /// - public virtual PdfArray GetCoords() { - return GetPdfObject().GetAsArray(PdfName.Coords); - } - - /// Sets the Choords object with the four params expressed in the shading's target coordinate space. - /// the start coordinate of X axis to be set. - /// the start coordinate of Y axis to be set. - /// the end coordinate of X axis to be set. - /// the end coordinate of Y axis to be set. - public virtual void SetCoords(float x0, float y0, float x1, float y1) { - SetCoords(new PdfArray(new float[] { x0, y0, x1, y1 })); - } - - /// - /// Sets the Choords object with the - /// - /// of four numbers [x0 y0 x1 y1], - /// that specified the starting and the endings coordinates of thew axis, - /// expressed in the shading's target coordinate space. - /// - /// - /// the Chords - /// - /// to be set. - /// - public virtual void SetCoords(PdfArray coords) { - GetPdfObject().Put(PdfName.Coords, coords); - SetModified(); - } - - /// - /// Gets the - /// - /// of two - /// float - /// [t0, t1] that represent the limiting values of a parametric - /// variable t, that becomes an input of color function(s). - /// - /// - /// the - /// - /// of Domain object ([0.0 1.0] by default) - /// - public virtual PdfArray GetDomain() { - PdfArray domain = GetPdfObject().GetAsArray(PdfName.Domain); - if (domain == null) { - domain = new PdfArray(new float[] { 0, 1 }); - SetDomain(domain); - } - return domain; - } - - /// - /// Sets the Domain with the array of two - /// float - /// [t0, t1] that represent the limiting values - /// of a parametric variable t, that becomes an input of color function(s). - /// - /// first limit of variable t - /// second limit of variable t - public virtual void SetDomain(float t0, float t1) { - SetDomain(new PdfArray(new float[] { t0, t1 })); - } - - /// - /// Sets the Domain with the - /// - /// of two - /// float - /// [t0, t1] that represent the limiting values - /// of a parametric variable t, that becomes an input of color function(s). - /// - /// - /// the - /// - /// that represents domain - /// - public virtual void SetDomain(PdfArray domain) { - GetPdfObject().Put(PdfName.Domain, domain); - SetModified(); - } - - /// - /// Gets the - /// - /// of two - /// boolean - /// that specified whether to extend the shading - /// beyond the starting and ending points of the axis, respectively. - /// - /// - /// the - /// - /// of Extended object ([false false] by default) - /// - public virtual PdfArray GetExtend() { - PdfArray extend = GetPdfObject().GetAsArray(PdfName.Extend); - if (extend == null) { - extend = new PdfArray(new bool[] { false, false }); - SetExtend(extend); - } - return extend; - } - - /// - /// Sets the Extend object with the two - /// boolean - /// value. - /// - /// if true will extend shading beyond the starting point of Coords - /// if true will extend shading beyond the ending point of Coords - public virtual void SetExtend(bool extendStart, bool extendEnd) { - SetExtend(new PdfArray(new bool[] { extendStart, extendEnd })); - } - - /// - /// Sets the Extend object with the - /// - /// of two - /// boolean. - /// - /// - /// Sets the Extend object with the - /// - /// of two - /// boolean. - /// If first is true shading will extend beyond the starting point of Coords. - /// If second is true shading will extend beyond the ending point of Coords. - /// - /// - /// the - /// - /// representing Extend object - /// - public virtual void SetExtend(PdfArray extend) { - GetPdfObject().Put(PdfName.Extend, extend); - SetModified(); - } - } - - /// - /// The class that extends - /// - /// class and is in charge of Shading Dictionary with radial type, - /// that define a colour blend that varies between two circles. - /// - /// - /// The class that extends - /// - /// class and is in charge of Shading Dictionary with radial type, - /// that define a colour blend that varies between two circles. - /// This type of shading shall not be used with an Indexed colour space - /// - public class Radial : PdfShading { - /// - /// Creates the new instance of the class from the existing - /// . - /// - /// - /// from which this - /// - /// will be created - /// - protected internal Radial(PdfDictionary pdfDictionary) - : base(pdfDictionary) { - } - - /// Creates the new instance of the class. - /// - /// the - /// - /// object in which colour values shall be expressed. - /// The Indexed color space isn't excepted. - /// - /// the X coordinate of starting circle's centre, expressed in in the shading’s target coordinate space. - /// - /// the Y coordinate of starting circle's centre, expressed in in the shading’s target coordinate space. - /// - /// - /// the radius of starting circle's centre, should be greater or equal to 0. - /// If 0 then starting circle is treated as point. - /// If both radii are 0, nothing shall be painted. - /// - /// - /// the - /// float[] - /// that represents the color in the start circle. - /// - /// the X coordinate of ending circle's centre, expressed in in the shading’s target coordinate space. - /// - /// the Y coordinate of ending circle's centre, expressed in in the shading’s target coordinate space. - /// - /// - /// the radius of ending circle's centre, should be greater or equal to 0. - /// If 0 then ending circle is treated as point. - /// If both radii are 0, nothing shall be painted. - /// - /// - /// the - /// float[] - /// that represents the color in the end circle. - /// - public Radial(PdfColorSpace cs, float x0, float y0, float r0, float[] color0, float x1, float y1, float r1 - , float[] color1) - : base(new PdfDictionary(), PdfShading.ShadingType.RADIAL, cs) { - SetCoords(x0, y0, r0, x1, y1, r1); - IPdfFunction func = new PdfType2Function(new float[] { 0, 1 }, null, color0, color1, 1); - SetFunction(func); - } - - /// Creates the new instance of the class. - /// - /// the - /// - /// object in which colour values shall be expressed. - /// The Indexed color space isn't excepted. - /// - /// the X coordinate of starting circle's centre, expressed in in the shading’s target coordinate space. - /// - /// the Y coordinate of starting circle's centre, expressed in in the shading’s target coordinate space. - /// - /// - /// the radius of starting circle's centre, should be greater or equal to 0. - /// If 0 then starting circle is treated as point. - /// If both radii are 0, nothing shall be painted. - /// - /// - /// the - /// float[] - /// that represents the color in the start circle. - /// - /// the X coordinate of ending circle's centre, expressed in in the shading’s target coordinate space. - /// - /// the Y coordinate of ending circle's centre, expressed in in the shading’s target coordinate space. - /// - /// - /// the radius of ending circle's centre, should be greater or equal to 0. - /// If 0 then ending circle is treated as point. - /// If both radii are 0, nothing shall be painted. - /// - /// - /// the - /// float[] - /// that represents the color in the end circle. - /// - /// - /// the array of two - /// boolean - /// that specified whether to extend the shading - /// beyond the starting and ending points of the axis, respectively. - /// - public Radial(PdfColorSpace cs, float x0, float y0, float r0, float[] color0, float x1, float y1, float r1 - , float[] color1, bool[] extend) - : this(cs, x0, y0, r0, color0, x1, y1, r1, color1) { - if (extend == null || extend.Length != 2) { - throw new ArgumentException("extend"); - } - SetExtend(extend[0], extend[1]); - } - - /// Creates the new instance of the class. - /// - /// the - /// - /// object in which colour values shall be expressed. - /// The Indexed color space isn't excepted. - /// - /// - /// the - /// - /// of of six numbers [x0 y0 r0 x1 y1 r1], - /// specifying the centres and radii of the starting and ending circles, - /// expressed in the shading’s target coordinate space. - /// The radii r0 and r1 shall both be greater than or equal to 0. - /// If one radius is 0, the corresponding circle shall be treated as a point; - /// if both are 0, nothing shall be painted. - /// - /// - /// the - /// - /// object, that is used to calculate color transitions. - /// - public Radial(PdfColorSpace cs, PdfArray coords, IPdfFunction function) - : base(new PdfDictionary(), PdfShading.ShadingType.RADIAL, cs) { - SetCoords(coords); - SetFunction(function); - } - - /// - /// Gets the coords - /// - /// object - an array of six numbers [x0 y0 r0 x1 y1 r1], - /// specifying the centres and radii of the starting and ending circles, - /// expressed in the shading’s target coordinate space. - /// - /// - /// Gets the coords - /// - /// object - an array of six numbers [x0 y0 r0 x1 y1 r1], - /// specifying the centres and radii of the starting and ending circles, - /// expressed in the shading’s target coordinate space. - /// The radii r0 and r1 shall both be greater than or equal to 0. - /// If one radius is 0, the corresponding circle shall be treated as a point; - /// if both are 0, nothing shall be painted. - /// - /// - /// the - /// - /// coords object. - /// - public virtual PdfArray GetCoords() { - return GetPdfObject().GetAsArray(PdfName.Coords); - } - - /// Sets the coords object. - /// the X coordinate of starting circle's centre, expressed in in the shading’s target coordinate space. - /// - /// the Y coordinate of starting circle's centre, expressed in in the shading’s target coordinate space. - /// - /// - /// the radius of starting circle's centre, should be greater or equal to 0. - /// If 0 then starting circle is treated as point. - /// If both radii are 0, nothing shall be painted. - /// - /// the X coordinate of ending circle's centre, expressed in in the shading’s target coordinate space. - /// - /// the Y coordinate of ending circle's centre, expressed in in the shading’s target coordinate space. - /// - /// - /// the radius of ending circle's centre, should be greater or equal to 0. - /// If 0 then ending circle is treated as point. - /// If both radii are 0, nothing shall be painted. - /// - public virtual void SetCoords(float x0, float y0, float r0, float x1, float y1, float r1) { - SetCoords(new PdfArray(new float[] { x0, y0, r0, x1, y1, r1 })); - } - - /// - /// Sets the coords - /// - /// object - an array of six numbers [x0 y0 r0 x1 y1 r1], - /// specifying the centres and radii of the starting and ending circles, - /// expressed in the shading’s target coordinate space. - /// - /// - /// Sets the coords - /// - /// object - an array of six numbers [x0 y0 r0 x1 y1 r1], - /// specifying the centres and radii of the starting and ending circles, - /// expressed in the shading’s target coordinate space. - /// The radii r0 and r1 shall both be greater than or equal to 0. - /// If one radius is 0, the corresponding circle shall be treated as a point; - /// if both are 0, nothing shall be painted. - /// - /// - /// - - /// - /// choords object to be set. - /// - public virtual void SetCoords(PdfArray coords) { - GetPdfObject().Put(PdfName.Coords, coords); - SetModified(); - } - - /// - /// Gets the - /// - /// of two - /// float - /// [t0, t1] that represent the limiting values of a parametric - /// variable t, that becomes an input of color function(s). - /// - /// - /// the - /// - /// of Domain object ([0.0 1.0] by default) - /// - public virtual PdfArray GetDomain() { - PdfArray domain = GetPdfObject().GetAsArray(PdfName.Domain); - if (domain == null) { - domain = new PdfArray(new float[] { 0, 1 }); - SetDomain(domain); - } - return domain; - } - - /// - /// Sets the Domain with the array of two - /// float - /// [t0, t1] that represent the limiting values - /// of a parametric variable t, that becomes an input of color function(s). - /// - /// first limit of variable t - /// second limit of variable t - public virtual void SetDomain(float t0, float t1) { - SetDomain(new PdfArray(new float[] { t0, t1 })); - } - - /// - /// Sets the Domain with the - /// - /// of two - /// float - /// [t0, t1] that represent the limiting values - /// of a parametric variable t, that becomes an input of color function(s). - /// - /// - /// the - /// - /// that represents domain - /// - public virtual void SetDomain(PdfArray domain) { - GetPdfObject().Put(PdfName.Domain, domain); - SetModified(); - } - - /// - /// Gets the - /// - /// of two - /// boolean - /// that specified whether to extend the shading - /// beyond the starting and ending circles of the axis, respectively. - /// - /// - /// the - /// - /// of Extended object ([false false] by default) - /// - public virtual PdfArray GetExtend() { - PdfArray extend = GetPdfObject().GetAsArray(PdfName.Extend); - if (extend == null) { - extend = new PdfArray(new bool[] { false, false }); - SetExtend(extend); - } - return extend; - } - - /// - /// Sets the Extend object with the two - /// boolean - /// value. - /// - /// if true will extend shading beyond the starting circle of Coords. - /// if true will extend shading beyond the ending circle of Coords. - public virtual void SetExtend(bool extendStart, bool extendEnd) { - SetExtend(new PdfArray(new bool[] { extendStart, extendEnd })); - } - - /// - /// Sets the Extend object with the - /// - /// of two - /// boolean. - /// - /// - /// Sets the Extend object with the - /// - /// of two - /// boolean. - /// If first is true shading will extend beyond the starting circle of Coords. - /// If second is true shading will extend beyond the ending circle of Coords. - /// - /// - /// the - /// - /// representing Extend object - /// - public virtual void SetExtend(PdfArray extend) { - GetPdfObject().Put(PdfName.Extend, extend); - SetModified(); - } - } - - /// - /// The class that extends - /// - /// class and is in charge of Shading Dictionary with - /// free-form Gouraud-shaded triangle mesh type. - /// - /// - /// The class that extends - /// - /// class and is in charge of Shading Dictionary with - /// free-form Gouraud-shaded triangle mesh type. - /// The area to be shaded is defined by a path composed entirely of triangles. - /// The colour at each vertex of the triangles is specified, - /// and a technique known as Gouraud interpolation is used to colour the interiors. - /// The object shall be represented as stream containing a sequence of vertex data. - /// Each vertex is specified by the following values, in the order shown: - /// f x y c1 ... cn where: - /// f - the vertex's edge flag, that determines the vertex is connected to other vertices of the triangle mesh. - /// For full description, see ISO-320001 Paragraph 8.7.4.5.5 - /// x, y - vertex's horizontal and vertical coordinates, expressed in the shading's target coordinate space. - /// c1...cn - vertex's colour components. - /// If the shading dictionary includes a Function entry, only a single parametric value, t, - /// shall be specified for each vertex in place of the colour components c1...cn. - /// - public class FreeFormGouraudShadedTriangleMesh : PdfShading { - /// - /// Creates the new instance of the class from the existing - /// . - /// - /// - /// from which this - /// - /// will be created - /// - protected internal FreeFormGouraudShadedTriangleMesh(PdfStream pdfStream) - : base(pdfStream) { - } - - /// Creates the new instance of the class. - /// - /// the - /// - /// object in which colour values shall be expressed. - /// The special Pattern space isn't excepted. - /// - /// - /// the number of bits used to represent each vertex coordinate. - /// The value shall be 1, 2, 4, 8, 12, 16, 24, or 32. - /// - /// - /// the number of bits used to represent each colour component. - /// The value shall be 1, 2, 4, 8, 12, or 16. - /// - /// - /// the number of bits used to represent the edge flag for each vertex. - /// The value of BitsPerFlag shall be 2, 4, or 8, - /// but only the least significant 2 bits in each flag value shall be used. - /// The value for the edge flag shall be 0, 1, or 2. - /// - /// - /// the - /// int[] - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. The ranges shall be specified as follows: - /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. - /// Only one pair of color values shall be specified if a Function entry is present. - /// - public FreeFormGouraudShadedTriangleMesh(PdfColorSpace cs, int bitsPerCoordinate, int bitsPerComponent, int - bitsPerFlag, float[] decode) - : this(cs, bitsPerCoordinate, bitsPerComponent, bitsPerFlag, new PdfArray(decode)) { - } - - /// Creates the new instance of the class. - /// - /// the - /// - /// object in which colour values shall be expressed. - /// The special Pattern space isn't excepted. - /// - /// - /// the number of bits used to represent each vertex coordinate. - /// The value shall be 1, 2, 4, 8, 12, 16, 24, or 32. - /// - /// - /// the number of bits used to represent each colour component. - /// The value shall be 1, 2, 4, 8, 12, or 16. - /// - /// - /// the number of bits used to represent the edge flag for each vertex. - /// The value of BitsPerFlag shall be 2, 4, or 8, - /// but only the least significant 2 bits in each flag value shall be used. - /// The value for the edge flag shall be 0, 1, or 2. - /// - /// - /// the - /// - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. The ranges shall be specified as follows: - /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. - /// Only one pair of color values shall be specified if a Function entry is present. - /// - public FreeFormGouraudShadedTriangleMesh(PdfColorSpace cs, int bitsPerCoordinate, int bitsPerComponent, int - bitsPerFlag, PdfArray decode) - : base(new PdfStream(), PdfShading.ShadingType.FREE_FORM_GOURAUD_SHADED_TRIANGLE_MESH, cs) { - SetBitsPerCoordinate(bitsPerCoordinate); - SetBitsPerComponent(bitsPerComponent); - SetBitsPerFlag(bitsPerFlag); - SetDecode(decode); - } - - /// Gets the number of bits used to represent each vertex coordinate. - /// the number of bits. Can be 1, 2, 4, 8, 12, 16, 24, or 32. - public virtual int GetBitsPerCoordinate() { - return (int)GetPdfObject().GetAsInt(PdfName.BitsPerCoordinate); - } - - /// Sets the number of bits used to represent each vertex coordinate. - /// the number of bits to be set. Shall be 1, 2, 4, 8, 12, 16, 24, or 32. - public virtual void SetBitsPerCoordinate(int bitsPerCoordinate) { - GetPdfObject().Put(PdfName.BitsPerCoordinate, new PdfNumber(bitsPerCoordinate)); - SetModified(); - } - - /// Gets the number of bits used to represent each colour component. - /// the number of bits. Can be 1, 2, 4, 8, 12, or 16. - public virtual int GetBitsPerComponent() { - return (int)GetPdfObject().GetAsInt(PdfName.BitsPerComponent); - } - - /// Sets the number of bits used to represent each colour component. - /// the number of bits to be set. Shall be 1, 2, 4, 8, 12, or 16. - public virtual void SetBitsPerComponent(int bitsPerComponent) { - GetPdfObject().Put(PdfName.BitsPerComponent, new PdfNumber(bitsPerComponent)); - SetModified(); - } - - /// Gets the number of bits used to represent the edge flag for each vertex. - /// - /// Gets the number of bits used to represent the edge flag for each vertex. - /// But only the least significant 2 bits in each flag value shall be used. - /// The valid flag values are 0, 1 or 2. - /// - /// the number of bits. Can be 2, 4 or 8. - public virtual int GetBitsPerFlag() { - return (int)GetPdfObject().GetAsInt(PdfName.BitsPerFlag); - } - - /// Sets the number of bits used to represent the edge flag for each vertex. - /// - /// Sets the number of bits used to represent the edge flag for each vertex. - /// But only the least significant 2 bits in each flag value shall be used. - /// The valid flag values are 0, 1 or 2. - /// - /// the number of bits to be set. Shall be 2, 4 or 8. - public virtual void SetBitsPerFlag(int bitsPerFlag) { - GetPdfObject().Put(PdfName.BitsPerFlag, new PdfNumber(bitsPerFlag)); - SetModified(); - } - - /// - /// Gets the - /// - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. - /// - /// - /// Gets the - /// - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. The ranges shall be specified as follows: - /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. - /// Only one pair of color values shall be specified if a Function entry is present. - /// - /// - /// the - /// - /// Decode object. - /// - public virtual PdfArray GetDecode() { - return GetPdfObject().GetAsArray(PdfName.Decode); - } - - /// - /// Sets the - /// float[] - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. - /// - /// - /// Sets the - /// float[] - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. The ranges shall be specified as follows: - /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. - /// Only one pair of color values shall be specified if a Function entry is present. - /// - /// - /// the - /// float[] - /// of Decode object to set. - /// - public virtual void SetDecode(float[] decode) { - SetDecode(new PdfArray(decode)); - } - - /// - /// Sets the - /// - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. - /// - /// - /// Sets the - /// - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. The ranges shall be specified as follows: - /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. - /// Only one pair of color values shall be specified if a Function entry is present. - /// - /// - /// the - /// - /// Decode object to set. - /// - public virtual void SetDecode(PdfArray decode) { - GetPdfObject().Put(PdfName.Decode, decode); - SetModified(); - } - } - - /// - /// The class that extends - /// - /// class and is in charge of Shading Dictionary with - /// lattice-form Gouraud-shaded triangle mesh type. - /// - /// - /// The class that extends - /// - /// class and is in charge of Shading Dictionary with - /// lattice-form Gouraud-shaded triangle mesh type. - /// This type is similar to - /// - /// but instead of using free-form geometry, - /// the vertices are arranged in a pseudorectangular lattice, - /// which is topologically equivalent to a rectangular grid. - /// The vertices are organized into rows, which need not be geometrically linear. - /// The verticals data in stream is similar to - /// - /// , - /// except there is no edge flag. - /// - public class LatticeFormGouraudShadedTriangleMesh : PdfShading { - /// - /// Creates the new instance of the class from the existing - /// . - /// - /// - /// from which this - /// - /// will be created - /// - protected internal LatticeFormGouraudShadedTriangleMesh(PdfStream pdfStream) - : base(pdfStream) { - } - - /// Creates the new instance of the class. - /// - /// the - /// - /// object in which colour values shall be expressed. - /// The special Pattern space isn't excepted. - /// - /// - /// the number of bits used to represent each vertex coordinate. - /// The value shall be 1, 2, 4, 8, 12, 16, 24, or 32. - /// - /// - /// the number of bits used to represent each colour component. - /// The value shall be 1, 2, 4, 8, 12, or 16. - /// - /// - /// the number of vertices in each row of the lattice (shall be > 1). - /// The number of rows need not be specified. - /// - /// - /// the - /// int[] - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. The ranges shall be specified as follows: - /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. - /// Only one pair of color values shall be specified if a Function entry is present. - /// - public LatticeFormGouraudShadedTriangleMesh(PdfColorSpace cs, int bitsPerCoordinate, int bitsPerComponent, - int verticesPerRow, float[] decode) - : this(cs, bitsPerCoordinate, bitsPerComponent, verticesPerRow, new PdfArray(decode)) { - } - - /// Creates the new instance of the class. - /// - /// the - /// - /// object in which colour values shall be expressed. - /// The special Pattern space isn't excepted. - /// - /// - /// the number of bits used to represent each vertex coordinate. - /// The value shall be 1, 2, 4, 8, 12, 16, 24, or 32. - /// - /// - /// the number of bits used to represent each colour component. - /// The value shall be 1, 2, 4, 8, 12, or 16. - /// - /// - /// the number of vertices in each row of the lattice (shall be > 1). - /// The number of rows need not be specified. - /// - /// - /// the - /// - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. The ranges shall be specified as follows: - /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. - /// Only one pair of color values shall be specified if a Function entry is present. - /// - public LatticeFormGouraudShadedTriangleMesh(PdfColorSpace cs, int bitsPerCoordinate, int bitsPerComponent, - int verticesPerRow, PdfArray decode) - : base(new PdfStream(), PdfShading.ShadingType.LATTICE_FORM_GOURAUD_SHADED_TRIANGLE_MESH, cs) { - SetBitsPerCoordinate(bitsPerCoordinate); - SetBitsPerComponent(bitsPerComponent); - SetVerticesPerRow(verticesPerRow); - SetDecode(decode); - } - - /// Gets the number of bits used to represent each vertex coordinate. - /// the number of bits. Can be 1, 2, 4, 8, 12, 16, 24, or 32. - public virtual int GetBitsPerCoordinate() { - return (int)GetPdfObject().GetAsInt(PdfName.BitsPerCoordinate); - } - - /// Sets the number of bits used to represent each vertex coordinate. - /// the number of bits to be set. Shall be 1, 2, 4, 8, 12, 16, 24, or 32. - public virtual void SetBitsPerCoordinate(int bitsPerCoordinate) { - GetPdfObject().Put(PdfName.BitsPerCoordinate, new PdfNumber(bitsPerCoordinate)); - SetModified(); - } - - /// Gets the number of bits used to represent each colour component. - /// the number of bits. Can be 1, 2, 4, 8, 12, or 16. - public virtual int GetBitsPerComponent() { - return (int)GetPdfObject().GetAsInt(PdfName.BitsPerComponent); - } - - /// Sets the number of bits used to represent each colour component. - /// the number of bits to be set. Shall be 1, 2, 4, 8, 12, or 16. - public virtual void SetBitsPerComponent(int bitsPerComponent) { - GetPdfObject().Put(PdfName.BitsPerComponent, new PdfNumber(bitsPerComponent)); - SetModified(); - } - - /// Gets the number of vertices in each row of the lattice. - /// the number of vertices. Can only be greater than 1. - public virtual int GetVerticesPerRow() { - return (int)GetPdfObject().GetAsInt(PdfName.VerticesPerRow); - } - - /// Sets the number of vertices in each row of the lattice. - /// - /// Sets the number of vertices in each row of the lattice. - /// The number of rows need not be specified. - /// - /// the number of vertices to be set. Shall be greater than 1. - public virtual void SetVerticesPerRow(int verticesPerRow) { - GetPdfObject().Put(PdfName.VerticesPerRow, new PdfNumber(verticesPerRow)); - SetModified(); - } - - /// - /// Gets the - /// - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. - /// - /// - /// Gets the - /// - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. The ranges shall be specified as follows: - /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. - /// Only one pair of color values shall be specified if a Function entry is present. - /// - /// - /// the - /// - /// Decode object. - /// - public virtual PdfArray GetDecode() { - return GetPdfObject().GetAsArray(PdfName.Decode); - } - - /// - /// Sets the - /// float[] - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. - /// - /// - /// Sets the - /// float[] - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. The ranges shall be specified as follows: - /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. - /// Only one pair of color values shall be specified if a Function entry is present. - /// - /// - /// the - /// float[] - /// of Decode object to set. - /// - public virtual void SetDecode(float[] decode) { - SetDecode(new PdfArray(decode)); - } - - /// - /// Sets the - /// - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. - /// - /// - /// Sets the - /// - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. The ranges shall be specified as follows: - /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. - /// Only one pair of color values shall be specified if a Function entry is present. - /// - /// - /// the - /// - /// Decode object to set. - /// - public virtual void SetDecode(PdfArray decode) { - GetPdfObject().Put(PdfName.Decode, decode); - SetModified(); - } - } - - /// - /// The class that extends - /// - /// class and is in charge of Shading Dictionary with - /// Coons Patch mesh type. - /// - /// - /// The class that extends - /// - /// class and is in charge of Shading Dictionary with - /// Coons Patch mesh type. - /// This type of shading is constructed from one or more colour patches, each bounded by four cubic Bézier curves. - /// Degenerate Bézier curves are allowed and are useful for certain graphical effects. - /// At least one complete patch shall be specified. - /// The shape of patch is defined by 12 control points. - /// Colours are specified for each corner of the unit square, - /// and bilinear interpolation is used to fill in colours over the entire unit square. - /// Coordinates are mapped from the unit square into a four-sided patch whose sides are not necessarily linear. - /// The mapping is continuous: the corners of the unit square map to corners of the patch - /// and the sides of the unit square map to sides of the patch. - /// For the format of data stream, that defines patches (see ISO-320001 Table 85). - /// If the shading dictionary contains a Function entry, the colour data for each corner of a patch - /// shall be specified by a single parametric value t rather than by n separate colour components c1...cn. - /// - public class CoonsPatchMesh : PdfShading { - /// - /// Creates the new instance of the class from the existing - /// . - /// - /// - /// from which this - /// - /// will be created - /// - protected internal CoonsPatchMesh(PdfStream pdfStream) - : base(pdfStream) { - } - - /// Creates the new instance of the class. - /// - /// the - /// - /// object in which colour values shall be expressed. - /// The special Pattern space isn't excepted. - /// - /// - /// the number of bits used to represent each vertex coordinate. - /// The value shall be 1, 2, 4, 8, 12, 16, 24, or 32. - /// - /// - /// the number of bits used to represent each colour component. - /// The value shall be 1, 2, 4, 8, 12, or 16. - /// - /// - /// the number of bits used to represent the edge flag for each vertex. - /// The value of BitsPerFlag shall be 2, 4, or 8, - /// but only the least significant 2 bits in each flag value shall be used. - /// The value for the edge flag shall be 0, 1, 2 or 3. - /// - /// - /// the - /// int[] - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. The ranges shall be specified as follows: - /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. - /// Only one pair of color values shall be specified if a Function entry is present. - /// - public CoonsPatchMesh(PdfColorSpace cs, int bitsPerCoordinate, int bitsPerComponent, int bitsPerFlag, float - [] decode) - : this(cs, bitsPerCoordinate, bitsPerComponent, bitsPerFlag, new PdfArray(decode)) { - } - - /// Creates the new instance of the class. - /// - /// the - /// - /// object in which colour values shall be expressed. - /// The special Pattern space isn't excepted. - /// - /// - /// the number of bits used to represent each vertex coordinate. - /// The value shall be 1, 2, 4, 8, 12, 16, 24, or 32. - /// - /// - /// the number of bits used to represent each colour component. - /// The value shall be 1, 2, 4, 8, 12, or 16. - /// - /// - /// the number of bits used to represent the edge flag for each vertex. - /// The value of BitsPerFlag shall be 2, 4, or 8, - /// but only the least significant 2 bits in each flag value shall be used. - /// The value for the edge flag shall be 0, 1, 2 or 3. - /// - /// - /// the - /// - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. The ranges shall be specified as follows: - /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. - /// Only one pair of color values shall be specified if a Function entry is present. - /// - public CoonsPatchMesh(PdfColorSpace cs, int bitsPerCoordinate, int bitsPerComponent, int bitsPerFlag, PdfArray - decode) - : base(new PdfStream(), PdfShading.ShadingType.COONS_PATCH_MESH, cs) { - SetBitsPerCoordinate(bitsPerCoordinate); - SetBitsPerComponent(bitsPerComponent); - SetBitsPerFlag(bitsPerFlag); - SetDecode(decode); - } - - /// Gets the number of bits used to represent each vertex coordinate. - /// the number of bits. Can be 1, 2, 4, 8, 12, 16, 24, or 32. - public virtual int GetBitsPerCoordinate() { - return (int)GetPdfObject().GetAsInt(PdfName.BitsPerCoordinate); - } - - /// Sets the number of bits used to represent each vertex coordinate. - /// the number of bits to be set. Shall be 1, 2, 4, 8, 12, 16, 24, or 32. - public virtual void SetBitsPerCoordinate(int bitsPerCoordinate) { - GetPdfObject().Put(PdfName.BitsPerCoordinate, new PdfNumber(bitsPerCoordinate)); - SetModified(); - } - - /// Gets the number of bits used to represent each colour component. - /// the number of bits. Can be 1, 2, 4, 8, 12, or 16. - public virtual int GetBitsPerComponent() { - return (int)GetPdfObject().GetAsInt(PdfName.BitsPerComponent); - } - - /// Sets the number of bits used to represent each colour component. - /// the number of bits to be set. Shall be 1, 2, 4, 8, 12, or 16. - public virtual void SetBitsPerComponent(int bitsPerComponent) { - GetPdfObject().Put(PdfName.BitsPerComponent, new PdfNumber(bitsPerComponent)); - SetModified(); - } - - /// Gets the number of bits used to represent the edge flag for each vertex. - /// - /// Gets the number of bits used to represent the edge flag for each vertex. - /// But only the least significant 2 bits in each flag value shall be used. - /// The valid flag values are 0, 1, 2 or 3. - /// - /// the number of bits. Can be 2, 4 or 8. - public virtual int GetBitsPerFlag() { - return (int)GetPdfObject().GetAsInt(PdfName.BitsPerFlag); - } - - /// Sets the number of bits used to represent the edge flag for each vertex. - /// - /// Sets the number of bits used to represent the edge flag for each vertex. - /// But only the least significant 2 bits in each flag value shall be used. - /// The valid flag values are 0, 1, 2 or 3. - /// - /// the number of bits to be set. Shall be 2, 4 or 8. - public virtual void SetBitsPerFlag(int bitsPerFlag) { - GetPdfObject().Put(PdfName.BitsPerFlag, new PdfNumber(bitsPerFlag)); - SetModified(); - } - - /// - /// Gets the - /// - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. - /// - /// - /// Gets the - /// - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. The ranges shall be specified as follows: - /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. - /// Only one pair of color values shall be specified if a Function entry is present. - /// - /// - /// the - /// - /// Decode object. - /// - public virtual PdfArray GetDecode() { - return GetPdfObject().GetAsArray(PdfName.Decode); - } - - /// - /// Sets the - /// float[] - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. - /// - /// - /// Sets the - /// float[] - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. The ranges shall be specified as follows: - /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. - /// Only one pair of color values shall be specified if a Function entry is present. - /// - /// - /// the - /// float[] - /// of Decode object to set. - /// - public virtual void SetDecode(float[] decode) { - SetDecode(new PdfArray(decode)); - } - - /// - /// Sets the - /// - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. - /// - /// - /// Sets the - /// - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. The ranges shall be specified as follows: - /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. - /// Only one pair of color values shall be specified if a Function entry is present. - /// - /// - /// the - /// - /// Decode object to set. - /// - public virtual void SetDecode(PdfArray decode) { - GetPdfObject().Put(PdfName.Decode, decode); - SetModified(); - } - } - - /// - /// The class that extends - /// - /// class and is in charge of Shading Dictionary with - /// Tensor-Product Patch mesh type. - /// - /// - /// The class that extends - /// - /// class and is in charge of Shading Dictionary with - /// Tensor-Product Patch mesh type. - /// This type of shading is identical to - /// - /// , except that it's based on a - /// bicubic tensor-product patch defined by 16 control points. - /// For the format of data stream, that defines patches, see ISO-320001 Table 86. - /// - public class TensorProductPatchMesh : PdfShading { - /// - /// Creates the new instance of the class from the existing - /// . - /// - /// - /// from which this - /// - /// will be created - /// - protected internal TensorProductPatchMesh(PdfStream pdfStream) - : base(pdfStream) { - } - - /// Creates the new instance of the class. - /// - /// the - /// - /// object in which colour values shall be expressed. - /// The special Pattern space isn't excepted. - /// - /// - /// the number of bits used to represent each vertex coordinate. - /// The value shall be 1, 2, 4, 8, 12, 16, 24, or 32. - /// - /// - /// the number of bits used to represent each colour component. - /// The value shall be 1, 2, 4, 8, 12, or 16. - /// - /// - /// the number of bits used to represent the edge flag for each vertex. - /// The value of BitsPerFlag shall be 2, 4, or 8, - /// but only the least significant 2 bits in each flag value shall be used. - /// The value for the edge flag shall be 0, 1, 2 or 3. - /// - /// - /// the - /// int[] - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. The ranges shall be specified as follows: - /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. - /// Only one pair of color values shall be specified if a Function entry is present. - /// - public TensorProductPatchMesh(PdfColorSpace cs, int bitsPerCoordinate, int bitsPerComponent, int bitsPerFlag - , float[] decode) - : this(cs, bitsPerCoordinate, bitsPerComponent, bitsPerFlag, new PdfArray(decode)) { - } - - /// Creates the new instance of the class. - /// - /// the - /// - /// object in which colour values shall be expressed. - /// The special Pattern space isn't excepted. - /// - /// - /// the number of bits used to represent each vertex coordinate. - /// The value shall be 1, 2, 4, 8, 12, 16, 24, or 32. - /// - /// - /// the number of bits used to represent each colour component. - /// The value shall be 1, 2, 4, 8, 12, or 16. - /// - /// - /// the number of bits used to represent the edge flag for each vertex. - /// The value of BitsPerFlag shall be 2, 4, or 8, - /// but only the least significant 2 bits in each flag value shall be used. - /// The value for the edge flag shall be 0, 1, 2 or 3. - /// - /// - /// the - /// - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. The ranges shall be specified as follows: - /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. - /// Only one pair of color values shall be specified if a Function entry is present. - /// - public TensorProductPatchMesh(PdfColorSpace cs, int bitsPerCoordinate, int bitsPerComponent, int bitsPerFlag - , PdfArray decode) - : base(new PdfStream(), PdfShading.ShadingType.TENSOR_PRODUCT_PATCH_MESH, cs) { - SetBitsPerCoordinate(bitsPerCoordinate); - SetBitsPerComponent(bitsPerComponent); - SetBitsPerFlag(bitsPerFlag); - SetDecode(decode); - } - - /// Gets the number of bits used to represent each vertex coordinate. - /// the number of bits. Can be 1, 2, 4, 8, 12, 16, 24, or 32. - public virtual int GetBitsPerCoordinate() { - return (int)GetPdfObject().GetAsInt(PdfName.BitsPerCoordinate); - } - - /// Sets the number of bits used to represent each vertex coordinate. - /// the number of bits to be set. Shall be 1, 2, 4, 8, 12, 16, 24, or 32. - public virtual void SetBitsPerCoordinate(int bitsPerCoordinate) { - GetPdfObject().Put(PdfName.BitsPerCoordinate, new PdfNumber(bitsPerCoordinate)); - SetModified(); - } - - /// Gets the number of bits used to represent each colour component. - /// the number of bits. Can be 1, 2, 4, 8, 12, or 16. - public virtual int GetBitsPerComponent() { - return (int)GetPdfObject().GetAsInt(PdfName.BitsPerComponent); - } - - /// Sets the number of bits used to represent each colour component. - /// the number of bits to be set. Shall be 1, 2, 4, 8, 12, or 16. - public virtual void SetBitsPerComponent(int bitsPerComponent) { - GetPdfObject().Put(PdfName.BitsPerComponent, new PdfNumber(bitsPerComponent)); - SetModified(); - } - - /// Gets the number of bits used to represent the edge flag for each vertex. - /// - /// Gets the number of bits used to represent the edge flag for each vertex. - /// But only the least significant 2 bits in each flag value shall be used. - /// The valid flag values are 0, 1, 2 or 3. - /// - /// the number of bits. Can be 2, 4 or 8. - public virtual int GetBitsPerFlag() { - return (int)GetPdfObject().GetAsInt(PdfName.BitsPerFlag); - } - - /// Sets the number of bits used to represent the edge flag for each vertex. - /// - /// Sets the number of bits used to represent the edge flag for each vertex. - /// But only the least significant 2 bits in each flag value shall be used. - /// The valid flag values are 0, 1, 2 or 3. - /// - /// the number of bits to be set. Shall be 2, 4 or 8. - public virtual void SetBitsPerFlag(int bitsPerFlag) { - GetPdfObject().Put(PdfName.BitsPerFlag, new PdfNumber(bitsPerFlag)); - SetModified(); - } - - /// - /// Gets the - /// - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. - /// - /// - /// Gets the - /// - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. The ranges shall be specified as follows: - /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. - /// Only one pair of color values shall be specified if a Function entry is present. - /// - /// - /// the - /// - /// Decode object. - /// - public virtual PdfArray GetDecode() { - return GetPdfObject().GetAsArray(PdfName.Decode); - } - - /// - /// Sets the - /// float[] - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. - /// - /// - /// Sets the - /// float[] - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. The ranges shall be specified as follows: - /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. - /// Only one pair of color values shall be specified if a Function entry is present. - /// - /// - /// the - /// float[] - /// of Decode object to set. - /// - public virtual void SetDecode(float[] decode) { - SetDecode(new PdfArray(decode)); - } - - /// - /// Sets the - /// - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. - /// - /// - /// Sets the - /// - /// of numbers specifying how to map vertex coordinates and colour components - /// into the appropriate ranges of values. The ranges shall be specified as follows: - /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. - /// Only one pair of color values shall be specified if a Function entry is present. - /// - /// - /// the - /// - /// Decode object to set. - /// - public virtual void SetDecode(PdfArray decode) { - GetPdfObject().Put(PdfName.Decode, decode); - SetModified(); - } - } - } -} diff --git a/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/AbstractPdfShading.cs b/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/AbstractPdfShading.cs new file mode 100644 index 0000000000..10653413e9 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/AbstractPdfShading.cs @@ -0,0 +1,257 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using iText.Kernel.Exceptions; +using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Colorspace; +using iText.Kernel.Pdf.Function; + +namespace iText.Kernel.Pdf.Colorspace.Shading { + /// The PdfShading class that represents the Shading Dictionary PDF object. + public abstract class AbstractPdfShading : PdfObjectWrapper { + /// + /// Creates the + /// + /// object from the existing + /// + /// with corresponding type. + /// + /// + /// + /// + /// from which the + /// + /// object will be created + /// + /// + /// Created + /// + /// object + /// + public static iText.Kernel.Pdf.Colorspace.Shading.AbstractPdfShading MakeShading(PdfDictionary shadingDictionary + ) { + if (!shadingDictionary.ContainsKey(PdfName.ShadingType)) { + throw new PdfException(KernelExceptionMessageConstant.SHADING_TYPE_NOT_FOUND); + } + if (!shadingDictionary.ContainsKey(PdfName.ColorSpace)) { + throw new PdfException(KernelExceptionMessageConstant.COLOR_SPACE_NOT_FOUND); + } + iText.Kernel.Pdf.Colorspace.Shading.AbstractPdfShading shading; + switch (shadingDictionary.GetAsNumber(PdfName.ShadingType).IntValue()) { + case ShadingType.FUNCTION_BASED: { + shading = new PdfFunctionBasedShading(shadingDictionary); + break; + } + + case ShadingType.AXIAL: { + shading = new PdfAxialShading(shadingDictionary); + break; + } + + case ShadingType.RADIAL: { + shading = new PdfRadialShading(shadingDictionary); + break; + } + + case ShadingType.FREE_FORM_GOURAUD_SHADED_TRIANGLE_MESH: { + if (!shadingDictionary.IsStream()) { + throw new PdfException(KernelExceptionMessageConstant.UNEXPECTED_SHADING_TYPE); + } + shading = new PdfFreeFormGouraudShadedTriangleShading((PdfStream)shadingDictionary); + break; + } + + case ShadingType.LATTICE_FORM_GOURAUD_SHADED_TRIANGLE_MESH: { + if (!shadingDictionary.IsStream()) { + throw new PdfException(KernelExceptionMessageConstant.UNEXPECTED_SHADING_TYPE); + } + shading = new PdfLatticeFormGouraudShadedTriangleShading((PdfStream)shadingDictionary); + break; + } + + case ShadingType.COONS_PATCH_MESH: { + if (!shadingDictionary.IsStream()) { + throw new PdfException(KernelExceptionMessageConstant.UNEXPECTED_SHADING_TYPE); + } + shading = new PdfCoonsPatchShading((PdfStream)shadingDictionary); + break; + } + + case ShadingType.TENSOR_PRODUCT_PATCH_MESH: { + if (!shadingDictionary.IsStream()) { + throw new PdfException(KernelExceptionMessageConstant.UNEXPECTED_SHADING_TYPE); + } + shading = new PdfTensorProductPatchShading((PdfStream)shadingDictionary); + break; + } + + default: { + throw new PdfException(KernelExceptionMessageConstant.UNEXPECTED_SHADING_TYPE); + } + } + return shading; + } + + /// + /// Creates the + /// + /// object from the existing + /// . + /// + /// + /// + /// + /// from which the + /// + /// object will be created + /// + protected internal AbstractPdfShading(PdfDictionary pdfObject) + : base(pdfObject) { + } + + /// + /// Creates the + /// + /// object from the existing + /// + /// , + /// using provided type and colorspace. + /// + /// + /// + /// + /// from which the + /// + /// object will be created + /// + /// + /// type with which this + /// + /// object will be created + /// + /// + /// + /// + /// with which this + /// + /// object will be created + /// + protected internal AbstractPdfShading(PdfDictionary pdfObject, int type, PdfColorSpace colorSpace) + : base(pdfObject) { + GetPdfObject().Put(PdfName.ShadingType, new PdfNumber(type)); + if (colorSpace is PdfSpecialCs.Pattern) { + throw new ArgumentException("colorSpace"); + } + GetPdfObject().Put(PdfName.ColorSpace, colorSpace.GetPdfObject()); + } + + /// Gets the shading type. + /// + /// int value of + /// + /// + public virtual int GetShadingType() { + return (int)GetPdfObject().GetAsInt(PdfName.ShadingType); + } + + /// Gets the color space in which colour values shall be expressed. + /// + /// + /// + /// Color space + /// + public virtual PdfObject GetColorSpace() { + return GetPdfObject().Get(PdfName.ColorSpace); + } + + /// + /// Gets the function PdfObject that represents color transitions + /// across the shading geometry. + /// + /// + /// + /// + /// Function + /// + public virtual PdfObject GetFunction() { + return GetPdfObject().Get(PdfName.Function); + } + + /// + /// Sets the function that represents color transitions + /// across the shading geometry as one object. + /// + /// + /// The + /// + /// to set + /// + public void SetFunction(IPdfFunction function) { + GetPdfObject().Put(PdfName.Function, function.GetAsPdfObject()); + SetModified(); + } + + /// + /// Sets the function object that represents color transitions + /// across the shading geometry as an array of functions. + /// + /// + /// The array of + /// + /// to be set + /// + public void SetFunction(IPdfFunction[] functions) { + PdfArray arr = new PdfArray(); + foreach (IPdfFunction func in functions) { + arr.Add(func.GetAsPdfObject()); + } + GetPdfObject().Put(PdfName.Function, arr); + SetModified(); + } + + /// + /// To manually flush a + /// PdfObject + /// behind this wrapper, you have to ensure + /// that this object is added to the document, i.e. it has an indirect reference. + /// + /// + /// To manually flush a + /// PdfObject + /// behind this wrapper, you have to ensure + /// that this object is added to the document, i.e. it has an indirect reference. + /// Basically this means that before flushing you need to explicitly call + /// . + /// For example: wrapperInstance.makeIndirect(document).flush(); + /// Note that not every wrapper require this, only those that have such warning in documentation. + /// + public sealed override void Flush() { + base.Flush(); + } + + /// + protected internal override bool IsWrappedObjectMustBeIndirect() { + return true; + } + } +} diff --git a/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/AbstractPdfShadingBlend.cs b/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/AbstractPdfShadingBlend.cs new file mode 100644 index 0000000000..f2cf510d50 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/AbstractPdfShadingBlend.cs @@ -0,0 +1,188 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Colorspace; + +namespace iText.Kernel.Pdf.Colorspace.Shading { + /// + /// The PdfShadingBlend class which extends + /// + /// and represents shadings which are + /// based on a blend, with Coords, Domain and Extend fields in the PDF object. + /// + public abstract class AbstractPdfShadingBlend : AbstractPdfShading { + /// + /// Gets the coords + /// + /// object. + /// + /// + /// the + /// + /// coords object + /// + public virtual PdfArray GetCoords() { + return GetPdfObject().GetAsArray(PdfName.Coords); + } + + /// + /// Sets the Coords object with the + /// + /// , + /// that specified the starting and the endings coordinates of thew axis, + /// expressed in the shading's target coordinate space. + /// + /// + /// the Chords + /// + /// to be set + /// + public void SetCoords(PdfArray coords) { + GetPdfObject().Put(PdfName.Coords, coords); + SetModified(); + } + + /// + /// Gets the + /// + /// of two + /// float + /// [t0, t1] that represent the limiting values of a parametric + /// variable t, that becomes an input of color function(s). + /// + /// + /// the + /// + /// of Domain object ([0.0 1.0] by default) + /// + public virtual PdfArray GetDomain() { + PdfArray domain = GetPdfObject().GetAsArray(PdfName.Domain); + if (domain == null) { + domain = new PdfArray(new float[] { 0, 1 }); + SetDomain(domain); + } + return domain; + } + + /// + /// Sets the Domain with the array of two + /// float + /// [t0, t1] that represent the limiting values + /// of a parametric variable t, that becomes an input of color function(s). + /// + /// first limit of variable t + /// second limit of variable t + public void SetDomain(float t0, float t1) { + SetDomain(new PdfArray(new float[] { t0, t1 })); + } + + /// + /// Sets the Domain with the + /// + /// of two + /// float + /// [t0, t1] that represent the limiting values + /// of a parametric variable t, that becomes an input of color function(s). + /// + /// + /// the + /// + /// that represents domain + /// + public void SetDomain(PdfArray domain) { + GetPdfObject().Put(PdfName.Domain, domain); + SetModified(); + } + + /// + /// Gets the + /// + /// of two + /// boolean + /// that specified whether to extend the shading + /// beyond the starting and ending points of the axis, respectively. + /// + /// + /// the + /// + /// of Extended object ([false false] by default) + /// + public virtual PdfArray GetExtend() { + PdfArray extend = GetPdfObject().GetAsArray(PdfName.Extend); + if (extend == null) { + extend = new PdfArray(new bool[] { false, false }); + SetExtend(extend); + } + return extend; + } + + /// + /// Sets the Extend object with the two + /// boolean + /// value. + /// + /// if true will extend shading beyond the starting point of Coords + /// if true will extend shading beyond the ending point of Coords + public void SetExtend(bool extendStart, bool extendEnd) { + SetExtend(new PdfArray(new bool[] { extendStart, extendEnd })); + } + + /// + /// Sets the Extend object with the + /// + /// of two + /// boolean. + /// + /// + /// Sets the Extend object with the + /// + /// of two + /// boolean. + /// If first is true shading will extend beyond the starting point of Coords. + /// If second is true shading will extend beyond the ending point of Coords. + /// + /// + /// the + /// + /// representing Extend object + /// + public void SetExtend(PdfArray extend) { + GetPdfObject().Put(PdfName.Extend, extend); + SetModified(); + } + + /// Constructor for PdfShadingBlend object using a PdfDictionary. + /// input PdfDictionary + protected internal AbstractPdfShadingBlend(PdfDictionary pdfObject) + : base(pdfObject) { + } + + /// Constructor for PdfShadingBlend object using PdfDictionary, shading type and colorspace value. + /// input PdfDictionary + /// shading type + /// color space + protected internal AbstractPdfShadingBlend(PdfDictionary pdfObject, int shadingType, PdfColorSpace cs) + : base(pdfObject, shadingType, cs) { + } + } +} diff --git a/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/AbstractPdfShadingMesh.cs b/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/AbstractPdfShadingMesh.cs new file mode 100644 index 0000000000..632fd0784a --- /dev/null +++ b/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/AbstractPdfShadingMesh.cs @@ -0,0 +1,144 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Colorspace; + +namespace iText.Kernel.Pdf.Colorspace.Shading { + /// + /// The PdfShadingMesh class which extends + /// + /// and represents shadings which are based on a mesh, + /// with BitsPerCoordinate, BitsPerComponent and Decode fields in the PDF object. + /// + public abstract class AbstractPdfShadingMesh : AbstractPdfShading { + /// Gets the number of bits used to represent each vertex coordinate. + /// the number of bits. Can be 1, 2, 4, 8, 12, 16, 24, or 32 + public virtual int GetBitsPerCoordinate() { + return (int)GetPdfObject().GetAsInt(PdfName.BitsPerCoordinate); + } + + /// Sets the number of bits used to represent each vertex coordinate. + /// the number of bits to be set. Shall be 1, 2, 4, 8, 12, 16, 24, or 32 + public void SetBitsPerCoordinate(int bitsPerCoordinate) { + GetPdfObject().Put(PdfName.BitsPerCoordinate, new PdfNumber(bitsPerCoordinate)); + SetModified(); + } + + /// Gets the number of bits used to represent each colour component. + /// the number of bits. Can be 1, 2, 4, 8, 12, or 16 + public virtual int GetBitsPerComponent() { + return (int)GetPdfObject().GetAsInt(PdfName.BitsPerComponent); + } + + /// Sets the number of bits used to represent each colour component. + /// the number of bits to be set. Shall be 1, 2, 4, 8, 12, or 16 + public void SetBitsPerComponent(int bitsPerComponent) { + GetPdfObject().Put(PdfName.BitsPerComponent, new PdfNumber(bitsPerComponent)); + SetModified(); + } + + /// + /// Gets the + /// + /// of numbers specifying how to map vertex coordinates and colour components + /// into the appropriate ranges of values. + /// + /// + /// Gets the + /// + /// of numbers specifying how to map vertex coordinates and colour components + /// into the appropriate ranges of values. The ranges shall be specified as follows: + /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. + /// Only one pair of color values shall be specified if a Function entry is present. + /// + /// + /// the + /// + /// Decode object + /// + public virtual PdfArray GetDecode() { + return GetPdfObject().GetAsArray(PdfName.Decode); + } + + /// + /// Sets the + /// float[] + /// of numbers specifying how to map vertex coordinates and colour components + /// into the appropriate ranges of values. + /// + /// + /// Sets the + /// float[] + /// of numbers specifying how to map vertex coordinates and colour components + /// into the appropriate ranges of values. The ranges shall be specified as follows: + /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. + /// Only one pair of color values shall be specified if a Function entry is present. + /// + /// + /// the + /// float[] + /// of Decode object to set + /// + public void SetDecode(float[] decode) { + SetDecode(new PdfArray(decode)); + } + + /// + /// Sets the + /// + /// of numbers specifying how to map vertex coordinates and colour components + /// into the appropriate ranges of values. + /// + /// + /// Sets the + /// + /// of numbers specifying how to map vertex coordinates and colour components + /// into the appropriate ranges of values. The ranges shall be specified as follows: + /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. + /// Only one pair of color values shall be specified if a Function entry is present. + /// + /// + /// the + /// + /// Decode object to set + /// + public void SetDecode(PdfArray decode) { + GetPdfObject().Put(PdfName.Decode, decode); + SetModified(); + } + + /// Constructor for PdfShadingBlend object using a PdfDictionary. + /// input PdfDictionary + protected internal AbstractPdfShadingMesh(PdfDictionary pdfObject) + : base(pdfObject) { + } + + /// Constructor for PdfShadingBlend object using a PdfDictionary, shading type and color space. + /// input PdfDictionary + /// shading type + /// color space + protected internal AbstractPdfShadingMesh(PdfDictionary pdfObject, int type, PdfColorSpace colorSpace) + : base(pdfObject, type, colorSpace) { + } + } +} diff --git a/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/AbstractPdfShadingMeshWithFlags.cs b/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/AbstractPdfShadingMeshWithFlags.cs new file mode 100644 index 0000000000..9db1ea87da --- /dev/null +++ b/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/AbstractPdfShadingMeshWithFlags.cs @@ -0,0 +1,75 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Colorspace; + +namespace iText.Kernel.Pdf.Colorspace.Shading { + /// + /// The PdfShadingMeshFlags class which extends + /// + /// and + /// + /// and represents shadings which are based on a mesh, with all fields from + /// + /// as well as BitsPerFlag in the PDF object. + /// + public abstract class AbstractPdfShadingMeshWithFlags : AbstractPdfShadingMesh { + /// Gets the number of bits used to represent the edge flag for each vertex. + /// + /// Gets the number of bits used to represent the edge flag for each vertex. + /// But only the least significant 2 bits in each flag value shall be used. + /// The valid flag values are 0, 1, 2 or 3. + /// + /// the number of bits. Can be 2, 4 or 8 + public virtual int GetBitsPerFlag() { + return (int)GetPdfObject().GetAsInt(PdfName.BitsPerFlag); + } + + /// Sets the number of bits used to represent the edge flag for each vertex. + /// + /// Sets the number of bits used to represent the edge flag for each vertex. + /// But only the least significant 2 bits in each flag value shall be used. + /// The valid flag values are 0, 1, 2 or 3. + /// + /// the number of bits to be set. Shall be 2, 4 or 8 + public void SetBitsPerFlag(int bitsPerFlag) { + GetPdfObject().Put(PdfName.BitsPerFlag, new PdfNumber(bitsPerFlag)); + SetModified(); + } + + /// Constructor for PdfShadingBlend object using a PdfDictionary. + /// input PdfDictionary + protected internal AbstractPdfShadingMeshWithFlags(PdfDictionary pdfObject) + : base(pdfObject) { + } + + /// Constructor for PdfShadingBlend object using a PdfDictionary, shading type and color space. + /// input PdfDictionary + /// shading type + /// color space + protected internal AbstractPdfShadingMeshWithFlags(PdfDictionary pdfObject, int type, PdfColorSpace colorSpace + ) + : base(pdfObject, type, colorSpace) { + } + } +} diff --git a/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/PdfAxialShading.cs b/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/PdfAxialShading.cs new file mode 100644 index 0000000000..befac6ed1f --- /dev/null +++ b/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/PdfAxialShading.cs @@ -0,0 +1,181 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Colorspace; +using iText.Kernel.Pdf.Function; + +namespace iText.Kernel.Pdf.Colorspace.Shading { + /// + /// The class that extends + /// + /// and + /// + /// classes + /// and is in charge of Shading Dictionary with axial type, that define a colour blend that varies along + /// a linear axis between two endpoints and extends indefinitely perpendicular to that axis. + /// + public class PdfAxialShading : AbstractPdfShadingBlend { + /// + /// Creates the new instance of the class from the existing + /// . + /// + /// + /// from which this + /// + /// will be created + /// + public PdfAxialShading(PdfDictionary pdfDictionary) + : base(pdfDictionary) { + } + + /// Creates the new instance of the class. + /// + /// the + /// + /// object in which colour values shall be expressed. + /// The special Pattern space isn't excepted + /// + /// the start coordinate of X axis expressed in the shading's target coordinate space + /// the start coordinate of Y axis expressed in the shading's target coordinate space + /// + /// the + /// float[] + /// that represents the color in the start point + /// + /// the end coordinate of X axis expressed in the shading's target coordinate space + /// the end coordinate of Y axis expressed in the shading's target coordinate space + /// + /// the + /// float[] + /// that represents the color in the end point + /// + public PdfAxialShading(PdfColorSpace cs, float x0, float y0, float[] color0, float x1, float y1, float[] color1 + ) + : base(new PdfDictionary(), ShadingType.AXIAL, cs) { + SetCoords(x0, y0, x1, y1); + IPdfFunction func = new PdfType2Function(new float[] { 0, 1 }, null, color0, color1, 1); + SetFunction(func); + } + + /// Creates the new instance of the class. + /// + /// the + /// + /// object in which colour values shall be expressed. + /// The special Pattern space isn't excepted + /// + /// the start coordinate of X axis expressed in the shading's target coordinate space + /// the start coordinate of Y axis expressed in the shading's target coordinate space + /// + /// the + /// float[] + /// that represents the color in the start point + /// + /// the end coordinate of X axis expressed in the shading's target coordinate space + /// the end coordinate of Y axis expressed in the shading's target coordinate space + /// + /// the + /// float[] + /// that represents the color in the end point + /// + /// + /// the array of two booleans that specified whether to extend the shading + /// beyond the starting and ending points of the axis, respectively + /// + public PdfAxialShading(PdfColorSpace cs, float x0, float y0, float[] color0, float x1, float y1, float[] color1 + , bool[] extend) + : this(cs, x0, y0, color0, x1, y1, color1) { + if (extend == null || extend.Length != 2) { + throw new ArgumentException("extend"); + } + SetExtend(extend[0], extend[1]); + } + + /// Creates the new instance of the class. + /// + /// the + /// + /// object in which colour values shall be expressed. + /// The special Pattern space isn't excepted + /// + /// + /// the + /// + /// of four numbers [x0 y0 x1 y1] that specified the starting + /// and the endings coordinates of thew axis, expressed in the shading's target coordinate space + /// + /// + /// the + /// + /// object, that is used to calculate color transitions + /// + public PdfAxialShading(PdfColorSpace cs, PdfArray coords, IPdfFunction function) + : this(cs, coords, null, function) { + } + + /// Creates the new instance of the class. + /// + /// the + /// + /// object in which colour values shall be expressed. + /// The special Pattern space isn't excepted + /// + /// + /// the + /// + /// of four numbers [x0 y0 x1 y1] that specified + /// the starting and the endings coordinates of thew axis, expressed + /// in the shading's target coordinate space + /// + /// + /// the + /// + /// of two numbers [t0 t1] specifying the limiting values + /// of a parametric variable t which is considered to vary linearly between + /// these two values and becomes the input argument to the colour function + /// + /// + /// the + /// + /// object, that is used to calculate color transitions + /// + public PdfAxialShading(PdfColorSpace cs, PdfArray coords, PdfArray domain, IPdfFunction function) + : base(new PdfDictionary(), ShadingType.AXIAL, cs) { + SetCoords(coords); + if (domain != null) { + SetDomain(domain); + } + SetFunction(function); + } + + /// Sets the Choords object with the four params expressed in the shading's target coordinate space. + /// the start coordinate of X axis to be set + /// the start coordinate of Y axis to be set + /// the end coordinate of X axis to be set + /// the end coordinate of Y axis to be set + public void SetCoords(float x0, float y0, float x1, float y1) { + SetCoords(new PdfArray(new float[] { x0, y0, x1, y1 })); + } + } +} diff --git a/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/PdfCoonsPatchShading.cs b/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/PdfCoonsPatchShading.cs new file mode 100644 index 0000000000..a7116617e6 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/PdfCoonsPatchShading.cs @@ -0,0 +1,149 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Colorspace; + +namespace iText.Kernel.Pdf.Colorspace.Shading { + /// + /// The class that extends + /// + /// , + /// + /// and + /// + /// classes and is in charge of Shading Dictionary with Coons Patch mesh type. + /// + /// + /// The class that extends + /// + /// , + /// + /// and + /// + /// classes and is in charge of Shading Dictionary with Coons Patch mesh type. + /// + /// This type of shading is constructed from one or more colour patches, each bounded by four cubic Bézier curves. + /// Degenerate Bézier curves are allowed and are useful for certain graphical effects. + /// At least one complete patch shall be specified. + /// + /// The shape of patch is defined by 12 control points. + /// + /// Colours are specified for each corner of the unit square, + /// and bilinear interpolation is used to fill in colours over the entire unit square. + /// + /// Coordinates are mapped from the unit square into a four-sided patch whose sides are not necessarily linear. + /// The mapping is continuous: the corners of the unit square map to corners of the patch + /// and the sides of the unit square map to sides of the patch. + /// + /// For the format of data stream, that defines patches (see ISO-320001 Table 85). + /// + /// If the shading dictionary contains a Function entry, the colour data for each corner of a patch + /// shall be specified by a single parametric value t rather than by n separate colour components c1...cn. + /// + public class PdfCoonsPatchShading : AbstractPdfShadingMeshWithFlags { + /// + /// Creates the new instance of the class from the existing + /// . + /// + /// + /// from which this + /// + /// will be created + /// + public PdfCoonsPatchShading(PdfStream pdfStream) + : base(pdfStream) { + } + + /// Creates the new instance of the class. + /// + /// the + /// + /// object in which colour values shall be expressed. + /// The special Pattern space isn't excepted + /// + /// + /// the number of bits used to represent each vertex coordinate. + /// The value shall be 1, 2, 4, 8, 12, 16, 24, or 32 + /// + /// + /// the number of bits used to represent each colour component. + /// The value shall be 1, 2, 4, 8, 12, or 16 + /// + /// + /// the number of bits used to represent the edge flag for each vertex. + /// The value of BitsPerFlag shall be 2, 4, or 8, + /// but only the least significant 2 bits in each flag value shall be used. + /// The value for the edge flag shall be 0, 1, 2 or 3 + /// + /// + /// the + /// int[] + /// of numbers specifying how to map vertex coordinates and colour components + /// into the appropriate ranges of values. The ranges shall be specified as follows: + /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. + /// Only one pair of color values shall be specified if a Function entry is present + /// + public PdfCoonsPatchShading(PdfColorSpace cs, int bitsPerCoordinate, int bitsPerComponent, int bitsPerFlag + , float[] decode) + : this(cs, bitsPerCoordinate, bitsPerComponent, bitsPerFlag, new PdfArray(decode)) { + } + + /// Creates the new instance of the class. + /// + /// the + /// + /// object in which colour values shall be expressed. + /// The special Pattern space isn't excepted + /// + /// + /// the number of bits used to represent each vertex coordinate. + /// The value shall be 1, 2, 4, 8, 12, 16, 24, or 32 + /// + /// + /// the number of bits used to represent each colour component. + /// The value shall be 1, 2, 4, 8, 12, or 16 + /// + /// + /// the number of bits used to represent the edge flag for each vertex. + /// The value of BitsPerFlag shall be 2, 4, or 8, + /// but only the least significant 2 bits in each flag value shall be used. + /// The value for the edge flag shall be 0, 1, 2 or 3 + /// + /// + /// the + /// + /// of numbers specifying how to map vertex coordinates and colour components + /// into the appropriate ranges of values. The ranges shall be specified as follows: + /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. + /// Only one pair of color values shall be specified if a Function entry is present + /// + public PdfCoonsPatchShading(PdfColorSpace cs, int bitsPerCoordinate, int bitsPerComponent, int bitsPerFlag + , PdfArray decode) + : base(new PdfStream(), ShadingType.COONS_PATCH_MESH, cs) { + SetBitsPerCoordinate(bitsPerCoordinate); + SetBitsPerComponent(bitsPerComponent); + SetBitsPerFlag(bitsPerFlag); + SetDecode(decode); + } + } +} diff --git a/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/PdfFreeFormGouraudShadedTriangleShading.cs b/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/PdfFreeFormGouraudShadedTriangleShading.cs new file mode 100644 index 0000000000..d38c935fb1 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/PdfFreeFormGouraudShadedTriangleShading.cs @@ -0,0 +1,148 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Colorspace; + +namespace iText.Kernel.Pdf.Colorspace.Shading { + /// + /// The class that extends + /// + /// , + /// + /// and + /// + /// classes and is in charge of Shading Dictionary + /// with free-form Gouraud-shaded triangle mesh type. + /// + /// + /// The class that extends + /// + /// , + /// + /// and + /// + /// classes and is in charge of Shading Dictionary + /// with free-form Gouraud-shaded triangle mesh type. + /// + /// The area to be shaded is defined by a path composed entirely of triangles. + /// The colour at each vertex of the triangles is specified, + /// and a technique known as Gouraud interpolation is used to colour the interiors. + /// + /// The object shall be represented as stream containing a sequence of vertex data. + /// Each vertex is specified by the following values, in the order shown: + /// f x y c1 ... cn where: + /// f - the vertex's edge flag, that determines the vertex is connected to other vertices of the triangle mesh. + /// For full description, see ISO-320001 Paragraph 8.7.4.5.5 + /// x, y - vertex's horizontal and vertical coordinates, expressed in the shading's target coordinate space. + /// c1...cn - vertex's colour components. + /// + /// If the shading dictionary includes a Function entry, only a single parametric value, t, + /// shall be specified for each vertex in place of the colour components c1...cn. + /// + public class PdfFreeFormGouraudShadedTriangleShading : AbstractPdfShadingMeshWithFlags { + /// + /// Creates the new instance of the class from the existing + /// . + /// + /// + /// from which this + /// + /// will be created + /// + public PdfFreeFormGouraudShadedTriangleShading(PdfStream pdfStream) + : base(pdfStream) { + } + + /// Creates the new instance of the class. + /// + /// the + /// + /// object in which colour values shall be expressed. + /// The special Pattern space isn't excepted. + /// + /// + /// the number of bits used to represent each vertex coordinate. + /// The value shall be 1, 2, 4, 8, 12, 16, 24, or 32 + /// + /// + /// the number of bits used to represent each colour component. + /// The value shall be 1, 2, 4, 8, 12, or 16 + /// + /// + /// the number of bits used to represent the edge flag for each vertex. + /// The value of BitsPerFlag shall be 2, 4, or 8, + /// but only the least significant 2 bits in each flag value shall be used. + /// The value for the edge flag shall be 0, 1, or 2 + /// + /// + /// the + /// int[] + /// of numbers specifying how to map vertex coordinates and colour components + /// into the appropriate ranges of values. The ranges shall be specified as follows: + /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. + /// Only one pair of color values shall be specified if a Function entry is present + /// + public PdfFreeFormGouraudShadedTriangleShading(PdfColorSpace cs, int bitsPerCoordinate, int bitsPerComponent + , int bitsPerFlag, float[] decode) + : this(cs, bitsPerCoordinate, bitsPerComponent, bitsPerFlag, new PdfArray(decode)) { + } + + /// Creates the new instance of the class. + /// + /// the + /// + /// object in which colour values shall be expressed. + /// The special Pattern space isn't excepted + /// + /// + /// the number of bits used to represent each vertex coordinate. + /// The value shall be 1, 2, 4, 8, 12, 16, 24, or 32 + /// + /// + /// the number of bits used to represent each colour component. + /// The value shall be 1, 2, 4, 8, 12, or 16 + /// + /// + /// the number of bits used to represent the edge flag for each vertex. + /// The value of BitsPerFlag shall be 2, 4, or 8, + /// but only the least significant 2 bits in each flag value shall be used. + /// The value for the edge flag shall be 0, 1, or 2 + /// + /// + /// the + /// + /// of numbers specifying how to map vertex coordinates and colour components + /// into the appropriate ranges of values. The ranges shall be specified as follows: + /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. + /// Only one pair of color values shall be specified if a Function entry is present + /// + public PdfFreeFormGouraudShadedTriangleShading(PdfColorSpace cs, int bitsPerCoordinate, int bitsPerComponent + , int bitsPerFlag, PdfArray decode) + : base(new PdfStream(), ShadingType.FREE_FORM_GOURAUD_SHADED_TRIANGLE_MESH, cs) { + SetBitsPerCoordinate(bitsPerCoordinate); + SetBitsPerComponent(bitsPerComponent); + SetBitsPerFlag(bitsPerFlag); + SetDecode(decode); + } + } +} diff --git a/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/PdfFunctionBasedShading.cs b/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/PdfFunctionBasedShading.cs new file mode 100644 index 0000000000..f5c4126b2b --- /dev/null +++ b/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/PdfFunctionBasedShading.cs @@ -0,0 +1,171 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Colorspace; +using iText.Kernel.Pdf.Function; + +namespace iText.Kernel.Pdf.Colorspace.Shading { + /// + /// The class that extends + /// + /// class and is in charge of Shading Dictionary + /// with function-based type, that defines color at every point in the domain by a specified mathematical function. + /// + public class PdfFunctionBasedShading : AbstractPdfShading { + /// + /// Creates the new instance of the class from the existing + /// . + /// + /// + /// from which this + /// + /// will be created + /// + public PdfFunctionBasedShading(PdfDictionary pdfDictionary) + : base(pdfDictionary) { + } + + /// Creates the new instance of the class. + /// + /// the + /// + /// object in which colour values shall be expressed + /// + /// + /// the + /// + /// , that is used to calculate color transitions + /// + public PdfFunctionBasedShading(PdfColorSpace colorSpace, IPdfFunction function) + : this(colorSpace.GetPdfObject(), function) { + } + + /// Creates the new instance of the class. + /// + /// the + /// + /// , that represents color space in which colour values shall be expressed + /// + /// + /// the + /// + /// , that is used to calculate color transitions + /// + public PdfFunctionBasedShading(PdfObject colorSpace, IPdfFunction function) + : base(new PdfDictionary(), ShadingType.FUNCTION_BASED, PdfColorSpace.MakeColorSpace(colorSpace)) { + SetFunction(function); + } + + /// + /// Gets the + /// + /// domain rectangle object that establishes an internal coordinate space + /// for the shading that is independent of the target coordinate space in which it shall be painted. + /// + /// + /// + /// + /// domain rectangle + /// + public virtual PdfArray GetDomain() { + return GetPdfObject().GetAsArray(PdfName.Domain); + } + + /// + /// Sets the + /// + /// domain rectangle object that establishes an internal coordinate space + /// for the shading that is independent of the target coordinate space in which it shall be painted. + /// + /// the Xmin coordinate of rectangle + /// the Xmax coordinate of rectangle + /// the Ymin coordinate of rectangle + /// the Ymax coordinate of rectangle + public virtual void SetDomain(float xmin, float xmax, float ymin, float ymax) { + SetDomain(new PdfArray(new float[] { xmin, xmax, ymin, ymax })); + } + + /// + /// Sets the + /// + /// domain rectangle object that establishes an internal coordinate space + /// for the shading that is independent of the target coordinate space in which it shall be painted. + /// + /// + /// the + /// + /// domain rectangle object to be set + /// + public virtual void SetDomain(PdfArray domain) { + GetPdfObject().Put(PdfName.Domain, domain); + SetModified(); + } + + /// + /// Gets the + /// + /// of floats that represents the transformation matrix that maps the domain rectangle + /// into a corresponding figure in the target coordinate space. + /// + /// + /// the + /// + /// of transformation matrix (identical matrix by default) + /// + public virtual PdfArray GetMatrix() { + PdfArray matrix = GetPdfObject().GetAsArray(PdfName.Matrix); + if (matrix == null) { + matrix = new PdfArray(new float[] { 1, 0, 0, 1, 0, 0 }); + SetMatrix(matrix); + } + return matrix; + } + + /// + /// Sets the array of floats that represents the transformation matrix that maps the domain rectangle + /// into a corresponding figure in the target coordinate space. + /// + /// + /// the + /// float[] + /// of transformation matrix to be set + /// + public virtual void SetMatrix(float[] matrix) { + SetMatrix(new PdfArray(matrix)); + } + + /// + /// Sets the array of floats that represents the transformation matrix that maps the domain rectangle + /// into a corresponding figure in the target coordinate space. + /// + /// + /// the + /// + /// transformation matrix object to be set + /// + public virtual void SetMatrix(PdfArray matrix) { + GetPdfObject().Put(PdfName.Matrix, matrix); + SetModified(); + } + } +} diff --git a/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/PdfLatticeFormGouraudShadedTriangleShading.cs b/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/PdfLatticeFormGouraudShadedTriangleShading.cs new file mode 100644 index 0000000000..db42e37882 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/PdfLatticeFormGouraudShadedTriangleShading.cs @@ -0,0 +1,154 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Colorspace; + +namespace iText.Kernel.Pdf.Colorspace.Shading { + /// + /// The class that extends + /// + /// and + /// + /// classes + /// and is in charge of Shading Dictionary with lattice-form Gouraud-shaded triangle mesh type. + /// + /// + /// The class that extends + /// + /// and + /// + /// classes + /// and is in charge of Shading Dictionary with lattice-form Gouraud-shaded triangle mesh type. + /// + /// This type is similar to + /// + /// but instead of using free-form geometry, + /// the vertices are arranged in a pseudorectangular lattice, + /// which is topologically equivalent to a rectangular grid. + /// The vertices are organized into rows, which need not be geometrically linear. + /// + /// The verticals data in stream is similar to + /// + /// , + /// except there is no edge flag. + /// + public class PdfLatticeFormGouraudShadedTriangleShading : AbstractPdfShadingMesh { + /// + /// Creates the new instance of the class from the existing + /// . + /// + /// + /// from which this + /// + /// will be created + /// + public PdfLatticeFormGouraudShadedTriangleShading(PdfStream pdfStream) + : base(pdfStream) { + } + + /// Creates the new instance of the class. + /// + /// the + /// + /// object in which colour values shall be expressed. + /// The special Pattern space isn't excepted + /// + /// + /// the number of bits used to represent each vertex coordinate. + /// The value shall be 1, 2, 4, 8, 12, 16, 24, or 32 + /// + /// + /// the number of bits used to represent each colour component. + /// The value shall be 1, 2, 4, 8, 12, or 16 + /// + /// + /// the number of vertices in each row of the lattice (shall be > 1). + /// The number of rows need not be specified + /// + /// + /// the + /// int[] + /// of numbers specifying how to map vertex coordinates and colour components + /// into the appropriate ranges of values. The ranges shall be specified as follows: + /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. + /// Only one pair of color values shall be specified if a Function entry is present + /// + public PdfLatticeFormGouraudShadedTriangleShading(PdfColorSpace cs, int bitsPerCoordinate, int bitsPerComponent + , int verticesPerRow, float[] decode) + : this(cs, bitsPerCoordinate, bitsPerComponent, verticesPerRow, new PdfArray(decode)) { + } + + /// Creates the new instance of the class. + /// + /// the + /// + /// object in which colour values shall be expressed. + /// The special Pattern space isn't excepted + /// + /// + /// the number of bits used to represent each vertex coordinate. + /// The value shall be 1, 2, 4, 8, 12, 16, 24, or 32 + /// + /// + /// the number of bits used to represent each colour component. + /// The value shall be 1, 2, 4, 8, 12, or 16 + /// + /// + /// the number of vertices in each row of the lattice (shall be > 1). + /// The number of rows need not be specified + /// + /// + /// the + /// + /// of numbers specifying how to map vertex coordinates and colour components + /// into the appropriate ranges of values. The ranges shall be specified as follows: + /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. + /// Only one pair of color values shall be specified if a Function entry is present + /// + public PdfLatticeFormGouraudShadedTriangleShading(PdfColorSpace cs, int bitsPerCoordinate, int bitsPerComponent + , int verticesPerRow, PdfArray decode) + : base(new PdfStream(), ShadingType.LATTICE_FORM_GOURAUD_SHADED_TRIANGLE_MESH, cs) { + SetBitsPerCoordinate(bitsPerCoordinate); + SetBitsPerComponent(bitsPerComponent); + SetVerticesPerRow(verticesPerRow); + SetDecode(decode); + } + + /// Gets the number of vertices in each row of the lattice. + /// the number of vertices. Can only be greater than 1 + public virtual int GetVerticesPerRow() { + return (int)GetPdfObject().GetAsInt(PdfName.VerticesPerRow); + } + + /// Sets the number of vertices in each row of the lattice. + /// + /// Sets the number of vertices in each row of the lattice. + /// The number of rows need not be specified. + /// + /// the number of vertices to be set. Shall be greater than 1 + public void SetVerticesPerRow(int verticesPerRow) { + GetPdfObject().Put(PdfName.VerticesPerRow, new PdfNumber(verticesPerRow)); + SetModified(); + } + } +} diff --git a/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/PdfRadialShading.cs b/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/PdfRadialShading.cs new file mode 100644 index 0000000000..7470a2b665 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/PdfRadialShading.cs @@ -0,0 +1,205 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Colorspace; +using iText.Kernel.Pdf.Function; + +namespace iText.Kernel.Pdf.Colorspace.Shading { + /// + /// The class that extends + /// + /// and + /// + /// classes + /// and is in charge of Shading Dictionary with radial type, that defines a colour blend that varies between two circles. + /// + /// + /// The class that extends + /// + /// and + /// + /// classes + /// and is in charge of Shading Dictionary with radial type, that defines a colour blend that varies between two circles. + /// + /// This type of shading shall not be used with an Indexed colour space + /// + public class PdfRadialShading : AbstractPdfShadingBlend { + /// + /// Creates the new instance of the class from the existing + /// . + /// + /// + /// from which this + /// + /// will be created + /// + public PdfRadialShading(PdfDictionary pdfDictionary) + : base(pdfDictionary) { + } + + /// Creates the new instance of the class. + /// + /// the + /// + /// object in which colour values shall be expressed. + /// The Indexed color space isn't excepted + /// + /// the X coordinate of starting circle's centre, expressed in in the shading’s target coordinate space + /// + /// the Y coordinate of starting circle's centre, expressed in in the shading’s target coordinate space + /// + /// + /// the radius of starting circle's centre, should be greater or equal to 0. + /// If 0 then starting circle is treated as point. + /// If both radii are 0, nothing shall be painted + /// + /// + /// the + /// float[] + /// that represents the color in the start circle + /// + /// the X coordinate of ending circle's centre, expressed in in the shading’s target coordinate space + /// + /// the Y coordinate of ending circle's centre, expressed in in the shading’s target coordinate space + /// + /// + /// the radius of ending circle's centre, should be greater or equal to 0. + /// If 0 then ending circle is treated as point. + /// If both radii are 0, nothing shall be painted + /// + /// + /// the + /// float[] + /// that represents the color in the end circle + /// + public PdfRadialShading(PdfColorSpace cs, float x0, float y0, float r0, float[] color0, float x1, float y1 + , float r1, float[] color1) + : base(new PdfDictionary(), ShadingType.RADIAL, cs) { + SetCoords(x0, y0, r0, x1, y1, r1); + IPdfFunction func = new PdfType2Function(new float[] { 0, 1 }, null, color0, color1, 1); + SetFunction(func); + } + + /// Creates the new instance of the class. + /// + /// the + /// + /// object in which colour values shall be expressed. + /// The Indexed color space isn't excepted + /// + /// the X coordinate of starting circle's centre, expressed in in the shading’s target coordinate space + /// + /// the Y coordinate of starting circle's centre, expressed in in the shading’s target coordinate space + /// + /// + /// the radius of starting circle's centre, should be greater or equal to 0. + /// If 0 then starting circle is treated as point. + /// If both radii are 0, nothing shall be painted + /// + /// + /// the + /// float[] + /// that represents the color in the start circle + /// + /// the X coordinate of ending circle's centre, expressed in in the shading’s target coordinate space + /// + /// the Y coordinate of ending circle's centre, expressed in in the shading’s target coordinate space + /// + /// + /// the radius of ending circle's centre, should be greater or equal to 0. + /// If 0 then ending circle is treated as point. + /// If both radii are 0, nothing shall be painted + /// + /// + /// the + /// float[] + /// that represents the color in the end circle + /// + /// + /// the array of two + /// boolean + /// that specified whether to extend the shading + /// beyond the starting and ending points of the axis, respectively + /// + public PdfRadialShading(PdfColorSpace cs, float x0, float y0, float r0, float[] color0, float x1, float y1 + , float r1, float[] color1, bool[] extend) + : this(cs, x0, y0, r0, color0, x1, y1, r1, color1) { + if (extend == null || extend.Length != 2) { + throw new ArgumentException("extend"); + } + SetExtend(extend[0], extend[1]); + } + + /// Creates the new instance of the class. + /// + /// the + /// + /// object in which colour values shall be expressed. + /// The Indexed color space isn't excepted + /// + /// + /// the + /// + /// of of six numbers [x0 y0 r0 x1 y1 r1], + /// specifying the centres and radii of the starting and ending circles, + /// expressed in the shading’s target coordinate space. + /// The radii r0 and r1 shall both be greater than or equal to 0. + /// If one radius is 0, the corresponding circle shall be treated as a point; + /// if both are 0, nothing shall be painted + /// + /// + /// the + /// + /// object, that is used to calculate color transitions + /// + public PdfRadialShading(PdfColorSpace cs, PdfArray coords, IPdfFunction function) + : base(new PdfDictionary(), ShadingType.RADIAL, cs) { + SetCoords(coords); + SetFunction(function); + } + + /// Sets the coords object. + /// the X coordinate of starting circle's centre, expressed in in the shading’s target coordinate space + /// + /// the Y coordinate of starting circle's centre, expressed in in the shading’s target coordinate space + /// + /// + /// the radius of starting circle's centre, should be greater or equal to 0. + /// If 0 then starting circle is treated as point. + /// If both radii are 0, nothing shall be painted + /// + /// the X coordinate of ending circle's centre, expressed in in the shading’s target coordinate space + /// + /// the Y coordinate of ending circle's centre, expressed in in the shading’s target coordinate space + /// + /// + /// the radius of ending circle's centre, should be greater or equal to 0. + /// If 0 then ending circle is treated as point. + /// If both radii are 0, nothing shall be painted + /// + public void SetCoords(float x0, float y0, float r0, float x1, float y1, float r1) { + SetCoords(new PdfArray(new float[] { x0, y0, r0, x1, y1, r1 })); + } + } +} diff --git a/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/PdfTensorProductPatchShading.cs b/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/PdfTensorProductPatchShading.cs new file mode 100644 index 0000000000..a1b6d64bae --- /dev/null +++ b/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/PdfTensorProductPatchShading.cs @@ -0,0 +1,140 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Colorspace; + +namespace iText.Kernel.Pdf.Colorspace.Shading { + /// + /// The class that extends + /// + /// , + /// + /// and + /// + /// classes and is in charge of Shading Dictionary + /// with Tensor-Product Patch mesh type. + /// + /// + /// The class that extends + /// + /// , + /// + /// and + /// + /// classes and is in charge of Shading Dictionary + /// with Tensor-Product Patch mesh type. + /// + /// This type of shading is identical to + /// + /// , except that it's based on a + /// bicubic tensor-product patch defined by 16 control points. + /// + /// For the format of data stream, that defines patches, see ISO-320001 Table 86. + /// + public class PdfTensorProductPatchShading : AbstractPdfShadingMeshWithFlags { + /// + /// Creates the new instance of the class from the existing + /// . + /// + /// + /// from which this + /// + /// will be created + /// + public PdfTensorProductPatchShading(PdfStream pdfStream) + : base(pdfStream) { + } + + /// Creates the new instance of the class. + /// + /// the + /// + /// object in which colour values shall be expressed. + /// The special Pattern space isn't excepted + /// + /// + /// the number of bits used to represent each vertex coordinate. + /// The value shall be 1, 2, 4, 8, 12, 16, 24, or 32 + /// + /// + /// the number of bits used to represent each colour component. + /// The value shall be 1, 2, 4, 8, 12, or 16 + /// + /// + /// the number of bits used to represent the edge flag for each vertex. + /// The value of BitsPerFlag shall be 2, 4, or 8, + /// but only the least significant 2 bits in each flag value shall be used. + /// The value for the edge flag shall be 0, 1, 2 or 3 + /// + /// + /// the + /// int[] + /// of numbers specifying how to map vertex coordinates and colour components + /// into the appropriate ranges of values. The ranges shall be specified as follows: + /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. + /// Only one pair of color values shall be specified if a Function entry is present + /// + public PdfTensorProductPatchShading(PdfColorSpace cs, int bitsPerCoordinate, int bitsPerComponent, int bitsPerFlag + , float[] decode) + : this(cs, bitsPerCoordinate, bitsPerComponent, bitsPerFlag, new PdfArray(decode)) { + } + + /// Creates the new instance of the class. + /// + /// the + /// + /// object in which colour values shall be expressed. + /// The special Pattern space isn't excepted + /// + /// + /// the number of bits used to represent each vertex coordinate. + /// The value shall be 1, 2, 4, 8, 12, 16, 24, or 32 + /// + /// + /// the number of bits used to represent each colour component. + /// The value shall be 1, 2, 4, 8, 12, or 16 + /// + /// + /// the number of bits used to represent the edge flag for each vertex. + /// The value of BitsPerFlag shall be 2, 4, or 8, + /// but only the least significant 2 bits in each flag value shall be used. + /// The value for the edge flag shall be 0, 1, 2 or 3 + /// + /// + /// the + /// + /// of numbers specifying how to map vertex coordinates and colour components + /// into the appropriate ranges of values. The ranges shall be specified as follows: + /// [x_min x_max y_min y_max c1_min c1_max … cn_min cn_max]. + /// Only one pair of color values shall be specified if a Function entry is present + /// + public PdfTensorProductPatchShading(PdfColorSpace cs, int bitsPerCoordinate, int bitsPerComponent, int bitsPerFlag + , PdfArray decode) + : base(new PdfStream(), ShadingType.TENSOR_PRODUCT_PATCH_MESH, cs) { + SetBitsPerCoordinate(bitsPerCoordinate); + SetBitsPerComponent(bitsPerComponent); + SetBitsPerFlag(bitsPerFlag); + SetDecode(decode); + } + } +} diff --git a/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/ShadingType.cs b/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/ShadingType.cs new file mode 100644 index 0000000000..a99a451687 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/pdf/colorspace/shading/ShadingType.cs @@ -0,0 +1,50 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +namespace iText.Kernel.Pdf.Colorspace.Shading { + /// The constants of shading type (see ISO-320001 Table 78). + public sealed class ShadingType { + /// The int value of function-based shading type + public const int FUNCTION_BASED = 1; + + /// The int value of axial shading type + public const int AXIAL = 2; + + /// The int value of radial shading type + public const int RADIAL = 3; + + /// The int value of free-form Gouraud-shaded triangle mesh shading type + public const int FREE_FORM_GOURAUD_SHADED_TRIANGLE_MESH = 4; + + /// The int value of lattice-form Gouraud-shaded triangle mesh shading type + public const int LATTICE_FORM_GOURAUD_SHADED_TRIANGLE_MESH = 5; + + /// The int value of coons patch meshes shading type + public const int COONS_PATCH_MESH = 6; + + /// The int value of tensor-product patch meshes shading type + public const int TENSOR_PRODUCT_PATCH_MESH = 7; + + private ShadingType() { + } + } +} diff --git a/itext/itext.kernel/itext/kernel/pdf/event/AbstractPdfDocumentEvent.cs b/itext/itext.kernel/itext/kernel/pdf/event/AbstractPdfDocumentEvent.cs new file mode 100644 index 0000000000..9a12534b70 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/pdf/event/AbstractPdfDocumentEvent.cs @@ -0,0 +1,85 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using iText.Commons.Actions; +using iText.Kernel.Pdf; + +namespace iText.Kernel.Pdf.Event { + /// Describes abstract PDF document event of the specified type. + /// + /// Describes abstract PDF document event of the specified type. + /// + /// Use + /// + /// to fire an event + /// and + /// + /// to register + /// + /// handler for that type of event. + /// + public abstract class AbstractPdfDocumentEvent : IEvent { + /// A type of event. + protected internal String type; + + private PdfDocument document; + + /// Creates an event of the specified type. + /// the type of event + protected internal AbstractPdfDocumentEvent(String type) { + this.type = type; + } + + /// Returns the type of this event. + /// type of this event + public virtual String GetType() { + return type; + } + + /// Retrieves the document associated with this event. + /// + /// + /// + /// that triggered this event + /// + public virtual PdfDocument GetDocument() { + return document; + } + + /// Sets the document associated with this event. + /// + /// + /// + /// that triggered this event + /// + /// + /// this + /// + /// instance + /// + public virtual iText.Kernel.Pdf.Event.AbstractPdfDocumentEvent SetDocument(PdfDocument document) { + this.document = document; + return this; + } + } +} diff --git a/itext/itext.kernel/itext/kernel/pdf/event/AbstractPdfDocumentEventHandler.cs b/itext/itext.kernel/itext/kernel/pdf/event/AbstractPdfDocumentEventHandler.cs new file mode 100644 index 0000000000..25f283aa23 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/pdf/event/AbstractPdfDocumentEventHandler.cs @@ -0,0 +1,102 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using System.Collections.Generic; +using iText.Commons.Actions; + +namespace iText.Kernel.Pdf.Event { + /// Base class for PDF document events handling based on the event type. + /// + /// Base class for PDF document events handling based on the event type. + /// + /// Handles + /// + /// event fired by + /// . + /// Use + /// + /// to register this handler for + /// specific type of event. + /// + public abstract class AbstractPdfDocumentEventHandler : IEventHandler { + private readonly ICollection types = new HashSet(); + + /// + /// Creates new + /// + /// instance. + /// + /// + /// Creates new + /// + /// instance. + /// + /// By default, this instance handles all types of the + /// + /// events. For specific types + /// handling, use + /// + /// method. + /// + protected internal AbstractPdfDocumentEventHandler() { + } + + /// + /// Adds new event type to handle by this + /// + /// instance. + /// + /// + /// the + /// + /// type to handle + /// + /// + /// this + /// + /// instance + /// + public virtual iText.Kernel.Pdf.Event.AbstractPdfDocumentEventHandler AddType(String type) { + this.types.Add(type); + return this; + } + + public virtual void OnEvent(IEvent @event) { + if (!(@event is AbstractPdfDocumentEvent)) { + return; + } + AbstractPdfDocumentEvent iTextEvent = (AbstractPdfDocumentEvent)@event; + if (types.IsEmpty() || types.Contains(iTextEvent.GetType())) { + OnAcceptedEvent(iTextEvent); + } + } + + /// Handles the accepted event. + /// + /// + /// + /// to handle + /// + protected internal abstract void OnAcceptedEvent(AbstractPdfDocumentEvent @event); + } +} diff --git a/itext/itext.kernel/itext/kernel/events/PdfDocumentEvent.cs b/itext/itext.kernel/itext/kernel/pdf/event/PdfDocumentEvent.cs similarity index 80% rename from itext/itext.kernel/itext/kernel/events/PdfDocumentEvent.cs rename to itext/itext.kernel/itext/kernel/pdf/event/PdfDocumentEvent.cs index 4da09ae97c..87e844f5a5 100644 --- a/itext/itext.kernel/itext/kernel/events/PdfDocumentEvent.cs +++ b/itext/itext.kernel/itext/kernel/pdf/event/PdfDocumentEvent.cs @@ -23,9 +23,9 @@ You should have received a copy of the GNU Affero General Public License using System; using iText.Kernel.Pdf; -namespace iText.Kernel.Events { +namespace iText.Kernel.Pdf.Event { /// Event dispatched by PdfDocument. - public class PdfDocumentEvent : Event { + public class PdfDocumentEvent : AbstractPdfDocumentEvent { /// Dispatched after page is created. public const String START_PAGE = "StartPdfPage"; @@ -43,18 +43,19 @@ public class PdfDocumentEvent : Event { /// public const String END_PAGE = "EndPdfPage"; + /// Dispatched before writer is closed. + public const String START_WRITER_CLOSING = "StartWriterClosing"; + + /// Dispatched after writer is flushed to a document. + public const String START_DOCUMENT_CLOSING = "StartDocumentClosing"; + /// The PdfPage associated with this event. protected internal PdfPage page; - /// The PdfDocument associated with this event. - private PdfDocument document; - /// Creates a PdfDocumentEvent. /// type of the event that fired this event - /// document that fired this event - public PdfDocumentEvent(String type, PdfDocument document) + public PdfDocumentEvent(String type) : base(type) { - this.document = document; } /// Creates a PdfDocumentEvent. @@ -63,13 +64,6 @@ public PdfDocumentEvent(String type, PdfDocument document) public PdfDocumentEvent(String type, PdfPage page) : base(type) { this.page = page; - this.document = page.GetDocument(); - } - - /// Returns the PdfDocument associated with this event. - /// the PdfDocument associated with this event - public virtual PdfDocument GetDocument() { - return document; } /// Returns the PdfPage associated with this event. diff --git a/itext/itext.kernel/itext/kernel/pdf/extgstate/PdfExtGState.cs b/itext/itext.kernel/itext/kernel/pdf/extgstate/PdfExtGState.cs index 7855786922..c473b01ed6 100644 --- a/itext/itext.kernel/itext/kernel/pdf/extgstate/PdfExtGState.cs +++ b/itext/itext.kernel/itext/kernel/pdf/extgstate/PdfExtGState.cs @@ -31,67 +31,67 @@ namespace iText.Kernel.Pdf.Extgstate { public class PdfExtGState : PdfObjectWrapper { /// Standard separable blend mode. /// Standard separable blend mode. See ISO-320001, table 136 - public static PdfName BM_NORMAL = PdfName.Normal; + public static readonly PdfName BM_NORMAL = PdfName.Normal; /// Standard separable blend mode. /// Standard separable blend mode. See ISO-320001, table 136 - public static PdfName BM_MULTIPLY = PdfName.Multiply; + public static readonly PdfName BM_MULTIPLY = PdfName.Multiply; /// Standard separable blend mode. /// Standard separable blend mode. See ISO-320001, table 136 - public static PdfName BM_SCREEN = PdfName.Screen; + public static readonly PdfName BM_SCREEN = PdfName.Screen; /// Standard separable blend mode. /// Standard separable blend mode. See ISO-320001, table 136 - public static PdfName BM_OVERLAY = PdfName.Overlay; + public static readonly PdfName BM_OVERLAY = PdfName.Overlay; /// Standard separable blend mode. /// Standard separable blend mode. See ISO-320001, table 136 - public static PdfName BM_DARKEN = PdfName.Darken; + public static readonly PdfName BM_DARKEN = PdfName.Darken; /// Standard separable blend mode. /// Standard separable blend mode. See ISO-320001, table 136 - public static PdfName BM_LIGHTEN = PdfName.Lighten; + public static readonly PdfName BM_LIGHTEN = PdfName.Lighten; /// Standard separable blend mode. /// Standard separable blend mode. See ISO-320001, table 136 - public static PdfName BM_COLOR_DODGE = PdfName.ColorDodge; + public static readonly PdfName BM_COLOR_DODGE = PdfName.ColorDodge; /// Standard separable blend mode. /// Standard separable blend mode. See ISO-320001, table 136 - public static PdfName BM_COLOR_BURN = PdfName.ColorBurn; + public static readonly PdfName BM_COLOR_BURN = PdfName.ColorBurn; /// Standard separable blend mode. /// Standard separable blend mode. See ISO-320001, table 136 - public static PdfName BM_HARD_LIGHT = PdfName.HardLight; + public static readonly PdfName BM_HARD_LIGHT = PdfName.HardLight; /// Standard separable blend mode. /// Standard separable blend mode. See ISO-320001, table 136 - public static PdfName BM_SOFT_LIGHT = PdfName.SoftLight; + public static readonly PdfName BM_SOFT_LIGHT = PdfName.SoftLight; /// Standard separable blend mode. /// Standard separable blend mode. See ISO-320001, table 136 - public static PdfName BM_DIFFERENCE = PdfName.Difference; + public static readonly PdfName BM_DIFFERENCE = PdfName.Difference; /// Standard separable blend mode. /// Standard separable blend mode. See ISO-320001, table 136 - public static PdfName BM_EXCLUSION = PdfName.Exclusion; + public static readonly PdfName BM_EXCLUSION = PdfName.Exclusion; /// Standard nonseparable blend mode. /// Standard nonseparable blend mode. See ISO-320001, table 137 - public static PdfName BM_HUE = PdfName.Hue; + public static readonly PdfName BM_HUE = PdfName.Hue; /// Standard nonseparable blend mode. /// Standard nonseparable blend mode. See ISO-320001, table 137 - public static PdfName BM_SATURATION = PdfName.Saturation; + public static readonly PdfName BM_SATURATION = PdfName.Saturation; /// Standard nonseparable blend mode. /// Standard nonseparable blend mode. See ISO-320001, table 137 - public static PdfName BM_COLOR = PdfName.Color; + public static readonly PdfName BM_COLOR = PdfName.Color; /// Standard nonseparable blend mode. /// Standard nonseparable blend mode. See ISO-320001, table 137 - public static PdfName BM_LUMINOSITY = PdfName.Luminosity; + public static readonly PdfName BM_LUMINOSITY = PdfName.Luminosity; /// /// Create instance of graphics state parameter dictionary wrapper diff --git a/itext/itext.kernel/itext/kernel/pdf/filters/DoNothingFilter.cs b/itext/itext.kernel/itext/kernel/pdf/filters/DoNothingFilter.cs index a0cedfff05..1263b7af92 100644 --- a/itext/itext.kernel/itext/kernel/pdf/filters/DoNothingFilter.cs +++ b/itext/itext.kernel/itext/kernel/pdf/filters/DoNothingFilter.cs @@ -25,11 +25,8 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Kernel.Pdf.Filters { /// A filter that doesn't modify the stream at all public class DoNothingFilter : IFilterHandler { - private PdfName lastFilterName; - public virtual byte[] Decode(byte[] b, PdfName filterName, PdfObject decodeParams, PdfDictionary streamDictionary ) { - lastFilterName = filterName; return b; } } diff --git a/itext/itext.kernel/itext/kernel/pdf/layer/PdfLayer.cs b/itext/itext.kernel/itext/kernel/pdf/layer/PdfLayer.cs index dc677a1ed5..de5a67994a 100644 --- a/itext/itext.kernel/itext/kernel/pdf/layer/PdfLayer.cs +++ b/itext/itext.kernel/itext/kernel/pdf/layer/PdfLayer.cs @@ -24,6 +24,7 @@ You should have received a copy of the GNU Affero General Public License using System.Collections.Generic; using iText.Commons.Utils; using iText.IO.Font; +using iText.Kernel.Exceptions; using iText.Kernel.Pdf; namespace iText.Kernel.Pdf.Layer { @@ -114,8 +115,11 @@ public static void AddOCGRadioGroup(PdfDocument document, IListAdds a child layer. Nested layers can only have one parent. /// the child layer public virtual void AddChild(iText.Kernel.Pdf.Layer.PdfLayer childLayer) { + //TODO DEVSIX-8490 implement multiple parent support if (childLayer.parent != null) { - throw new ArgumentException("Illegal argument: childLayer"); + PdfIndirectReference @ref = childLayer.GetIndirectReference(); + throw new PdfException(MessageFormatUtil.Format(KernelExceptionMessageConstant.UNABLE_TO_ADD_SECOND_PARENT_LAYER + , @ref.ToString())); } childLayer.parent = this; if (children == null) { diff --git a/itext/itext.kernel/itext/kernel/pdf/layer/PdfOCProperties.cs b/itext/itext.kernel/itext/kernel/pdf/layer/PdfOCProperties.cs index 3bfbb72e00..f61c976b11 100644 --- a/itext/itext.kernel/itext/kernel/pdf/layer/PdfOCProperties.cs +++ b/itext/itext.kernel/itext/kernel/pdf/layer/PdfOCProperties.cs @@ -26,6 +26,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons; using iText.Commons.Utils; using iText.IO.Font; +using iText.Kernel.Exceptions; using iText.Kernel.Logs; using iText.Kernel.Pdf; @@ -51,6 +52,12 @@ public class PdfOCProperties : PdfObjectWrapper { private IList layers = new List(); + //TODO DEVSIX-8490 remove this field when implemented + private ICollection references; + + //TODO DEVSIX-8490 remove this field when implemented + private bool isDuplicateRemoved; + /// Creates a new PdfOCProperties instance. /// the document the optional content belongs to public PdfOCProperties(PdfDocument document) @@ -406,7 +413,14 @@ private void ReadLayersFromDictionary() { } PdfArray orderArray = d.GetAsArray(PdfName.Order); if (orderArray != null && !orderArray.IsEmpty()) { + references = new HashSet(); + isDuplicateRemoved = false; ReadOrderFromDictionary(null, orderArray, layerMap); + //TODO DEVSIX-8490 remove this check when implemented + if (isDuplicateRemoved) { + ILogger logger = ITextLogManager.GetLogger(typeof(iText.Kernel.Pdf.Layer.PdfOCProperties)); + logger.LogWarning(KernelLogMessageConstant.DUPLICATE_ENTRIES_IN_ORDER_ARRAY_REMOVED); + } } } // Add the layers which should not be displayed on the panel to the order list @@ -424,7 +438,25 @@ private void ReadOrderFromDictionary(PdfLayer parent, PdfArray orderArray, IDict PdfObject item = orderArray.Get(i); if (item.GetObjectType() == PdfObject.DICTIONARY) { PdfLayer layer = layerMap.Get(item.GetIndirectReference()); - if (layer != null) { + if (layer == null) { + continue; + } + //TODO DEVSIX-8490 remove this check and it statement when implemented + if (references.Contains(layer.GetIndirectReference())) { + //We want to check if this duplicate layer has childLayers, if it has - throw an exception, + // else just don't add this layer. + if (i + 1 < orderArray.Size() && orderArray.Get(i + 1).GetObjectType() == PdfObject.ARRAY) { + PdfArray nextArray = orderArray.GetAsArray(i + 1); + if (nextArray.Size() > 0 && nextArray.Get(0).GetObjectType() != PdfObject.STRING) { + PdfIndirectReference @ref = layer.GetIndirectReference(); + throw new PdfException(MessageFormatUtil.Format(KernelExceptionMessageConstant.UNABLE_TO_REMOVE_DUPLICATE_LAYER + , @ref.ToString())); + } + } + isDuplicateRemoved = true; + } + else { + references.Add(layer.GetIndirectReference()); layers.Add(layer); layer.onPanel = true; if (parent != null) { diff --git a/itext/itext.kernel/itext/kernel/pdf/tagging/McrCheckUtil.cs b/itext/itext.kernel/itext/kernel/pdf/tagging/McrCheckUtil.cs index 9bc68faeeb..324c66b7a3 100644 --- a/itext/itext.kernel/itext/kernel/pdf/tagging/McrCheckUtil.cs +++ b/itext/itext.kernel/itext/kernel/pdf/tagging/McrCheckUtil.cs @@ -64,8 +64,11 @@ public McrTagHandler() { } //empty constructor - /// - public virtual void NextElement(IStructureNode elem) { + public virtual bool Accept(IStructureNode node) { + return node != null; + } + + public virtual void ProcessElement(IStructureNode elem) { if ((elem is PdfMcr)) { haveMcr = true; } diff --git a/itext/itext.kernel/itext/kernel/pdf/tagging/ParentTreeHandler.cs b/itext/itext.kernel/itext/kernel/pdf/tagging/ParentTreeHandler.cs index 81a1b8f662..3f9561c365 100644 --- a/itext/itext.kernel/itext/kernel/pdf/tagging/ParentTreeHandler.cs +++ b/itext/itext.kernel/itext/kernel/pdf/tagging/ParentTreeHandler.cs @@ -28,6 +28,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Kernel.Exceptions; using iText.Kernel.Logs; using iText.Kernel.Pdf; +using iText.Kernel.Validation.Context; namespace iText.Kernel.Pdf.Tagging { //\cond DO_NOT_DOCUMENT @@ -368,7 +369,7 @@ private bool UpdateStructParentTreeForContentStreamEntries(IDictionaryA wrapper for structure element dictionaries (ISO-32000 14.7.2 "Structure Hierarchy"). @@ -593,7 +594,7 @@ public override void Flush() { } PdfDocument doc = GetDocument(); if (doc != null) { - doc.CheckIsoConformance(GetPdfObject(), IsoKey.TAG_STRUCTURE_ELEMENT); + doc.CheckIsoConformance(new TagStructElementValidationContext(GetPdfObject())); } base.Flush(); } diff --git a/itext/itext.kernel/itext/kernel/pdf/tagging/PdfStructIdTree.cs b/itext/itext.kernel/itext/kernel/pdf/tagging/PdfStructIdTree.cs index 68cc244ac9..ac10fee0ea 100644 --- a/itext/itext.kernel/itext/kernel/pdf/tagging/PdfStructIdTree.cs +++ b/itext/itext.kernel/itext/kernel/pdf/tagging/PdfStructIdTree.cs @@ -21,6 +21,7 @@ You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ using iText.Kernel.Pdf; +using iText.Kernel.Validation.Context; namespace iText.Kernel.Pdf.Tagging { /// Models the tree of structure element IDs. @@ -81,7 +82,8 @@ public virtual PdfStructElem GetStructElemById(byte[] id) { } public override void AddEntry(PdfString key, PdfObject value) { - base.AddEntry(key, value, (pdfDoc) => pdfDoc.CheckIsoConformance(key, IsoKey.DUPLICATE_ID_ENTRY)); + base.AddEntry(key, value, (pdfDoc) => pdfDoc.CheckIsoConformance(new DuplicateIdEntryValidationContext(key + ))); } } } diff --git a/itext/itext.kernel/itext/kernel/pdf/tagging/PdfStructTreeRoot.cs b/itext/itext.kernel/itext/kernel/pdf/tagging/PdfStructTreeRoot.cs index 7a6d371016..1c99ee9f07 100644 --- a/itext/itext.kernel/itext/kernel/pdf/tagging/PdfStructTreeRoot.cs +++ b/itext/itext.kernel/itext/kernel/pdf/tagging/PdfStructTreeRoot.cs @@ -369,18 +369,6 @@ public virtual PdfMcr FindMcrByMcid(PdfDictionary pageDict, int mcid) { return GetParentTreeHandler().FindMcrByMcid(pageDict, mcid); } - public virtual PdfMcr FindMcrByMcid(PdfDocument document, int mcid) { - int amountOfPages = document.GetNumberOfPages(); - for (int i = 1; i <= amountOfPages; ++i) { - PdfPage page = document.GetPage(i); - PdfMcr mcr = FindMcrByMcid(page.GetPdfObject(), mcid); - if (mcr != null) { - return mcr; - } - } - return null; - } - public virtual PdfObjRef FindObjRefByStructParentIndex(PdfDictionary pageDict, int structParentIndex) { return GetParentTreeHandler().FindObjRefByStructParentIndex(pageDict, structParentIndex); } @@ -599,8 +587,7 @@ protected internal override bool IsWrappedObjectMustBeIndirect() { } private static void FlushAllKids(iText.Kernel.Pdf.Tagging.PdfStructTreeRoot elem) { - TagTreeIterator iterator = new TagTreeIterator(elem, new TagTreeIteratorAvoidDuplicatesApprover(), TagTreeIterator.TreeTraversalOrder - .POST_ORDER); + TagTreeIterator iterator = new TagTreeIterator(elem, TagTreeIterator.TreeTraversalOrder.POST_ORDER); iterator.AddHandler(new TagTreeIteratorFlusher()); iterator.Traverse(); } diff --git a/itext/itext.kernel/itext/kernel/pdf/tagging/StructureTreeCopier.cs b/itext/itext.kernel/itext/kernel/pdf/tagging/StructureTreeCopier.cs index 520febff18..f66554a703 100644 --- a/itext/itext.kernel/itext/kernel/pdf/tagging/StructureTreeCopier.cs +++ b/itext/itext.kernel/itext/kernel/pdf/tagging/StructureTreeCopier.cs @@ -634,11 +634,12 @@ private static PdfDictionary GetTopmostParent(PdfMcr mcr) { } private static IList RetrieveParents(PdfMcr mcr, bool all) { - IList parents = new List(); + ICollection parents = new LinkedHashSet(); IStructureNode firstParent = mcr.GetParent(); PdfDictionary previous = null; PdfDictionary current = firstParent is PdfStructElem ? ((PdfStructElem)firstParent).GetPdfObject() : null; - while (current != null && !PdfName.StructTreeRoot.Equals(current.GetAsName(PdfName.Type))) { + while (current != null && !PdfName.StructTreeRoot.Equals(current.GetAsName(PdfName.Type)) && !parents.Contains + (current)) { if (all) { parents.Add(current); } @@ -648,7 +649,7 @@ private static IList RetrieveParents(PdfMcr mcr, bool all) { if (!all) { parents.Add(previous); } - return parents; + return new List(parents); } //\cond DO_NOT_DOCUMENT diff --git a/itext/itext.kernel/itext/kernel/pdf/tagutils/TagTreeIteratorAvoidDuplicatesApprover.cs b/itext/itext.kernel/itext/kernel/pdf/tagutils/AbstractAvoidDuplicatesTagTreeIteratorHandler.cs similarity index 60% rename from itext/itext.kernel/itext/kernel/pdf/tagutils/TagTreeIteratorAvoidDuplicatesApprover.cs rename to itext/itext.kernel/itext/kernel/pdf/tagutils/AbstractAvoidDuplicatesTagTreeIteratorHandler.cs index b3688c6bd5..151df950a7 100644 --- a/itext/itext.kernel/itext/kernel/pdf/tagutils/TagTreeIteratorAvoidDuplicatesApprover.cs +++ b/itext/itext.kernel/itext/kernel/pdf/tagutils/AbstractAvoidDuplicatesTagTreeIteratorHandler.cs @@ -26,43 +26,40 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Kernel.Pdf.Tagutils { /// - /// Element checker for + /// Handler for /// . /// /// - /// Element checker for + /// Handler for /// . /// It is used to check whether specific element should be traversed. - /// It doesn't approve elements which have been traversed before. + /// It doesn't accept elements which have been traversed before. /// - public class TagTreeIteratorAvoidDuplicatesApprover : TagTreeIteratorElementApprover { + public abstract class AbstractAvoidDuplicatesTagTreeIteratorHandler : ITagTreeIteratorHandler { private readonly ICollection processedObjects = new HashSet(); - /// - /// Creates a new instance of - /// - /// - public TagTreeIteratorAvoidDuplicatesApprover() - : base() { - } - - /// - public override bool Approve(IStructureNode elem) { - if (elem is PdfStructTreeRoot) { + public virtual bool Accept(IStructureNode node) { + if (node is PdfStructTreeRoot) { return true; } - if (!base.Approve(elem) || !(elem is PdfStructElem)) { - return false; - } - PdfObject obj = ((PdfStructElem)elem).GetPdfObject(); - bool isProcessed = processedObjects.Contains(obj); - if (isProcessed) { - return false; - } else { - processedObjects.Add(obj); - return true; + if (!(node is PdfStructElem)) { + return false; + } + else { + PdfObject obj = ((PdfStructElem)node).GetPdfObject(); + bool isProcessed = processedObjects.Contains(obj); + if (isProcessed) { + return false; + } + else { + processedObjects.Add(obj); + return true; + } + } } } + + public abstract void ProcessElement(IStructureNode arg1); } } diff --git a/itext/itext.kernel/itext/kernel/pdf/tagutils/ITagTreeIteratorHandler.cs b/itext/itext.kernel/itext/kernel/pdf/tagutils/ITagTreeIteratorHandler.cs index 3ff85d6f3b..2c4c5b62ec 100644 --- a/itext/itext.kernel/itext/kernel/pdf/tagutils/ITagTreeIteratorHandler.cs +++ b/itext/itext.kernel/itext/kernel/pdf/tagutils/ITagTreeIteratorHandler.cs @@ -33,8 +33,19 @@ namespace iText.Kernel.Pdf.Tagutils { /// Is used to handle specific events during the traversal. /// public interface ITagTreeIteratorHandler { - /// Called when the next element is reached during the traversal. - /// the next element - void NextElement(IStructureNode elem); + /// Checks whether the element should be traversed. + /// the element to check + /// + /// + /// + /// if the iteration should be continued, + /// + /// otherwise + /// + bool Accept(IStructureNode node); + + /// Called when the next element is reached during the traversal to process it. + /// the element to process + void ProcessElement(IStructureNode elem); } } diff --git a/itext/itext.kernel/itext/kernel/pdf/tagutils/RootTagNormalizer.cs b/itext/itext.kernel/itext/kernel/pdf/tagutils/RootTagNormalizer.cs index b3deb89bd6..ec08ccc492 100644 --- a/itext/itext.kernel/itext/kernel/pdf/tagutils/RootTagNormalizer.cs +++ b/itext/itext.kernel/itext/kernel/pdf/tagutils/RootTagNormalizer.cs @@ -113,8 +113,10 @@ private void AddStructTreeRootKidsToTheRootTag(IList rootKids) { } // This boolean is used to "flatten" possible deep "stacking" of the tag structure in case of the multiple pages copying operations. // This could happen due to the wrapping of all the kids in the createNewRootTag or ensureExistingRootTagIsDocument methods. - // And therefore, we don't need here to resolve mappings, because we exactly know which role we set. - bool kidIsDocument = PdfName.Document.Equals(kid.GetRole()); + IRoleMappingResolver mapping = kid.GetRole() == null ? null : context.ResolveMappingToStandardOrDomainSpecificRole + (kid.GetRole().GetValue(), rootTagElement.GetNamespace()); + bool kidIsDocument = mapping != null && mapping.CurrentRoleIsStandard() && StandardRoles.DOCUMENT.Equals(mapping + .GetRole()); if (kidIsDocument && kid.GetNamespace() != null && context.TargetTagStructureVersionIs2()) { // we flatten only tags of document role in standard structure namespace String kidNamespaceName = kid.GetNamespace().GetNamespaceName(); diff --git a/itext/itext.kernel/itext/kernel/pdf/tagutils/TagTreeIterator.cs b/itext/itext.kernel/itext/kernel/pdf/tagutils/TagTreeIterator.cs index 1ccf6c8faa..709c56df2c 100644 --- a/itext/itext.kernel/itext/kernel/pdf/tagutils/TagTreeIterator.cs +++ b/itext/itext.kernel/itext/kernel/pdf/tagutils/TagTreeIterator.cs @@ -38,8 +38,6 @@ public class TagTreeIterator { private readonly ICollection handlerList; - private readonly TagTreeIteratorElementApprover approver; - private readonly TagTreeIterator.TreeTraversalOrder traversalOrder; /// @@ -49,36 +47,24 @@ public class TagTreeIterator { /// /// Creates a new instance of /// - /// . It will use - /// - /// to filter - /// elements and TreeTraversalOrder.PRE_ORDER for tree traversal. + /// . It will use TreeTraversalOrder.PRE_ORDER for tree traversal. /// /// the tag tree pointer. public TagTreeIterator(IStructureNode tagTreePointer) - : this(tagTreePointer, new TagTreeIteratorElementApprover(), TagTreeIterator.TreeTraversalOrder.PRE_ORDER) { + : this(tagTreePointer, TagTreeIterator.TreeTraversalOrder.PRE_ORDER) { } /// /// Creates a new instance of /// . /// - /// the tag tree pointer. - /// - /// a filter that will be called to let iterator know whether some particular element - /// should be traversed or not. - /// + /// the tag tree pointer /// an order in which the tree will be traversed. - public TagTreeIterator(IStructureNode tagTreePointer, TagTreeIteratorElementApprover approver, TagTreeIterator.TreeTraversalOrder - traversalOrder) { + public TagTreeIterator(IStructureNode tagTreePointer, TagTreeIterator.TreeTraversalOrder traversalOrder) { if (tagTreePointer == null) { throw new ArgumentException(MessageFormatUtil.Format(KernelExceptionMessageConstant.ARG_SHOULD_NOT_BE_NULL , "tagTreepointer")); } - if (approver == null) { - throw new ArgumentException(MessageFormatUtil.Format(KernelExceptionMessageConstant.ARG_SHOULD_NOT_BE_NULL - , "approver")); - } if (traversalOrder == null) { throw new ArgumentException(MessageFormatUtil.Format(KernelExceptionMessageConstant.ARG_SHOULD_NOT_BE_NULL , "traversalOrder")); @@ -86,7 +72,6 @@ public TagTreeIterator(IStructureNode tagTreePointer, TagTreeIteratorElementAppr this.pointer = tagTreePointer; this.traversalOrder = traversalOrder; handlerList = new HashSet(); - this.approver = approver; } /// Adds a handler that will be called for the elements during the traversal. @@ -116,12 +101,14 @@ public virtual void Traverse() { } private void Traverse(IStructureNode elem) { - if (!approver.Approve(elem)) { - return; + foreach (ITagTreeIteratorHandler handler in handlerList) { + if (!handler.Accept(elem)) { + return; + } } if (traversalOrder == TagTreeIterator.TreeTraversalOrder.PRE_ORDER) { foreach (ITagTreeIteratorHandler handler in handlerList) { - handler.NextElement(elem); + handler.ProcessElement(elem); } } IList kids = elem.GetKids(); @@ -132,7 +119,7 @@ private void Traverse(IStructureNode elem) { } if (traversalOrder == TagTreeIterator.TreeTraversalOrder.POST_ORDER) { foreach (ITagTreeIteratorHandler handler in handlerList) { - handler.NextElement(elem); + handler.ProcessElement(elem); } } } diff --git a/itext/itext.kernel/itext/kernel/pdf/tagutils/TagTreeIteratorFlusher.cs b/itext/itext.kernel/itext/kernel/pdf/tagutils/TagTreeIteratorFlusher.cs index faac173d70..0ea6ed10cb 100644 --- a/itext/itext.kernel/itext/kernel/pdf/tagutils/TagTreeIteratorFlusher.cs +++ b/itext/itext.kernel/itext/kernel/pdf/tagutils/TagTreeIteratorFlusher.cs @@ -20,6 +20,8 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ +using System.Collections.Generic; +using iText.Kernel.Pdf; using iText.Kernel.Pdf.Tagging; namespace iText.Kernel.Pdf.Tagutils { @@ -27,17 +29,44 @@ namespace iText.Kernel.Pdf.Tagutils { /// Class that flushes struct elements while iterating over struct tree root with /// . /// - public class TagTreeIteratorFlusher : ITagTreeIteratorHandler { + public class TagTreeIteratorFlusher : AbstractAvoidDuplicatesTagTreeIteratorHandler { + private ICollection waitingTags; + + private bool waitingTagsUsed = false; + /// /// Creates a new instance of - /// + /// . /// public TagTreeIteratorFlusher() { } // Empty constructor - /// - public virtual void NextElement(IStructureNode elem) { + /// + /// Sets waiting tags for + /// . + /// + /// waiting tags to set + /// + /// this same + /// + /// instance + /// + public virtual ITagTreeIteratorHandler SetWaitingTags(ICollection waitingTags) { + this.waitingTags = waitingTags; + this.waitingTagsUsed = true; + return this; + } + + public override bool Accept(IStructureNode node) { + if (waitingTagsUsed) { + return base.Accept(node) && node is PdfStructElem && (waitingTags == null || !waitingTags.Contains(((PdfStructElem + )node).GetPdfObject())); + } + return base.Accept(node); + } + + public override void ProcessElement(IStructureNode elem) { if (elem is PdfStructElem && !((PdfStructElem)elem).IsFlushed()) { ((PdfStructElem)elem).Flush(); } diff --git a/itext/itext.kernel/itext/kernel/pdf/tagutils/TagTreePointer.cs b/itext/itext.kernel/itext/kernel/pdf/tagutils/TagTreePointer.cs index b22458e775..f326a1d721 100644 --- a/itext/itext.kernel/itext/kernel/pdf/tagutils/TagTreePointer.cs +++ b/itext/itext.kernel/itext/kernel/pdf/tagutils/TagTreePointer.cs @@ -762,10 +762,8 @@ public virtual iText.Kernel.Pdf.Tagutils.TagTreePointer MoveToKid(int n, String throw new PdfException(KernelExceptionMessageConstant.CANNOT_MOVE_TO_MARKED_CONTENT_REFERENCE); } TagTreePointer.RoleFinderHandler handler = new TagTreePointer.RoleFinderHandler(n, role); - TagTreePointer.TagTreeIteratorApproverWithStop approver = new TagTreePointer.TagTreeIteratorApproverWithStop - (handler); - TagTreeIterator iterator = new TagTreeIterator(GetCurrentStructElem(), approver, TagTreeIterator.TreeTraversalOrder - .PRE_ORDER); + TagTreeIterator iterator = new TagTreeIterator(GetCurrentStructElem(), TagTreeIterator.TreeTraversalOrder. + PRE_ORDER); iterator.AddHandler(handler); iterator.Traverse(); PdfStructElem elem = handler.GetFoundElement(); @@ -1129,7 +1127,7 @@ private void ThrowExceptionIfCurrentPageIsNotInited() { } } - private class RoleFinderHandler : ITagTreeIteratorHandler { + private class RoleFinderHandler : AbstractAvoidDuplicatesTagTreeIteratorHandler { private readonly int n; private readonly String role; @@ -1145,7 +1143,15 @@ internal RoleFinderHandler(int n, String role) { } //\endcond - public virtual void NextElement(IStructureNode elem) { + public virtual PdfStructElem GetFoundElement() { + return foundElem; + } + + public override bool Accept(IStructureNode node) { + return GetFoundElement() == null && base.Accept(node); + } + + public override void ProcessElement(IStructureNode elem) { if (foundElem != null) { return; } @@ -1154,25 +1160,6 @@ public virtual void NextElement(IStructureNode elem) { foundElem = (PdfStructElem)elem; } } - - public virtual PdfStructElem GetFoundElement() { - return foundElem; - } - } - - [System.ObsoleteAttribute(@"change ITagTreeIteratorHandler#nextElement to return boolean showing whether the iteration should be continued. It will allow to get rid of this ugly workaround." - )] - private class TagTreeIteratorApproverWithStop : TagTreeIteratorAvoidDuplicatesApprover { - private readonly TagTreePointer.RoleFinderHandler handler; - - public TagTreeIteratorApproverWithStop(TagTreePointer.RoleFinderHandler handler) - : base() { - this.handler = handler; - } - - public override bool Approve(IStructureNode elem) { - return base.Approve(elem) && handler.GetFoundElement() == null; - } } } } diff --git a/itext/itext.kernel/itext/kernel/pdf/tagutils/WaitingTagsManager.cs b/itext/itext.kernel/itext/kernel/pdf/tagutils/WaitingTagsManager.cs index 18afe508f4..b931a83b3e 100644 --- a/itext/itext.kernel/itext/kernel/pdf/tagutils/WaitingTagsManager.cs +++ b/itext/itext.kernel/itext/kernel/pdf/tagutils/WaitingTagsManager.cs @@ -38,9 +38,9 @@ namespace iText.Kernel.Pdf.Tagutils { /// Waiting state could also be perceived as a temporal association of the object to some particular tag. /// public class WaitingTagsManager { - private IDictionary associatedObjToWaitingTag; + private readonly IDictionary associatedObjToWaitingTag; - private IDictionary waitingTagToAssociatedObj; + private readonly IDictionary waitingTagToAssociatedObj; //\cond DO_NOT_DOCUMENT internal WaitingTagsManager() { @@ -222,9 +222,8 @@ private void FlushStructElementAndItKids(PdfStructElem elem) { if (waitingTagToAssociatedObj.ContainsKey(elem.GetPdfObject())) { return; } - TagTreeIterator iterator = new TagTreeIterator(elem, new WaitingTagsManager.WaitingTagsApprover(waitingTagToAssociatedObj - .Keys), TagTreeIterator.TreeTraversalOrder.POST_ORDER); - iterator.AddHandler(new TagTreeIteratorFlusher()); + TagTreeIterator iterator = new TagTreeIterator(elem, TagTreeIterator.TreeTraversalOrder.POST_ORDER); + iterator.AddHandler(new TagTreeIteratorFlusher().SetWaitingTags(waitingTagToAssociatedObj.Keys)); iterator.Traverse(); } @@ -237,19 +236,5 @@ private void RemoveWaitingStateAndFlushIfParentFlushed(PdfStructElem structElem) } } } - - private class WaitingTagsApprover : TagTreeIteratorAvoidDuplicatesApprover { - private readonly ICollection waitingTags; - - public WaitingTagsApprover(ICollection waitingTags) - : base() { - this.waitingTags = waitingTags; - } - - public override bool Approve(IStructureNode elem) { - return base.Approve(elem) && elem is PdfStructElem && (waitingTags == null || !waitingTags.Contains(((PdfStructElem - )elem).GetPdfObject())); - } - } } } diff --git a/itext/itext.kernel/itext/kernel/utils/CompareTool.cs b/itext/itext.kernel/itext/kernel/utils/CompareTool.cs index a4bea38ae2..f1b3ca52e7 100644 --- a/itext/itext.kernel/itext/kernel/utils/CompareTool.cs +++ b/itext/itext.kernel/itext/kernel/utils/CompareTool.cs @@ -108,6 +108,8 @@ public class CompareTool { private bool encryptionCompareEnabled = false; + private bool kdfSaltCompareEnabled = true; + private bool useCachedPagesForComparison = true; private IMetaInfo metaInfo; @@ -359,7 +361,31 @@ public virtual void SetEventCountingMetaInfo(IMetaInfo metaInfo) { /// /// this CompareTool instance. public virtual iText.Kernel.Utils.CompareTool EnableEncryptionCompare() { + return EnableEncryptionCompare(true); + } + + /// Enables the comparison of the encryption properties of the documents. + /// + /// Enables the comparison of the encryption properties of the documents. Encryption properties comparison + /// results are returned along with all other comparison results. + /// + /// IMPORTANT NOTE: this flag affects only the comparison performed by compareByContent methods! + /// + /// doesn't compare encryption properties + /// because encryption properties aren't part of the document's Catalog. + /// + /// + /// set to + /// + /// if + /// + /// entry must be compared, + /// {code false} otherwise + /// + /// this CompareTool instance. + public virtual iText.Kernel.Utils.CompareTool EnableEncryptionCompare(bool kdfSaltCompareEnabled) { this.encryptionCompareEnabled = true; + this.kdfSaltCompareEnabled = kdfSaltCompareEnabled; return this; } @@ -918,8 +944,8 @@ public virtual String CompareXmp(String outPdf, String cmpPdf, bool ignoreDateAn using (PdfReader readerOut = iText.Kernel.Utils.CompareTool.CreateOutputReader(this.outPdf)) { using (PdfDocument outDocument = new PdfDocument(readerOut, new DocumentProperties().SetEventCountingMetaInfo (metaInfo))) { - byte[] cmpBytes = cmpDocument.GetXmpMetadata(); - byte[] outBytes = outDocument.GetXmpMetadata(); + byte[] cmpBytes = cmpDocument.GetXmpMetadataBytes(); + byte[] outBytes = outDocument.GetXmpMetadataBytes(); if (ignoreDateAndProducerProperties) { XMPMeta xmpMeta = XMPMetaFactory.ParseFromBuffer(cmpBytes, new ParseOptions().SetOmitNormalization(true)); XMPUtils.RemoveProperties(xmpMeta, XMPConst.NS_XMP, PdfConst.CreateDate, true, true); @@ -1415,6 +1441,7 @@ private String CompareByContent(String outPath, String differenceImagePrefix, ID (), catalogPath, compareResult, ignoredCatalogEntries); if (encryptionCompareEnabled) { CompareDocumentsEncryption(outDocument, cmpDocument, compareResult); + CompareDocumentsMac(outDocument, cmpDocument, compareResult); } if (generateCompareByContentXmlReport) { String outPdfName = new FileInfo(outPdf).Name; @@ -1525,6 +1552,26 @@ private void CompareDocumentsEncryption(PdfDocument outDocument, PdfDocument cmp } } + private void CompareDocumentsMac(PdfDocument outDocument, PdfDocument cmpDocument, CompareTool.CompareResult + compareResult) { + PdfDictionary outAuthCode = outDocument.GetTrailer().GetAsDictionary(PdfName.AuthCode); + PdfDictionary cmpAuthCode = cmpDocument.GetTrailer().GetAsDictionary(PdfName.AuthCode); + if (outAuthCode == null && cmpAuthCode == null) { + return; + } + ObjectPath trailerPath = new TrailerPath(cmpDocument, outDocument); + if (outAuthCode == null) { + compareResult.AddError(trailerPath, "Output document does not contain MAC."); + return; + } + if (cmpAuthCode == null) { + compareResult.AddError(trailerPath, "Output document contains MAC which is not expected."); + return; + } + CompareDictionariesExtended(outAuthCode, cmpAuthCode, trailerPath, compareResult, new HashSet(JavaUtil.ArraysAsList + (PdfName.ByteRange, PdfName.MAC))); + } + private bool CompareStreams(Stream is1, Stream is2) { byte[] buffer1 = new byte[64 * 1024]; byte[] buffer2 = new byte[64 * 1024]; @@ -1569,7 +1616,8 @@ private bool CompareDictionariesExtended(PdfDictionary outDict, PdfDictionary cm if (excludedKeys != null && excludedKeys.Contains(key)) { continue; } - if (key.Equals(PdfName.Parent) || key.Equals(PdfName.P) || key.Equals(PdfName.ModDate)) { + if (key.Equals(PdfName.Parent) || key.Equals(PdfName.P) || key.Equals(PdfName.ModDate) || (key.Equals(PdfName + .KDFSalt) && !kdfSaltCompareEnabled)) { continue; } if (outDict.IsStream() && cmpDict.IsStream() && (key.Equals(PdfName.Filter) || key.Equals(PdfName.Length)) diff --git a/itext/itext.kernel/itext/kernel/utils/IValidationChecker.cs b/itext/itext.kernel/itext/kernel/utils/IValidationChecker.cs deleted file mode 100644 index 7683798d12..0000000000 --- a/itext/itext.kernel/itext/kernel/utils/IValidationChecker.cs +++ /dev/null @@ -1,76 +0,0 @@ -/* -This file is part of the iText (R) project. -Copyright (c) 1998-2024 Apryse Group NV -Authors: Apryse Software. - -This program is offered under a commercial and under the AGPL license. -For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. - -AGPL licensing: -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . -*/ -using System; -using iText.Kernel.Pdf; - -namespace iText.Kernel.Utils { - /// Used to check if a PDF document is compliant to a specific validation profile. - public interface IValidationChecker { - /// - /// Validate the provided - /// . - /// - /// - /// Validate the provided - /// . - /// - /// This method is called by the - /// - /// to check for additional conformance requirements. - /// - /// - /// the - /// - /// to validate - /// - void ValidateDocument(ValidationContext validationContext); - - /// Check the provided object for conformance. - /// - /// Check the provided object for conformance. - /// - /// This method is called by the - /// - /// to check for additional conformance requirements. - /// - /// the object to check - /// - /// the - /// - /// of the object - /// - /// - /// the - /// - /// of the object - /// - /// - /// the - /// - /// of the object - /// - /// additional information - void ValidateObject(Object obj, IsoKey key, PdfResources resources, PdfStream contentStream, Object extra); - } -} diff --git a/itext/itext.kernel/itext/kernel/utils/PdfMerger.cs b/itext/itext.kernel/itext/kernel/utils/PdfMerger.cs index e3f04beddb..dfdc000a05 100644 --- a/itext/itext.kernel/itext/kernel/utils/PdfMerger.cs +++ b/itext/itext.kernel/itext/kernel/utils/PdfMerger.cs @@ -20,7 +20,6 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ -using System; using System.Collections.Generic; using iText.Kernel.Pdf; @@ -38,28 +37,7 @@ public class PdfMerger { /// /// the document into which source documents will be merged public PdfMerger(PdfDocument pdfDocument) - : this(pdfDocument, true, true) { - } - - /// This class is used to merge a number of existing documents into one. - /// the document into which source documents will be merged - /// - /// if true, then tags from the source document are copied even if destination document is not set as - /// tagged. Note, that if false, tag structure is still could be copied if the destination document - /// is explicitly marked as tagged with - /// - /// - /// - /// if true, then outlines from the source document are copied even if in destination document - /// outlines are not initialized. Note, that if false, outlines are still could be copied if the - /// destination document outlines were explicitly initialized with - /// - /// - [System.ObsoleteAttribute(@"use PdfMerger(PdfDocument, PdfMergerProperties) constructor")] - public PdfMerger(PdfDocument pdfDocument, bool mergeTags, bool mergeOutlines) { - this.pdfDocument = pdfDocument; - this.properties = new PdfMergerProperties(); - this.properties.SetMergeTags(mergeTags).SetMergeOutlines(mergeOutlines); + : this(pdfDocument, new PdfMergerProperties().SetMergeTags(true).SetMergeOutlines(true)) { } /// This class is used to merge a number of existing documents into one. diff --git a/itext/itext.kernel/itext/kernel/utils/RegisterDefaultDiContainer.cs b/itext/itext.kernel/itext/kernel/utils/RegisterDefaultDiContainer.cs new file mode 100644 index 0000000000..d102d45dde --- /dev/null +++ b/itext/itext.kernel/itext/kernel/utils/RegisterDefaultDiContainer.cs @@ -0,0 +1,47 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Commons.Utils; +using iText.Kernel.DI.Pagetree; +using iText.Kernel.Mac; + +namespace iText.Kernel.Utils { + /// Registers a default instance for a dependency injection container for the kernel module. + public class RegisterDefaultDiContainer { + private const int DEFAULT_PAGE_TREE_LIST_FACTORY_MAX_SAFE_ENTRIES = 50_000; + + /// + /// Creates an instance of + /// . + /// + public RegisterDefaultDiContainer() { + } + + static RegisterDefaultDiContainer() { + // Empty constructor but should be public as we need it for automatic class loading + // sharp + DIContainer.RegisterDefault(typeof(IPageTreeListFactory), () => new DefaultPageTreeListFactory(DEFAULT_PAGE_TREE_LIST_FACTORY_MAX_SAFE_ENTRIES + )); + DIContainer.RegisterDefault(typeof(IMacContainerLocator), () => new StandaloneMacContainerLocator()); + } + } +} diff --git a/itext/itext.kernel/itext/kernel/utils/ValidationContext.cs b/itext/itext.kernel/itext/kernel/utils/ValidationContext.cs deleted file mode 100644 index 20ae280cec..0000000000 --- a/itext/itext.kernel/itext/kernel/utils/ValidationContext.cs +++ /dev/null @@ -1,108 +0,0 @@ -/* -This file is part of the iText (R) project. -Copyright (c) 1998-2024 Apryse Group NV -Authors: Apryse Software. - -This program is offered under a commercial and under the AGPL license. -For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. - -AGPL licensing: -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . -*/ -using System.Collections.Generic; -using iText.Kernel.Font; -using iText.Kernel.Pdf; - -namespace iText.Kernel.Utils { - /// - /// This class is used to pass additional information to the - /// - /// implementations. - /// - public class ValidationContext { - private PdfDocument PdfDocument = null; - - private ICollection fonts = null; - - /// - /// Creates new - /// - /// instance. - /// - public ValidationContext() { - } - - /// - /// Sets - /// - /// for this - /// - /// instance. - /// - /// document to validate. - /// - /// this - /// - /// instance. - /// - public virtual iText.Kernel.Utils.ValidationContext WithPdfDocument(PdfDocument pdfDocument) { - this.PdfDocument = pdfDocument; - return this; - } - - /// - /// Sets fonts for this - /// - /// instance. - /// - /// - /// collection of the - /// - /// fonts to validate. - /// - /// - /// this - /// - /// instance. - /// - public virtual iText.Kernel.Utils.ValidationContext WithFonts(ICollection fonts) { - this.fonts = fonts; - return this; - } - - /// - /// Gets - /// - /// related to this - /// . - /// - /// - /// - /// - /// document to validate. - /// - public virtual PdfDocument GetPdfDocument() { - return PdfDocument; - } - - /// - /// Gets fonts related to this - /// . - /// - /// fonts to validate. - public virtual ICollection GetFonts() { - return fonts; - } - } -} diff --git a/itext/itext.pdfua/itext/pdfua/checkers/utils/TagTreeHandlerUtil.cs b/itext/itext.kernel/itext/kernel/validation/IValidationChecker.cs similarity index 51% rename from itext/itext.pdfua/itext/pdfua/checkers/utils/TagTreeHandlerUtil.cs rename to itext/itext.kernel/itext/kernel/validation/IValidationChecker.cs index 372ac36de7..19c60b737e 100644 --- a/itext/itext.pdfua/itext/pdfua/checkers/utils/TagTreeHandlerUtil.cs +++ b/itext/itext.kernel/itext/kernel/validation/IValidationChecker.cs @@ -20,34 +20,35 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ -using System; using iText.Kernel.Pdf; -using iText.Kernel.Pdf.Tagging; -namespace iText.Pdfua.Checkers.Utils { - /// Utility class that contains utility methods used when working with the TagTreeHandler - [Obsolete] - public sealed class TagTreeHandlerUtil { - private TagTreeHandlerUtil() { - } +namespace iText.Kernel.Validation { + /// Used to check if a PDF document is compliant to a specific validation profile. + public interface IValidationChecker { + /// + /// Validate the provided + /// . + /// + /// + /// the + /// + /// to validate + /// + void Validate(IValidationContext validationContext); - //Empty constructor. /// - /// Gets the - /// - /// if the element matches the provided role and the structureNode is indeed an - /// + /// Is + /// + /// ready to flush. /// - /// The role that needs to be matched. - /// The structure node. + /// the pdf object to check /// - /// The - /// - /// if the structure matches the role. + /// + /// + /// if the object is ready to flush, + /// + /// otherwise /// - [Obsolete] - public static PdfStructElem GetElementIfRoleMatches(PdfName role, IStructureNode structureNode) { - return null; - } + bool IsPdfObjectReadyToFlush(PdfObject @object); } } diff --git a/itext/itext.kernel/itext/kernel/validation/IValidationContext.cs b/itext/itext.kernel/itext/kernel/validation/IValidationContext.cs new file mode 100644 index 0000000000..83cdd4b22a --- /dev/null +++ b/itext/itext.kernel/itext/kernel/validation/IValidationContext.cs @@ -0,0 +1,30 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +namespace iText.Kernel.Validation { + /// Interface for classes that store some information which is required for validation. + public interface IValidationContext { + /// Gets type of the context. + /// the type + ValidationType GetType(); + } +} diff --git a/itext/itext.kernel/itext/kernel/utils/ValidationContainer.cs b/itext/itext.kernel/itext/kernel/validation/ValidationContainer.cs similarity index 71% rename from itext/itext.kernel/itext/kernel/utils/ValidationContainer.cs rename to itext/itext.kernel/itext/kernel/validation/ValidationContainer.cs index a5715d334e..7eb9c2ac1b 100644 --- a/itext/itext.kernel/itext/kernel/utils/ValidationContainer.cs +++ b/itext/itext.kernel/itext/kernel/validation/ValidationContainer.cs @@ -20,11 +20,10 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ -using System; using System.Collections.Generic; using iText.Kernel.Pdf; -namespace iText.Kernel.Utils { +namespace iText.Kernel.Validation { /// /// This class is a container for one or more /// @@ -62,62 +61,19 @@ public ValidationContainer() { /// /// Validate the provided - /// + /// /// with all the /// /// implementations. /// - /// - /// Validate the provided - /// - /// with all the - /// - /// implementations. - /// - /// /// /// the - /// + /// /// to validate /// - public virtual void Validate(ValidationContext context) { - foreach (IValidationChecker checker in validationCheckers) { - checker.ValidateDocument(context); - } - } - - /// - /// Check the provided object for conformance with all the - /// - /// implementations. - /// - /// - /// Check the provided object for conformance with all the - /// - /// implementations. - /// - /// - /// the object to check - /// - /// the - /// - /// of the object - /// - /// - /// the - /// - /// of the object - /// - /// - /// the - /// - /// of the object - /// - /// additional information - public virtual void Validate(Object obj, IsoKey key, PdfResources resources, PdfStream contentStream, Object - extra) { + public virtual void Validate(IValidationContext context) { foreach (IValidationChecker checker in validationCheckers) { - checker.ValidateObject(obj, key, resources, contentStream, extra); + checker.Validate(context); } } @@ -157,5 +113,29 @@ public virtual void AddChecker(IValidationChecker checker) { public virtual bool ContainsChecker(IValidationChecker checker) { return validationCheckers.Contains(checker); } + + /// + /// Is + /// + /// ready to flush according to all added + /// + /// implementations. + /// + /// the pdf object to check + /// + /// + /// + /// if the object is ready to flush, + /// + /// otherwise + /// + public virtual bool IsPdfObjectChecked(PdfObject pdfObject) { + foreach (IValidationChecker checker in validationCheckers) { + if (!checker.IsPdfObjectReadyToFlush(pdfObject)) { + return false; + } + } + return true; + } } } diff --git a/itext/itext.kernel/itext/kernel/pdf/IsoKey.cs b/itext/itext.kernel/itext/kernel/validation/ValidationType.cs similarity index 89% rename from itext/itext.kernel/itext/kernel/pdf/IsoKey.cs rename to itext/itext.kernel/itext/kernel/validation/ValidationType.cs index 31714f77bc..ee93580704 100644 --- a/itext/itext.kernel/itext/kernel/pdf/IsoKey.cs +++ b/itext/itext.kernel/itext/kernel/validation/ValidationType.cs @@ -20,14 +20,15 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ -namespace iText.Kernel.Pdf { - /// Type of object to conform. - public enum IsoKey { +namespace iText.Kernel.Validation { + /// Type of object to validate. + public enum ValidationType { + PDF_DOCUMENT, CANVAS_STACK, FILL_COLOR, EXTENDED_GRAPHICS_STATE, INLINE_IMAGE, - PAGE, + PDF_PAGE, PDF_OBJECT, RENDERING_INTENT, STROKE_COLOR, diff --git a/itext/itext.kernel/itext/kernel/validation/context/AbstractColorValidationContext.cs b/itext/itext.kernel/itext/kernel/validation/context/AbstractColorValidationContext.cs new file mode 100644 index 0000000000..26374ccd09 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/validation/context/AbstractColorValidationContext.cs @@ -0,0 +1,69 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Canvas; +using iText.Kernel.Validation; + +namespace iText.Kernel.Validation.Context { + /// Abstract class for color validation context. + public abstract class AbstractColorValidationContext : IValidationContext, IContentStreamValidationParameter + , IGraphicStateValidationParameter { + private readonly CanvasGraphicsState graphicsState; + + private readonly PdfDictionary currentColorSpaces; + + private readonly PdfStream contentStream; + + /// + /// Instantiates a new + /// + /// based on graphic state, resources and content stream. + /// + /// the graphical state + /// the resources + /// the content stream + protected internal AbstractColorValidationContext(CanvasGraphicsState graphicsState, PdfResources resources + , PdfStream contentStream) { + this.graphicsState = graphicsState; + currentColorSpaces = resources == null ? null : resources.GetPdfObject().GetAsDictionary(PdfName.ColorSpace + ); + this.contentStream = contentStream; + } + + /// Gets the current color space. + /// the color space dictionary + public virtual PdfDictionary GetCurrentColorSpaces() { + return currentColorSpaces; + } + + public virtual CanvasGraphicsState GetGraphicsState() { + return graphicsState; + } + + public virtual PdfStream GetContentStream() { + return contentStream; + } + + public abstract ValidationType GetType(); + } +} diff --git a/itext/itext.kernel/itext/kernel/validation/context/CanvasBmcValidationContext.cs b/itext/itext.kernel/itext/kernel/validation/context/CanvasBmcValidationContext.cs new file mode 100644 index 0000000000..f158f0e6ed --- /dev/null +++ b/itext/itext.kernel/itext/kernel/validation/context/CanvasBmcValidationContext.cs @@ -0,0 +1,64 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System.Collections.Generic; +using iText.Commons.Datastructures; +using iText.Kernel.Pdf; +using iText.Kernel.Validation; + +namespace iText.Kernel.Validation.Context { + /// Class for canvas begin marked content validation. + public class CanvasBmcValidationContext : IValidationContext { + private readonly Stack> tagStructureStack; + + private readonly Tuple2 currentBmc; + + /// + /// Instantiates a new + /// + /// based on tag structure stack and current BMC. + /// + /// the tag structure stack + /// the current BMC + public CanvasBmcValidationContext(Stack> tagStructureStack, Tuple2 currentBmc) { + this.tagStructureStack = tagStructureStack; + this.currentBmc = currentBmc; + } + + /// Gets tag structure stack. + /// tag structure stack + public virtual Stack> GetTagStructureStack() { + return tagStructureStack; + } + + /// Gets current BMC. + /// the current BMC + public virtual Tuple2 GetCurrentBmc() { + return currentBmc; + } + + public virtual ValidationType GetType() { + return ValidationType.CANVAS_BEGIN_MARKED_CONTENT; + } + } +} diff --git a/itext/itext.kernel/itext/kernel/validation/context/CanvasStackValidationContext.cs b/itext/itext.kernel/itext/kernel/validation/context/CanvasStackValidationContext.cs new file mode 100644 index 0000000000..c317827594 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/validation/context/CanvasStackValidationContext.cs @@ -0,0 +1,50 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Validation; + +namespace iText.Kernel.Validation.Context { + /// Class for canvas stack validation. + public class CanvasStackValidationContext : IValidationContext { + private readonly char @operator; + + /// + /// Instantiates a new + /// + /// based on operator. + /// + /// the operator + public CanvasStackValidationContext(char @operator) { + this.@operator = @operator; + } + + /// Gets the operator. + /// the operator + public virtual char GetOperator() { + return @operator; + } + + public virtual ValidationType GetType() { + return ValidationType.CANVAS_STACK; + } + } +} diff --git a/itext/itext.kernel/itext/kernel/validation/context/CanvasWritingContentValidationContext.cs b/itext/itext.kernel/itext/kernel/validation/context/CanvasWritingContentValidationContext.cs new file mode 100644 index 0000000000..967ac87415 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/validation/context/CanvasWritingContentValidationContext.cs @@ -0,0 +1,53 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System.Collections.Generic; +using iText.Commons.Datastructures; +using iText.Kernel.Pdf; +using iText.Kernel.Validation; + +namespace iText.Kernel.Validation.Context { + /// Class for canvas writing content validation. + public class CanvasWritingContentValidationContext : IValidationContext { + private readonly Stack> tagStructureStack; + + /// + /// Instantiates a new + /// + /// based on tag structure stack. + /// + /// the tag structure stack + public CanvasWritingContentValidationContext(Stack> tagStructureStack) { + this.tagStructureStack = tagStructureStack; + } + + /// Gets the tag structure stack. + /// the tag structure stack + public virtual Stack> GetTagStructureStack() { + return tagStructureStack; + } + + public virtual ValidationType GetType() { + return ValidationType.CANVAS_WRITING_CONTENT; + } + } +} diff --git a/itext/itext.kernel/itext/kernel/validation/context/CryptoValidationContext.cs b/itext/itext.kernel/itext/kernel/validation/context/CryptoValidationContext.cs new file mode 100644 index 0000000000..94af540b25 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/validation/context/CryptoValidationContext.cs @@ -0,0 +1,51 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Pdf; +using iText.Kernel.Validation; + +namespace iText.Kernel.Validation.Context { + /// Class for crypto validation. + public class CryptoValidationContext : IValidationContext { + private readonly PdfObject crypto; + + /// + /// Instantiates a new + /// + /// based on crypto object. + /// + /// the crypto object + public CryptoValidationContext(PdfObject crypto) { + this.crypto = crypto; + } + + /// Gets the crypto object. + /// the crypto object + public virtual PdfObject GetCrypto() { + return crypto; + } + + public virtual ValidationType GetType() { + return ValidationType.CRYPTO; + } + } +} diff --git a/itext/itext.kernel/itext/kernel/validation/context/DuplicateIdEntryValidationContext.cs b/itext/itext.kernel/itext/kernel/validation/context/DuplicateIdEntryValidationContext.cs new file mode 100644 index 0000000000..1b3f489e85 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/validation/context/DuplicateIdEntryValidationContext.cs @@ -0,0 +1,51 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Pdf; +using iText.Kernel.Validation; + +namespace iText.Kernel.Validation.Context { + /// Class for duplicate ID entry in structure element tree validation. + public class DuplicateIdEntryValidationContext : IValidationContext { + private readonly PdfString id; + + /// + /// Instantiates a new + /// + /// based on ID string. + /// + /// the ID of the entry + public DuplicateIdEntryValidationContext(PdfString id) { + this.id = id; + } + + /// Gets the ID of the entry. + /// the ID + public virtual PdfString GetId() { + return id; + } + + public virtual ValidationType GetType() { + return ValidationType.DUPLICATE_ID_ENTRY; + } + } +} diff --git a/itext/itext.kernel/itext/kernel/validation/context/ExtendedGStateValidationContext.cs b/itext/itext.kernel/itext/kernel/validation/context/ExtendedGStateValidationContext.cs new file mode 100644 index 0000000000..f480467455 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/validation/context/ExtendedGStateValidationContext.cs @@ -0,0 +1,58 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Canvas; +using iText.Kernel.Validation; + +namespace iText.Kernel.Validation.Context { + /// Class for extended graphics state validation. + public class ExtendedGStateValidationContext : IValidationContext, IGraphicStateValidationParameter, IContentStreamValidationParameter { + private readonly CanvasGraphicsState graphicsState; + + private readonly PdfStream contentStream; + + /// + /// Instantiates a new + /// + /// based on graphics state and content stream. + /// + /// the graphics state + /// the content stream + public ExtendedGStateValidationContext(CanvasGraphicsState graphicsState, PdfStream contentStream) { + this.graphicsState = graphicsState; + this.contentStream = contentStream; + } + + public virtual PdfStream GetContentStream() { + return contentStream; + } + + public virtual CanvasGraphicsState GetGraphicsState() { + return graphicsState; + } + + public virtual ValidationType GetType() { + return ValidationType.EXTENDED_GRAPHICS_STATE; + } + } +} diff --git a/itext/itext.kernel/itext/kernel/validation/context/FillColorValidationContext.cs b/itext/itext.kernel/itext/kernel/validation/context/FillColorValidationContext.cs new file mode 100644 index 0000000000..4d208568c7 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/validation/context/FillColorValidationContext.cs @@ -0,0 +1,47 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Canvas; +using iText.Kernel.Validation; + +namespace iText.Kernel.Validation.Context { + /// Class for fill canvas color canvas tag validation. + public class FillColorValidationContext : AbstractColorValidationContext { + /// + /// Instantiates a new + /// + /// based on graphics state, resources and content stream. + /// + /// the canvas graphics state + /// the resources + /// the content stream + public FillColorValidationContext(CanvasGraphicsState canvasGraphicsState, PdfResources resources, PdfStream + stream) + : base(canvasGraphicsState, resources, stream) { + } + + public override ValidationType GetType() { + return ValidationType.FILL_COLOR; + } + } +} diff --git a/itext/itext.kernel/itext/kernel/validation/context/FontGlyphsGStateValidationContext.cs b/itext/itext.kernel/itext/kernel/validation/context/FontGlyphsGStateValidationContext.cs new file mode 100644 index 0000000000..0d3e46cc83 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/validation/context/FontGlyphsGStateValidationContext.cs @@ -0,0 +1,58 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Canvas; +using iText.Kernel.Validation; + +namespace iText.Kernel.Validation.Context { + /// Class for canvas font glyphs validation context. + public class FontGlyphsGStateValidationContext : IValidationContext, IGraphicStateValidationParameter, IContentStreamValidationParameter { + private readonly CanvasGraphicsState graphicsState; + + private readonly PdfStream contentStream; + + /// + /// Instantiates a new + /// + /// based on canvas graphics state and content stream. + /// + /// the canvas graphics state + /// the content stream + public FontGlyphsGStateValidationContext(CanvasGraphicsState graphicsState, PdfStream contentStream) { + this.graphicsState = graphicsState; + this.contentStream = contentStream; + } + + public virtual PdfStream GetContentStream() { + return contentStream; + } + + public virtual CanvasGraphicsState GetGraphicsState() { + return graphicsState; + } + + public virtual ValidationType GetType() { + return ValidationType.FONT_GLYPHS; + } + } +} diff --git a/itext/itext.kernel/itext/kernel/validation/context/FontValidationContext.cs b/itext/itext.kernel/itext/kernel/validation/context/FontValidationContext.cs new file mode 100644 index 0000000000..c2cdf5eae7 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/validation/context/FontValidationContext.cs @@ -0,0 +1,62 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using iText.Kernel.Font; +using iText.Kernel.Validation; + +namespace iText.Kernel.Validation.Context { + /// Class for font validation context. + public class FontValidationContext : IValidationContext { + private readonly String text; + + private readonly PdfFont font; + + /// + /// Instantiates a new + /// + /// based on text and font. + /// + /// the text + /// the font + public FontValidationContext(String text, PdfFont font) { + this.text = text; + this.font = font; + } + + /// Gets the text. + /// the text + public virtual String GetText() { + return text; + } + + /// Gets the font. + /// the font + public virtual PdfFont GetFont() { + return font; + } + + public virtual ValidationType GetType() { + return ValidationType.FONT; + } + } +} diff --git a/itext/itext.kernel/itext/kernel/validation/context/IContentStreamValidationParameter.cs b/itext/itext.kernel/itext/kernel/validation/context/IContentStreamValidationParameter.cs new file mode 100644 index 0000000000..d466afc438 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/validation/context/IContentStreamValidationParameter.cs @@ -0,0 +1,32 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Pdf; + +namespace iText.Kernel.Validation.Context { + /// Interface for validation context classes which store content stream. + public interface IContentStreamValidationParameter { + /// Gets the content stream. + /// the content stream + PdfStream GetContentStream(); + } +} diff --git a/itext/itext.kernel/itext/kernel/validation/context/IGraphicStateValidationParameter.cs b/itext/itext.kernel/itext/kernel/validation/context/IGraphicStateValidationParameter.cs new file mode 100644 index 0000000000..b076aed958 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/validation/context/IGraphicStateValidationParameter.cs @@ -0,0 +1,32 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Pdf.Canvas; + +namespace iText.Kernel.Validation.Context { + /// Interface for validation context classes which store graphics state. + public interface IGraphicStateValidationParameter { + /// Gets the graphics state. + /// the graphics state + CanvasGraphicsState GetGraphicsState(); + } +} diff --git a/itext/itext.kernel/itext/kernel/validation/context/InlineImageValidationContext.cs b/itext/itext.kernel/itext/kernel/validation/context/InlineImageValidationContext.cs new file mode 100644 index 0000000000..c7f8a582fa --- /dev/null +++ b/itext/itext.kernel/itext/kernel/validation/context/InlineImageValidationContext.cs @@ -0,0 +1,62 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Pdf; +using iText.Kernel.Validation; + +namespace iText.Kernel.Validation.Context { + /// Class for inline image validation context. + public class InlineImageValidationContext : IValidationContext { + private readonly PdfStream image; + + private readonly PdfDictionary currentColorSpaces; + + /// + /// Instantiates a new + /// + /// based on image and resources. + /// + /// the image + /// the resources which are used to extract color space of the image + public InlineImageValidationContext(PdfStream image, PdfResources resources) { + this.image = image; + currentColorSpaces = resources == null ? null : resources.GetPdfObject().GetAsDictionary(PdfName.ColorSpace + ); + } + + /// Gets the image. + /// the image + public virtual PdfStream GetImage() { + return image; + } + + /// Gets the current color space. + /// the color space + public virtual PdfDictionary GetCurrentColorSpaces() { + return currentColorSpaces; + } + + public virtual ValidationType GetType() { + return ValidationType.INLINE_IMAGE; + } + } +} diff --git a/itext/itext.kernel/itext/kernel/validation/context/PdfDocumentValidationContext.cs b/itext/itext.kernel/itext/kernel/validation/context/PdfDocumentValidationContext.cs new file mode 100644 index 0000000000..9e28a4e76d --- /dev/null +++ b/itext/itext.kernel/itext/kernel/validation/context/PdfDocumentValidationContext.cs @@ -0,0 +1,67 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System.Collections.Generic; +using iText.Kernel.Font; +using iText.Kernel.Pdf; +using iText.Kernel.Validation; + +namespace iText.Kernel.Validation.Context { + /// + /// Class for + /// + /// validation context. + /// + public class PdfDocumentValidationContext : IValidationContext { + private readonly PdfDocument pdfDocument; + + private readonly ICollection documentFonts; + + /// + /// Instantiates a new + /// + /// based on document and document fonts. + /// + /// the pdf document + /// the document fonts + public PdfDocumentValidationContext(PdfDocument pdfDocument, ICollection documentFonts) { + this.pdfDocument = pdfDocument; + this.documentFonts = documentFonts; + } + + /// Gets the pdf document. + /// the pdf document + public virtual PdfDocument GetPdfDocument() { + return pdfDocument; + } + + /// Gets the document fonts. + /// the document fonts + public virtual ICollection GetDocumentFonts() { + return documentFonts; + } + + public virtual ValidationType GetType() { + return ValidationType.PDF_DOCUMENT; + } + } +} diff --git a/itext/itext.kernel/itext/kernel/validation/context/PdfObjectValidationContext.cs b/itext/itext.kernel/itext/kernel/validation/context/PdfObjectValidationContext.cs new file mode 100644 index 0000000000..ad0042c007 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/validation/context/PdfObjectValidationContext.cs @@ -0,0 +1,55 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Pdf; +using iText.Kernel.Validation; + +namespace iText.Kernel.Validation.Context { + /// + /// Class for + /// + /// validation context. + /// + public class PdfObjectValidationContext : IValidationContext { + private readonly PdfObject @object; + + /// + /// Instantiates a new + /// + /// based on pdf object. + /// + /// the pdf object + public PdfObjectValidationContext(PdfObject @object) { + this.@object = @object; + } + + /// Gets the pdf object. + /// the pdf object + public virtual PdfObject GetObject() { + return @object; + } + + public virtual ValidationType GetType() { + return ValidationType.PDF_OBJECT; + } + } +} diff --git a/itext/itext.kernel/itext/kernel/validation/context/PdfPageValidationContext.cs b/itext/itext.kernel/itext/kernel/validation/context/PdfPageValidationContext.cs new file mode 100644 index 0000000000..31e07df571 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/validation/context/PdfPageValidationContext.cs @@ -0,0 +1,55 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Pdf; +using iText.Kernel.Validation; + +namespace iText.Kernel.Validation.Context { + /// + /// Class for + /// + /// validation context. + /// + public class PdfPageValidationContext : IValidationContext { + private readonly PdfPage page; + + /// + /// Instantiates a new + /// + /// based on pdf page. + /// + /// the pdf page + public PdfPageValidationContext(PdfPage page) { + this.page = page; + } + + /// Gets the pdf page. + /// the pdf page + public virtual PdfPage GetPage() { + return page; + } + + public virtual ValidationType GetType() { + return ValidationType.PDF_PAGE; + } + } +} diff --git a/itext/itext.kernel/itext/kernel/validation/context/RenderingIntentValidationContext.cs b/itext/itext.kernel/itext/kernel/validation/context/RenderingIntentValidationContext.cs new file mode 100644 index 0000000000..079e55456f --- /dev/null +++ b/itext/itext.kernel/itext/kernel/validation/context/RenderingIntentValidationContext.cs @@ -0,0 +1,51 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Pdf; +using iText.Kernel.Validation; + +namespace iText.Kernel.Validation.Context { + /// Class for rendering intent validation context. + public class RenderingIntentValidationContext : IValidationContext { + private readonly PdfName intent; + + /// + /// Instantiates a new + /// + /// based on pdf name. + /// + /// the intent pdf name + public RenderingIntentValidationContext(PdfName intent) { + this.intent = intent; + } + + /// Gets the intent pdf name. + /// the intent pdf name + public virtual PdfName GetIntent() { + return intent; + } + + public virtual ValidationType GetType() { + return ValidationType.RENDERING_INTENT; + } + } +} diff --git a/itext/itext.kernel/itext/kernel/validation/context/SignTypeValidationContext.cs b/itext/itext.kernel/itext/kernel/validation/context/SignTypeValidationContext.cs new file mode 100644 index 0000000000..ecdf21cf1a --- /dev/null +++ b/itext/itext.kernel/itext/kernel/validation/context/SignTypeValidationContext.cs @@ -0,0 +1,50 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Validation; + +namespace iText.Kernel.Validation.Context { + /// Class for sign type validation context. + public class SignTypeValidationContext : IValidationContext { + private readonly bool isCAdES; + + /// + /// Instantiates a new + /// + /// based on whether sign is CAdeS or not. + /// + /// whether sign is CAdeS or not + public SignTypeValidationContext(bool isCAdES) { + this.isCAdES = isCAdES; + } + + /// Whether sign is CAdeS or not. + /// whether sign is CAdeS or not + public virtual bool IsCAdES() { + return isCAdES; + } + + public virtual ValidationType GetType() { + return ValidationType.SIGNATURE_TYPE; + } + } +} diff --git a/itext/itext.kernel/itext/kernel/validation/context/SignatureValidationContext.cs b/itext/itext.kernel/itext/kernel/validation/context/SignatureValidationContext.cs new file mode 100644 index 0000000000..0df7d87c78 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/validation/context/SignatureValidationContext.cs @@ -0,0 +1,51 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Pdf; +using iText.Kernel.Validation; + +namespace iText.Kernel.Validation.Context { + /// Class for signature validation context. + public class SignatureValidationContext : IValidationContext { + private readonly PdfDictionary sign; + + /// + /// Instantiates a new + /// + /// based on sign pdf dictionary. + /// + /// the sign pdf dictionary + public SignatureValidationContext(PdfDictionary sign) { + this.sign = sign; + } + + /// Gets the sign pdf dictionary. + /// the sign pdf dictionary + public virtual PdfDictionary GetSignature() { + return sign; + } + + public virtual ValidationType GetType() { + return ValidationType.SIGNATURE; + } + } +} diff --git a/itext/itext.kernel/itext/kernel/validation/context/StrokeColorValidationContext.cs b/itext/itext.kernel/itext/kernel/validation/context/StrokeColorValidationContext.cs new file mode 100644 index 0000000000..efa26c9473 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/validation/context/StrokeColorValidationContext.cs @@ -0,0 +1,47 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Canvas; +using iText.Kernel.Validation; + +namespace iText.Kernel.Validation.Context { + /// Class for stroke canvas color validation context. + public class StrokeColorValidationContext : AbstractColorValidationContext { + /// + /// Instantiates a new + /// + /// based on graphics state, resources and content stream. + /// + /// the canvas graphics state + /// the resources + /// the content stream + public StrokeColorValidationContext(CanvasGraphicsState canvasGraphicsState, PdfResources resources, PdfStream + stream) + : base(canvasGraphicsState, resources, stream) { + } + + public override ValidationType GetType() { + return ValidationType.STROKE_COLOR; + } + } +} diff --git a/itext/itext.kernel/itext/kernel/validation/context/TagStructElementValidationContext.cs b/itext/itext.kernel/itext/kernel/validation/context/TagStructElementValidationContext.cs new file mode 100644 index 0000000000..2a6acf400c --- /dev/null +++ b/itext/itext.kernel/itext/kernel/validation/context/TagStructElementValidationContext.cs @@ -0,0 +1,51 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Pdf; +using iText.Kernel.Validation; + +namespace iText.Kernel.Validation.Context { + /// Class for tag structure element validation context. + public class TagStructElementValidationContext : IValidationContext { + private readonly PdfObject @object; + + /// + /// Instantiates a new + /// + /// based on pdf object. + /// + /// the tag pdf object + public TagStructElementValidationContext(PdfObject @object) { + this.@object = @object; + } + + /// Gets the tag pdf object. + /// the tag pdf object + public virtual PdfObject GetObject() { + return @object; + } + + public virtual ValidationType GetType() { + return ValidationType.TAG_STRUCTURE_ELEMENT; + } + } +} diff --git a/itext/itext.kernel/itext/kernel/validation/context/XrefTableValidationContext.cs b/itext/itext.kernel/itext/kernel/validation/context/XrefTableValidationContext.cs new file mode 100644 index 0000000000..7e33d6e1e2 --- /dev/null +++ b/itext/itext.kernel/itext/kernel/validation/context/XrefTableValidationContext.cs @@ -0,0 +1,55 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Pdf; +using iText.Kernel.Validation; + +namespace iText.Kernel.Validation.Context { + /// + /// Class for + /// + /// validation context. + /// + public class XrefTableValidationContext : IValidationContext { + private readonly PdfXrefTable xrefTable; + + /// + /// Instantiates a new + /// + /// based on pdf xref table. + /// + /// the pdf xref table + public XrefTableValidationContext(PdfXrefTable xrefTable) { + this.xrefTable = xrefTable; + } + + /// Gets the pdf xref table. + /// the pdf xref table + public virtual PdfXrefTable GetXrefTable() { + return xrefTable; + } + + public virtual ValidationType GetType() { + return ValidationType.XREF_TABLE; + } + } +} diff --git a/itext/itext.layout/Properties/AssemblyInfo.cs b/itext/itext.layout/Properties/AssemblyInfo.cs index de432b12a1..e1a292fa6c 100644 --- a/itext/itext.layout/Properties/AssemblyInfo.cs +++ b/itext/itext.layout/Properties/AssemblyInfo.cs @@ -22,8 +22,8 @@ [assembly: Guid("fd0a08a8-0f82-4d6f-a3db-7b8f3f9302b4")] -[assembly: TypographyVersion("4.0.2.0")] +[assembly: TypographyVersion("5.0.0.0")] -[assembly: AssemblyVersion("8.0.5.0")] -[assembly: AssemblyFileVersion("8.0.5.0")] -[assembly: AssemblyInformationalVersion("8.0.5")] +[assembly: AssemblyVersion("9.0.0.0")] +[assembly: AssemblyFileVersion("9.0.0.0")] +[assembly: AssemblyInformationalVersion("9.0.0")] diff --git a/itext/itext.layout/itext/layout/Document.cs b/itext/itext.layout/itext/layout/Document.cs index d92f12b437..08f2a675cf 100644 --- a/itext/itext.layout/itext/layout/Document.cs +++ b/itext/itext.layout/itext/layout/Document.cs @@ -293,7 +293,7 @@ public virtual Rectangle GetPageEffectiveArea(PageSize pageSize) { public override T1 GetDefaultProperty(int property) { switch (property) { case Property.FONT: { - if (GetPdfDocument().GetConformanceLevel() != null) { + if (GetPdfDocument().GetConformance().IsPdfAOrUa()) { return (T1)(Object)GetPdfDocument().GetDefaultFont(); } return base.GetDefaultProperty(property); diff --git a/itext/itext.layout/itext/layout/ElementPropertyContainer.cs b/itext/itext.layout/itext/layout/ElementPropertyContainer.cs index e37db6556d..0b03cb764f 100644 --- a/itext/itext.layout/itext/layout/ElementPropertyContainer.cs +++ b/itext/itext.layout/itext/layout/ElementPropertyContainer.cs @@ -473,7 +473,10 @@ public virtual T SetBackgroundImage(IList imagesList) { /// /// this Element. public virtual T SetBorder(Border border) { - SetProperty(Property.BORDER, border); + SetProperty(Property.BORDER_TOP, border); + SetProperty(Property.BORDER_RIGHT, border); + SetProperty(Property.BORDER_BOTTOM, border); + SetProperty(Property.BORDER_LEFT, border); return (T)(Object)this; } @@ -528,7 +531,10 @@ public virtual T SetBorderLeft(Border border) { /// /// this Element. public virtual T SetBorderRadius(BorderRadius borderRadius) { - SetProperty(Property.BORDER_RADIUS, borderRadius); + SetProperty(Property.BORDER_BOTTOM_LEFT_RADIUS, borderRadius); + SetProperty(Property.BORDER_BOTTOM_RIGHT_RADIUS, borderRadius); + SetProperty(Property.BORDER_TOP_LEFT_RADIUS, borderRadius); + SetProperty(Property.BORDER_TOP_RIGHT_RADIUS, borderRadius); return (T)(Object)this; } @@ -669,24 +675,24 @@ public virtual T SetStrokeWidth(float strokeWidth) { return (T)(Object)this; } - /// Switch on the simulation of bold style for a font. + /// Simulates bold style for a font. /// - /// Switch on the simulation of bold style for a font. + /// Simulates bold style for a font. /// Be aware that using correct bold font is highly preferred over this option. /// /// this element - public virtual T SetBold() { + public virtual T SimulateBold() { SetProperty(Property.BOLD_SIMULATION, true); return (T)(Object)this; } - /// Switch on the simulation of italic style for a font. + /// Simulates italic style for a font. /// - /// Switch on the simulation of italic style for a font. + /// Simulates italic style for a font. /// Be aware that using correct italic (oblique) font is highly preferred over this option. /// /// this element - public virtual T SetItalic() { + public virtual T SimulateItalic() { SetProperty(Property.ITALIC_SIMULATION, true); return (T)(Object)this; } diff --git a/itext/itext.layout/itext/layout/RootElement.cs b/itext/itext.layout/itext/layout/RootElement.cs index 8791f3e607..45d5e4363a 100644 --- a/itext/itext.layout/itext/layout/RootElement.cs +++ b/itext/itext.layout/itext/layout/RootElement.cs @@ -33,6 +33,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Layout.Renderer; using iText.Layout.Splitting; using iText.Layout.Tagging; +using iText.Layout.Validation.Context; namespace iText.Layout { /// A generic abstract root element for a PDF layout object hierarchy. @@ -367,7 +368,7 @@ private static void TraverseAndCallIso(PdfDocument pdfDocument, IRenderer render if (renderer == null) { return; } - pdfDocument.CheckIsoConformance(renderer, IsoKey.LAYOUT); + pdfDocument.CheckIsoConformance(new LayoutValidationContext(renderer)); IList renderers = renderer.GetChildRenderers(); if (renderers == null) { return; diff --git a/itext/itext.layout/itext/layout/borders/Border.cs b/itext/itext.layout/itext/layout/borders/Border.cs index 2fe31bf0bc..b174e1e1ac 100644 --- a/itext/itext.layout/itext/layout/borders/Border.cs +++ b/itext/itext.layout/itext/layout/borders/Border.cs @@ -569,15 +569,16 @@ protected internal virtual void DrawDiscontinuousBorders(PdfCanvas canvas, Recta (x0, y0), new Point(x0 + 10, y0)); clipPoint2 = GetIntersectionPoint(new Point(x2 + borderWidthAfter, y2 + width), new Point(x2, y2), new Point (x3, y3), new Point(x3 - 10, y3)); - if (clipPoint1.x > clipPoint2.x) { + if (clipPoint1.GetX() > clipPoint2.GetX()) { clipPoint = GetIntersectionPoint(new Point(x1 - borderWidthBefore, y1 + width), clipPoint1, clipPoint2, new Point(x2 + borderWidthAfter, y2 + width)); - canvas.MoveTo(x1 - borderWidthBefore, y1 + width).LineTo(clipPoint.x, clipPoint.y).LineTo(x2 + borderWidthAfter + canvas.MoveTo(x1 - borderWidthBefore, y1 + width).LineTo(clipPoint.GetX(), clipPoint.GetY()).LineTo(x2 + borderWidthAfter , y2 + width).LineTo(x1 - borderWidthBefore, y1 + width); } else { - canvas.MoveTo(x1 - borderWidthBefore, y1 + width).LineTo(clipPoint1.x, clipPoint1.y).LineTo(clipPoint2.x, - clipPoint2.y).LineTo(x2 + borderWidthAfter, y2 + width).LineTo(x1 - borderWidthBefore, y1 + width); + canvas.MoveTo(x1 - borderWidthBefore, y1 + width).LineTo(clipPoint1.GetX(), clipPoint1.GetY()).LineTo(clipPoint2 + .GetX(), clipPoint2.GetY()).LineTo(x2 + borderWidthAfter, y2 + width).LineTo(x1 - borderWidthBefore, y1 + + width); } canvas.Clip().EndPath(); x1 += innerRadiusBefore; @@ -603,16 +604,16 @@ protected internal virtual void DrawDiscontinuousBorders(PdfCanvas canvas, Recta (x0, y0), new Point(x0, y0 - 10)); clipPoint2 = GetIntersectionPoint(new Point(x2 + width, y2 - borderWidthAfter), new Point(x2, y2), new Point (x3, y3), new Point(x3, y3 - 10)); - if (clipPoint1.y < clipPoint2.y) { + if (clipPoint1.GetY() < clipPoint2.GetY()) { clipPoint = GetIntersectionPoint(new Point(x1 + width, y1 + borderWidthBefore), clipPoint1, clipPoint2, new Point(x2 + width, y2 - borderWidthAfter)); - canvas.MoveTo(x1 + width, y1 + borderWidthBefore).LineTo(clipPoint.x, clipPoint.y).LineTo(x2 + width, y2 - - borderWidthAfter).LineTo(x1 + width, y1 + borderWidthBefore).Clip().EndPath(); + canvas.MoveTo(x1 + width, y1 + borderWidthBefore).LineTo(clipPoint.GetX(), clipPoint.GetY()).LineTo(x2 + width + , y2 - borderWidthAfter).LineTo(x1 + width, y1 + borderWidthBefore).Clip().EndPath(); } else { - canvas.MoveTo(x1 + width, y1 + borderWidthBefore).LineTo(clipPoint1.x, clipPoint1.y).LineTo(clipPoint2.x, - clipPoint2.y).LineTo(x2 + width, y2 - borderWidthAfter).LineTo(x1 + width, y1 + borderWidthBefore).Clip - ().EndPath(); + canvas.MoveTo(x1 + width, y1 + borderWidthBefore).LineTo(clipPoint1.GetX(), clipPoint1.GetY()).LineTo(clipPoint2 + .GetX(), clipPoint2.GetY()).LineTo(x2 + width, y2 - borderWidthAfter).LineTo(x1 + width, y1 + borderWidthBefore + ).Clip().EndPath(); } canvas.Clip().EndPath(); x1 += widthHalf; @@ -638,15 +639,16 @@ protected internal virtual void DrawDiscontinuousBorders(PdfCanvas canvas, Recta (x0, y0), new Point(x0 - 10, y0)); clipPoint2 = GetIntersectionPoint(new Point(x2 - borderWidthAfter, y2 - width), new Point(x2, y2), new Point (x3, y3), new Point(x3 + 10, y3)); - if (clipPoint1.x < clipPoint2.x) { + if (clipPoint1.GetX() < clipPoint2.GetX()) { clipPoint = GetIntersectionPoint(new Point(x1 + borderWidthBefore, y1 - width), clipPoint1, clipPoint2, new Point(x2 - borderWidthAfter, y2 - width)); - canvas.MoveTo(x1 + borderWidthBefore, y1 - width).LineTo(clipPoint.x, clipPoint.y).LineTo(x2 - borderWidthAfter + canvas.MoveTo(x1 + borderWidthBefore, y1 - width).LineTo(clipPoint.GetX(), clipPoint.GetY()).LineTo(x2 - borderWidthAfter , y2 - width).LineTo(x1 + borderWidthBefore, y1 - width); } else { - canvas.MoveTo(x1 + borderWidthBefore, y1 - width).LineTo(clipPoint1.x, clipPoint1.y).LineTo(clipPoint2.x, - clipPoint2.y).LineTo(x2 - borderWidthAfter, y2 - width).LineTo(x1 + borderWidthBefore, y1 - width); + canvas.MoveTo(x1 + borderWidthBefore, y1 - width).LineTo(clipPoint1.GetX(), clipPoint1.GetY()).LineTo(clipPoint2 + .GetX(), clipPoint2.GetY()).LineTo(x2 - borderWidthAfter, y2 - width).LineTo(x1 + borderWidthBefore, y1 + - width); } canvas.Clip().EndPath(); x1 -= innerRadiusBefore; @@ -672,15 +674,16 @@ protected internal virtual void DrawDiscontinuousBorders(PdfCanvas canvas, Recta (x0, y0), new Point(x0, y0 + 10)); clipPoint2 = GetIntersectionPoint(new Point(x2 - width, y2 + borderWidthAfter), new Point(x2, y2), new Point (x3, y3), new Point(x3, y3 + 10)); - if (clipPoint1.y > clipPoint2.y) { + if (clipPoint1.GetY() > clipPoint2.GetY()) { clipPoint = GetIntersectionPoint(new Point(x1 - width, y1 - borderWidthBefore), clipPoint1, clipPoint2, new Point(x2 - width, y2 + borderWidthAfter)); - canvas.MoveTo(x1 - width, y1 - borderWidthBefore).LineTo(clipPoint.x, clipPoint.y).LineTo(x2 - width, y2 + - borderWidthAfter).LineTo(x1 - width, y1 - borderWidthBefore); + canvas.MoveTo(x1 - width, y1 - borderWidthBefore).LineTo(clipPoint.GetX(), clipPoint.GetY()).LineTo(x2 - width + , y2 + borderWidthAfter).LineTo(x1 - width, y1 - borderWidthBefore); } else { - canvas.MoveTo(x1 - width, y1 - borderWidthBefore).LineTo(clipPoint1.x, clipPoint1.y).LineTo(clipPoint2.x, - clipPoint2.y).LineTo(x2 - width, y2 + borderWidthAfter).LineTo(x1 - width, y1 - borderWidthBefore); + canvas.MoveTo(x1 - width, y1 - borderWidthBefore).LineTo(clipPoint1.GetX(), clipPoint1.GetY()).LineTo(clipPoint2 + .GetX(), clipPoint2.GetY()).LineTo(x2 - width, y2 + borderWidthAfter).LineTo(x1 - width, y1 - borderWidthBefore + ); } canvas.Clip().EndPath(); x1 -= widthHalf; diff --git a/itext/itext.layout/itext/layout/element/Cell.cs b/itext/itext.layout/itext/layout/element/Cell.cs index 656cd78ebd..fe6dfc6e63 100644 --- a/itext/itext.layout/itext/layout/element/Cell.cs +++ b/itext/itext.layout/itext/layout/element/Cell.cs @@ -189,7 +189,10 @@ public virtual iText.Layout.Element.Cell Clone(bool includeContent) { public override T1 GetDefaultProperty(int property) { switch (property) { - case Property.BORDER: { + case Property.BORDER_TOP: + case Property.BORDER_RIGHT: + case Property.BORDER_BOTTOM: + case Property.BORDER_LEFT: { return (T1)(Object)DEFAULT_BORDER; } diff --git a/itext/itext.layout/itext/layout/element/ILargeElement.cs b/itext/itext.layout/itext/layout/element/ILargeElement.cs index 4cfc1af3e8..f14de47dbe 100644 --- a/itext/itext.layout/itext/layout/element/ILargeElement.cs +++ b/itext/itext.layout/itext/layout/element/ILargeElement.cs @@ -51,10 +51,16 @@ public interface ILargeElement : IElement { /// Writes the newly added content to the document. void Flush(); - /// Flushes the content which has just been added to the document. + /// Writes to the output document the content which has just been added to it. /// - /// Flushes the content which has just been added to the document. - /// This is a method for internal usage and is called automatically by the document. + /// Writes to the output document the content which has just been added to it. + /// + /// This method is called automatically for the newly added + /// + /// to be immediately placed + /// in the page contents after it is added to the + /// + /// , so it shouldn't be used in any other places. /// void FlushContent(); diff --git a/itext/itext.layout/itext/layout/element/Table.cs b/itext/itext.layout/itext/layout/element/Table.cs index 46e130abd1..62b290ef6b 100644 --- a/itext/itext.layout/itext/layout/element/Table.cs +++ b/itext/itext.layout/itext/layout/element/Table.cs @@ -870,11 +870,6 @@ public virtual void Flush() { } } - /// Flushes the content which has just been added to the document. - /// - /// Flushes the content which has just been added to the document. - /// This is a method for internal usage and is called automatically by the document. - /// public virtual void FlushContent() { if (lastAddedRowGroups == null || lastAddedRowGroups.IsEmpty()) { return; @@ -909,20 +904,14 @@ public virtual void SetDocument(Document document) { public virtual IList GetLastRowBottomBorder() { IList horizontalBorder = new List(); if (lastAddedRow != null) { - for (int i = 0; i < lastAddedRow.Length; i++) { - Cell cell = lastAddedRow[i]; + foreach (Cell cell in lastAddedRow) { Border border = null; if (cell != null) { if (cell.HasProperty(Property.BORDER_BOTTOM)) { border = cell.GetProperty(Property.BORDER_BOTTOM); } else { - if (cell.HasProperty(Property.BORDER)) { - border = cell.GetProperty(Property.BORDER); - } - else { - border = cell.GetDefaultProperty(Property.BORDER); - } + border = cell.GetDefaultProperty(Property.BORDER_BOTTOM); } } horizontalBorder.Add(border); diff --git a/itext/itext.layout/itext/layout/element/Text.cs b/itext/itext.layout/itext/layout/element/Text.cs index dd2eca9421..5e2322b66d 100644 --- a/itext/itext.layout/itext/layout/element/Text.cs +++ b/itext/itext.layout/itext/layout/element/Text.cs @@ -23,6 +23,7 @@ You should have received a copy of the GNU Affero General Public License using System; using iText.Kernel.Pdf.Tagging; using iText.Kernel.Pdf.Tagutils; +using iText.Layout.Exceptions; using iText.Layout.Properties; using iText.Layout.Renderer; using iText.Layout.Tagging; @@ -53,7 +54,7 @@ public class Text : AbstractElement, ILeafElement, IA /// public Text(String text) { if (null == text) { - throw new ArgumentException(); + throw new ArgumentException(LayoutExceptionMessageConstant.TEXT_CONTENT_CANNOT_BE_NULL); } this.text = text; } diff --git a/itext/itext.layout/itext/layout/exceptions/LayoutExceptionMessageConstant.cs b/itext/itext.layout/itext/layout/exceptions/LayoutExceptionMessageConstant.cs index 18613acbfc..ec9a8de27a 100644 --- a/itext/itext.layout/itext/layout/exceptions/LayoutExceptionMessageConstant.cs +++ b/itext/itext.layout/itext/layout/exceptions/LayoutExceptionMessageConstant.cs @@ -69,6 +69,8 @@ public sealed class LayoutExceptionMessageConstant { public const String FLEXIBLE_ARENT_ALLOWED_AS_MINIMUM_IN_MINMAX = "Flexible values aren't allowed as minimum in minmax grid function."; + public const String TEXT_CONTENT_CANNOT_BE_NULL = "Text content cannot be null."; + private LayoutExceptionMessageConstant() { } } diff --git a/itext/itext.layout/itext/layout/font/ComplexFontSelectorStrategy.cs b/itext/itext.layout/itext/layout/font/ComplexFontSelectorStrategy.cs deleted file mode 100644 index a8e378b920..0000000000 --- a/itext/itext.layout/itext/layout/font/ComplexFontSelectorStrategy.cs +++ /dev/null @@ -1,155 +0,0 @@ -/* -This file is part of the iText (R) project. -Copyright (c) 1998-2024 Apryse Group NV -Authors: Apryse Software. - -This program is offered under a commercial and under the AGPL license. -For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. - -AGPL licensing: -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . -*/ -using System; -using System.Collections.Generic; -using iText.Commons.Utils; -using iText.IO.Font.Otf; -using iText.Kernel.Font; - -namespace iText.Layout.Font { - /// - /// Complex FontSelectorStrategy split text based on - /// . - /// - /// - /// Complex FontSelectorStrategy split text based on - /// . - /// If unicode script changes, a new font will be found. - /// If there is no suitable font, only one notdef glyph from - /// - /// will be added. - /// - [System.ObsoleteAttribute(@"was replaced by iText.Layout.Font.Selectorstrategy.FirstMatchFontSelectorStrategy ." - )] - public class ComplexFontSelectorStrategy : FontSelectorStrategy { - private PdfFont font; - - private FontSelector selector; - - public ComplexFontSelectorStrategy(String text, FontSelector selector, FontProvider provider, FontSet additionalFonts - ) - : base(text, provider, additionalFonts) { - this.font = null; - this.selector = selector; - } - - public ComplexFontSelectorStrategy(String text, FontSelector selector, FontProvider provider) - : base(text, provider, null) { - this.font = null; - this.selector = selector; - } - - public override PdfFont GetCurrentFont() { - return font; - } - - public override IList NextGlyphs() { - font = null; - int nextUnignorable = NextSignificantIndex(); - if (nextUnignorable < text.Length) { - foreach (FontInfo f in selector.GetFonts()) { - int codePoint = IsSurrogatePair(text, nextUnignorable) ? iText.IO.Util.TextUtil.ConvertToUtf32(text, nextUnignorable - ) : (int)text[nextUnignorable]; - if (f.GetFontUnicodeRange().Contains(codePoint)) { - PdfFont currentFont = GetPdfFont(f); - Glyph glyph = currentFont.GetGlyph(codePoint); - if (null != glyph && 0 != glyph.GetCode()) { - font = currentFont; - break; - } - } - } - } - IList glyphs = new List(); - bool anyGlyphsAppended = false; - if (font != null) { - UnicodeScript? unicodeScript = NextSignificantUnicodeScript(nextUnignorable); - int to = nextUnignorable; - for (int i = nextUnignorable; i < text.Length; i++) { - int codePoint = IsSurrogatePair(text, i) ? iText.IO.Util.TextUtil.ConvertToUtf32(text, i) : (int)text[i]; - UnicodeScript? currScript = UnicodeScriptUtil.Of(codePoint); - if (IsSignificantUnicodeScript(currScript) && currScript != unicodeScript) { - break; - } - if (codePoint > 0xFFFF) { - i++; - } - to = i; - } - int numOfAppendedGlyphs = font.AppendGlyphs(text, index, to, glyphs); - anyGlyphsAppended = numOfAppendedGlyphs > 0; - System.Diagnostics.Debug.Assert(anyGlyphsAppended); - index += numOfAppendedGlyphs; - } - if (!anyGlyphsAppended) { - font = GetPdfFont(selector.BestMatch()); - if (index != nextUnignorable) { - index += font.AppendGlyphs(text, index, nextUnignorable - 1, glyphs); - } - while (index <= nextUnignorable && index < text.Length) { - index += font.AppendAnyGlyph(text, index, glyphs); - } - } - return glyphs; - } - - private int NextSignificantIndex() { - int nextValidChar = index; - for (; nextValidChar < text.Length; nextValidChar++) { - if (!iText.IO.Util.TextUtil.IsWhitespaceOrNonPrintable(text[nextValidChar])) { - break; - } - } - return nextValidChar; - } - - private UnicodeScript? NextSignificantUnicodeScript(int from) { - for (int i = from; i < text.Length; i++) { - int codePoint; - if (IsSurrogatePair(text, i)) { - codePoint = iText.IO.Util.TextUtil.ConvertToUtf32(text, i); - i++; - } - else { - codePoint = (int)text[i]; - } - UnicodeScript? unicodeScript = UnicodeScriptUtil.Of(codePoint); - if (IsSignificantUnicodeScript(unicodeScript)) { - return unicodeScript; - } - } - return UnicodeScript.COMMON; - } - - private static bool IsSignificantUnicodeScript(UnicodeScript? unicodeScript) { - // Character.UnicodeScript.UNKNOWN will be handled as significant unicode script - return unicodeScript != UnicodeScript.COMMON && unicodeScript != UnicodeScript.INHERITED; - } - - //This method doesn't perform additional checks if compare with TextUtil#isSurrogatePair() - private static bool IsSurrogatePair(String text, int idx) { - return iText.IO.Util.TextUtil.IsSurrogateHigh(text[idx]) && idx < text.Length - 1 && iText.IO.Util.TextUtil - .IsSurrogateLow(text[idx + 1]); - } - } -} diff --git a/itext/itext.layout/itext/layout/font/FontProvider.cs b/itext/itext.layout/itext/layout/font/FontProvider.cs index bb4c3501a9..2b08dd232d 100644 --- a/itext/itext.layout/itext/layout/font/FontProvider.cs +++ b/itext/itext.layout/itext/layout/font/FontProvider.cs @@ -115,8 +115,8 @@ public FontProvider(FontSet fontSet, String defaultFontFamily) { pdfFonts = new Dictionary(); fontSelectorCache = new FontSelectorCache(this.fontSet); this.defaultFontFamily = defaultFontFamily; - this.fontSelectorStrategyFactory = new FirstMatchFontSelectorStrategy.FirstMathFontSelectorStrategyFactory - (); + this.fontSelectorStrategyFactory = new BestMatchFontSelectorStrategy.BestMatchFontSelectorStrategyFactory( + ); } /// @@ -401,119 +401,6 @@ public virtual bool GetDefaultEmbeddingFlag() { return true; } - /// - /// Gets the - /// - /// to split specified text into sequences of glyphs, already tied - /// to the fonts which contain them. - /// - /// - /// Gets the - /// - /// to split specified text into sequences of glyphs, already tied - /// to the fonts which contain them. The fonts can be taken from the added fonts to the font provider and - /// are chosen based on font-families list and desired font characteristics. - /// - /// for splitting into sequences of glyphs. - /// - /// target font families to create - /// - /// for sequences of glyphs. - /// - /// - /// instance of - /// - /// to create - /// - /// for sequences of glyphs. - /// - /// - /// set which provides fonts additionally to the fonts added to font provider. - /// Combined set of font provider fonts and additional fonts is used when choosing - /// a single font for a sequence of glyphs. Additional fonts will only be used for the given - /// font selector strategy instance and will not be otherwise preserved in font provider. - /// - /// - /// - /// - /// instance. - /// - [System.ObsoleteAttribute(@"use CreateFontSelectorStrategy(System.Collections.Generic.IList{E}, FontCharacteristics, FontSet)" - )] - public virtual FontSelectorStrategy GetStrategy(String text, IList fontFamilies, FontCharacteristics - fc, FontSet additionalFonts) { - return new ComplexFontSelectorStrategy(text, GetFontSelector(fontFamilies, fc, additionalFonts), this, additionalFonts - ); - } - - /// - /// Gets the - /// - /// to split specified text into sequences of glyphs, already tied - /// to the fonts which contain them. - /// - /// - /// Gets the - /// - /// to split specified text into sequences of glyphs, already tied - /// to the fonts which contain them. The fonts can be taken from the added fonts to the font provider and - /// are chosen based on font-families list and desired font characteristics. - /// - /// for splitting into sequences of glyphs. - /// - /// target font families to create - /// - /// for sequences of glyphs. - /// - /// - /// instance of - /// - /// to create - /// - /// for sequences of glyphs. - /// - /// - /// - /// - /// instance. - /// - [System.ObsoleteAttribute(@"use CreateFontSelectorStrategy(System.Collections.Generic.IList{E}, FontCharacteristics, FontSet)" - )] - public virtual FontSelectorStrategy GetStrategy(String text, IList fontFamilies, FontCharacteristics - fc) { - return GetStrategy(text, fontFamilies, fc, null); - } - - /// - /// Gets the - /// - /// to split specified text into sequences of glyphs, already tied - /// to the fonts which contain them. - /// - /// - /// Gets the - /// - /// to split specified text into sequences of glyphs, already tied - /// to the fonts which contain them. The fonts can be taken from the added fonts to the font provider and - /// are chosen based on font-families list and desired font characteristics. - /// - /// for splitting into sequences of glyphs. - /// - /// target font families to create - /// - /// for sequences of glyphs. - /// - /// - /// - /// - /// instance. - /// - [System.ObsoleteAttribute(@"use CreateFontSelectorStrategy(System.Collections.Generic.IList{E}, FontCharacteristics, FontSet)" - )] - public virtual FontSelectorStrategy GetStrategy(String text, IList fontFamilies) { - return GetStrategy(text, fontFamilies, null); - } - /// /// Sets factory which will be used in /// . -*/ -using System; -using System.Collections.Generic; -using iText.IO.Font.Otf; -using iText.Kernel.Font; - -namespace iText.Layout.Font { - /// - /// - /// is responsible for splitting text into sub texts with one particular font. - /// - /// - /// - /// is responsible for splitting text into sub texts with one particular font. - /// - /// will create next sub text and set current font. - /// - [System.ObsoleteAttribute(@"replaced by iText.Layout.Font.Selectorstrategy.IFontSelectorStrategy .")] - public abstract class FontSelectorStrategy { - protected internal String text; - - protected internal int index; - - protected internal readonly FontProvider provider; - - protected internal readonly FontSet additionalFonts; - - protected internal FontSelectorStrategy(String text, FontProvider provider, FontSet additionalFonts) { - this.text = text; - this.index = 0; - this.provider = provider; - this.additionalFonts = additionalFonts; - } - - public virtual bool EndOfText() { - return text == null || index >= text.Length; - } - - public abstract PdfFont GetCurrentFont(); - - public abstract IList NextGlyphs(); - - /// Utility method to create PdfFont. - /// instance of FontInfo. - /// cached or just created PdfFont on success, otherwise null. - /// - protected internal virtual PdfFont GetPdfFont(FontInfo fontInfo) { - return provider.GetPdfFont(fontInfo, additionalFonts); - } - } -} diff --git a/itext/itext.layout/itext/layout/hyphenation/HyphenationTree.cs b/itext/itext.layout/itext/layout/hyphenation/HyphenationTree.cs index 77f2a04c1a..08792387d8 100644 --- a/itext/itext.layout/itext/layout/hyphenation/HyphenationTree.cs +++ b/itext/itext.layout/itext/layout/hyphenation/HyphenationTree.cs @@ -117,7 +117,7 @@ protected internal virtual String UnpackValues(int k) { /// Read hyphenation patterns from an XML file. /// the filename public virtual void LoadPatterns(String filename) { - LoadPatterns(new FileStream(filename, FileMode.Open, FileAccess.Read), filename); + LoadPatterns(FileUtil.GetInputStreamForFile(filename), filename); } /// Read hyphenation patterns from an XML file. diff --git a/itext/itext.layout/itext/layout/margincollapse/MarginsCollapseHandler.cs b/itext/itext.layout/itext/layout/margincollapse/MarginsCollapseHandler.cs index 0a57d7213a..8407bbe4d0 100644 --- a/itext/itext.layout/itext/layout/margincollapse/MarginsCollapseHandler.cs +++ b/itext/itext.layout/itext/layout/margincollapse/MarginsCollapseHandler.cs @@ -25,7 +25,6 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons; using iText.Commons.Utils; using iText.Kernel.Geom; -using iText.Layout; using iText.Layout.Properties; using iText.Layout.Renderer; @@ -499,11 +498,11 @@ private static bool HasBottomPadding(IRenderer renderer) { } private static bool HasTopBorders(IRenderer renderer) { - return iText.Layout.Margincollapse.MarginsCollapseHandler.HasBorders(renderer, Property.BORDER_TOP); + return renderer.GetModelElement().HasProperty(Property.BORDER_TOP); } private static bool HasBottomBorders(IRenderer renderer) { - return iText.Layout.Margincollapse.MarginsCollapseHandler.HasBorders(renderer, Property.BORDER_BOTTOM); + return renderer.GetModelElement().HasProperty(Property.BORDER_BOTTOM); } private static bool RendererIsFloated(IRenderer renderer) { @@ -571,10 +570,5 @@ private static bool HasPadding(IRenderer renderer, int property) { } return padding != null && padding.GetValue() > 0; } - - private static bool HasBorders(IRenderer renderer, int property) { - IPropertyContainer modelElement = renderer.GetModelElement(); - return modelElement.HasProperty(property) || modelElement.HasProperty(Property.BORDER); - } } } diff --git a/itext/itext.layout/itext/layout/minmaxwidth/MinMaxWidthUtils.cs b/itext/itext.layout/itext/layout/minmaxwidth/MinMaxWidthUtils.cs index 485e9ce6a0..2feebd5836 100644 --- a/itext/itext.layout/itext/layout/minmaxwidth/MinMaxWidthUtils.cs +++ b/itext/itext.layout/itext/layout/minmaxwidth/MinMaxWidthUtils.cs @@ -61,15 +61,8 @@ public static MinMaxWidth CountDefaultMinMaxWidth(IRenderer renderer) { } public static float GetBorderWidth(IPropertyContainer element) { - Border border = element.GetProperty(Property.BORDER); Border rightBorder = element.GetProperty(Property.BORDER_RIGHT); Border leftBorder = element.GetProperty(Property.BORDER_LEFT); - if (!element.HasOwnProperty(Property.BORDER_RIGHT)) { - rightBorder = border; - } - if (!element.HasOwnProperty(Property.BORDER_LEFT)) { - leftBorder = border; - } float rightBorderWidth = rightBorder != null ? rightBorder.GetWidth() : 0; float leftBorderWidth = leftBorder != null ? leftBorder.GetWidth() : 0; return rightBorderWidth + leftBorderWidth; diff --git a/itext/itext.layout/itext/layout/properties/ContinuousContainer.cs b/itext/itext.layout/itext/layout/properties/ContinuousContainer.cs index 28d3f2bdd8..314e014f55 100644 --- a/itext/itext.layout/itext/layout/properties/ContinuousContainer.cs +++ b/itext/itext.layout/itext/layout/properties/ContinuousContainer.cs @@ -23,7 +23,6 @@ You should have received a copy of the GNU Affero General Public License using System; using System.Collections.Generic; using iText.Layout; -using iText.Layout.Borders; using iText.Layout.Renderer; namespace iText.Layout.Properties { @@ -38,7 +37,7 @@ namespace iText.Layout.Properties { public sealed class ContinuousContainer { /// Properties needed to be removed/added for continuous container. private static readonly int[] PROPERTIES_NEEDED_FOR_CONTINUOUS_CONTAINER = new int[] { Property.MARGIN_BOTTOM - , Property.BORDER_BOTTOM, Property.PADDING_BOTTOM, Property.BORDER }; + , Property.BORDER_BOTTOM, Property.PADDING_BOTTOM }; private readonly Dictionary properties = new Dictionary(); @@ -95,11 +94,6 @@ public void ReApplyProperties(AbstractRenderer blockRenderer) { foreach (int property in PROPERTIES_NEEDED_FOR_CONTINUOUS_CONTAINER) { blockRenderer.SetProperty(property, properties.Get(property)); } - Border allBorders = (Border)properties.Get(Property.BORDER); - Border bottomBorder = (Border)properties.Get(Property.BORDER_BOTTOM); - if (allBorders != null && bottomBorder == null) { - blockRenderer.SetProperty(Property.BORDER_BOTTOM, allBorders); - } } /// Updates values of the saved property. diff --git a/itext/itext.layout/itext/layout/properties/Property.cs b/itext/itext.layout/itext/layout/properties/Property.cs index 5456ab6cf0..a99352e0c0 100644 --- a/itext/itext.layout/itext/layout/properties/Property.cs +++ b/itext/itext.layout/itext/layout/properties/Property.cs @@ -65,8 +65,6 @@ public sealed class Property { public const int BOLD_SIMULATION = 8; - public const int BORDER = 9; - public const int BORDER_BOTTOM = 10; public const int BORDER_BOTTOM_LEFT_RADIUS = 113; @@ -77,8 +75,6 @@ public sealed class Property { public const int BORDER_LEFT = 11; - public const int BORDER_RADIUS = 101; - public const int BORDER_RIGHT = 12; public const int BORDER_TOP = 13; @@ -191,13 +187,13 @@ public sealed class Property { public const int GRID_COLUMN_START = 148; - public const int GRID_COLUMN_SPAN = 155; + public const int GRID_COLUMN_SPAN = 9; public const int GRID_ROW_END = 149; public const int GRID_ROW_START = 150; - public const int GRID_ROW_SPAN = 156; + public const int GRID_ROW_SPAN = 101; public const int GRID_TEMPLATE_COLUMNS = 145; @@ -406,7 +402,7 @@ public sealed class Property { /// private static readonly bool[] INHERITED_PROPERTIES; - private const int MAX_INHERITED_PROPERTY_ID = 156; + private const int MAX_INHERITED_PROPERTY_ID = 154; static Property() { INHERITED_PROPERTIES = new bool[MAX_INHERITED_PROPERTY_ID + 1]; diff --git a/itext/itext.layout/itext/layout/renderer/AbstractRenderer.cs b/itext/itext.layout/itext/layout/renderer/AbstractRenderer.cs index 06af839a04..a4ca490d57 100644 --- a/itext/itext.layout/itext/layout/renderer/AbstractRenderer.cs +++ b/itext/itext.layout/itext/layout/renderer/AbstractRenderer.cs @@ -964,15 +964,20 @@ public virtual void DrawChildren(DrawContext drawContext) { } /// - /// Performs the drawing operation for the border of this renderer, if - /// defined by any of the - /// - /// values in either the layout - /// element or this + /// Performs the drawing operation for the border of this renderer, if defined by the + /// + /// , + /// + /// , + /// + /// and + /// + /// values in either + /// the layout element or this /// /// itself. /// - /// the context (canvas, document, etc) of this drawing operation. + /// the context (canvas, document, etc.) of this drawing operation public virtual void DrawBorder(DrawContext drawContext) { Border[] borders = GetBorders(); bool gotBorders = false; @@ -1316,8 +1321,8 @@ internal static void ProcessWaitingDrawing(IRenderer child, Transform transformP if (transformProp != null) { outlines.SetProperty(Property.TRANSFORM, transformProp); } - outlines.SetProperty(Property.BORDER, outlineProp); - float offset = outlines.GetProperty(Property.BORDER).GetWidth(); + outlines.SetBorder(outlineProp); + float offset = outlineProp.GetWidth(); if (abstractChild.GetPropertyAsFloat(Property.OUTLINE_OFFSET) != null) { offset += (float)abstractChild.GetPropertyAsFloat(Property.OUTLINE_OFFSET); } @@ -1328,8 +1333,12 @@ internal static void ProcessWaitingDrawing(IRenderer child, Transform transformP divOccupiedArea.SetWidth(divOccupiedArea.GetWidth() + 2 * offset).SetHeight(divOccupiedArea.GetHeight() + 2 * offset); div.occupiedArea = new LayoutArea(abstractChild.GetOccupiedArea().GetPageNumber(), divOccupiedArea); - float outlineWidth = div.GetProperty(Property.BORDER).GetWidth(); - if (divOccupiedArea.GetWidth() >= outlineWidth * 2 && divOccupiedArea.GetHeight() >= outlineWidth * 2) { + float outlineWidthTop = div.GetProperty(Property.BORDER_TOP).GetWidth(); + float outlineWidthBottom = div.GetProperty(Property.BORDER_BOTTOM).GetWidth(); + float outlineWidthLeft = div.GetProperty(Property.BORDER_LEFT).GetWidth(); + float outlineWidthRight = div.GetProperty(Property.BORDER_RIGHT).GetWidth(); + if (divOccupiedArea.GetWidth() >= (outlineWidthLeft + outlineWidthRight) && divOccupiedArea.GetHeight() >= + (outlineWidthTop + outlineWidthBottom)) { waitingDrawing.Add(div); } if (abstractChild.IsRelativePosition()) { @@ -1971,7 +1980,8 @@ protected internal virtual void ApplyAction(PdfDocument document) { PdfLinkAnnotation link = this.GetProperty(Property.LINK_ANNOTATION); if (link == null) { link = (PdfLinkAnnotation)new PdfLinkAnnotation(new Rectangle(0, 0, 0, 0)).SetFlags(PdfAnnotation.PRINT); - Border border = this.GetProperty(Property.BORDER); + // For now, we set left border to an annotation, but appropriate borders for an element will be drawn. + Border border = this.GetProperty(Property.BORDER_LEFT); if (border != null) { link.SetBorder(new PdfArray(new float[] { 0, 0, border.GetWidth() })); } @@ -2622,25 +2632,11 @@ internal virtual PdfFont ResolveFirstPdfFont(String[] font, FontProvider provide //\cond DO_NOT_DOCUMENT internal static Border[] GetBorders(IRenderer renderer) { - Border border = renderer.GetProperty(Property.BORDER); Border topBorder = renderer.GetProperty(Property.BORDER_TOP); Border rightBorder = renderer.GetProperty(Property.BORDER_RIGHT); Border bottomBorder = renderer.GetProperty(Property.BORDER_BOTTOM); Border leftBorder = renderer.GetProperty(Property.BORDER_LEFT); - Border[] borders = new Border[] { topBorder, rightBorder, bottomBorder, leftBorder }; - if (!HasOwnOrModelProperty(renderer, Property.BORDER_TOP)) { - borders[0] = border; - } - if (!HasOwnOrModelProperty(renderer, Property.BORDER_RIGHT)) { - borders[1] = border; - } - if (!HasOwnOrModelProperty(renderer, Property.BORDER_BOTTOM)) { - borders[2] = border; - } - if (!HasOwnOrModelProperty(renderer, Property.BORDER_LEFT)) { - borders[3] = border; - } - return borders; + return new Border[] { topBorder, rightBorder, bottomBorder, leftBorder }; } //\endcond @@ -2996,26 +2992,11 @@ private static UnitValue[] GetMargins(IRenderer renderer) { } private static BorderRadius[] GetBorderRadii(IRenderer renderer) { - BorderRadius radius = renderer.GetProperty(Property.BORDER_RADIUS); BorderRadius topLeftRadius = renderer.GetProperty(Property.BORDER_TOP_LEFT_RADIUS); BorderRadius topRightRadius = renderer.GetProperty(Property.BORDER_TOP_RIGHT_RADIUS); BorderRadius bottomRightRadius = renderer.GetProperty(Property.BORDER_BOTTOM_RIGHT_RADIUS); BorderRadius bottomLeftRadius = renderer.GetProperty(Property.BORDER_BOTTOM_LEFT_RADIUS); - BorderRadius[] borderRadii = new BorderRadius[] { topLeftRadius, topRightRadius, bottomRightRadius, bottomLeftRadius - }; - if (!HasOwnOrModelProperty(renderer, Property.BORDER_TOP_LEFT_RADIUS)) { - borderRadii[0] = radius; - } - if (!HasOwnOrModelProperty(renderer, Property.BORDER_TOP_RIGHT_RADIUS)) { - borderRadii[1] = radius; - } - if (!HasOwnOrModelProperty(renderer, Property.BORDER_BOTTOM_RIGHT_RADIUS)) { - borderRadii[2] = radius; - } - if (!HasOwnOrModelProperty(renderer, Property.BORDER_BOTTOM_LEFT_RADIUS)) { - borderRadii[3] = radius; - } - return borderRadii; + return new BorderRadius[] { topLeftRadius, topRightRadius, bottomRightRadius, bottomLeftRadius }; } private static UnitValue[] GetPaddings(IRenderer renderer) { diff --git a/itext/itext.layout/itext/layout/renderer/AccessibleAttributesApplier.cs b/itext/itext.layout/itext/layout/renderer/AccessibleAttributesApplier.cs index 007769eb63..1e032f9668 100644 --- a/itext/itext.layout/itext/layout/renderer/AccessibleAttributesApplier.cs +++ b/itext/itext.layout/itext/layout/renderer/AccessibleAttributesApplier.cs @@ -328,23 +328,10 @@ private static void ApplyPaddingAttribute(AbstractRenderer renderer, PdfDictiona } private static void ApplyBorderAttributes(AbstractRenderer renderer, PdfDictionary attributes) { - bool specificBorderProperties = renderer.GetProperty(Property.BORDER_TOP) != null || renderer.GetProperty + bool borderPropertiesSet = renderer.GetProperty(Property.BORDER_TOP) != null || renderer.GetProperty (Property.BORDER_RIGHT) != null || renderer.GetProperty(Property.BORDER_BOTTOM) != null || renderer.GetProperty(Property.BORDER_LEFT) != null; - bool generalBorderProperties = !specificBorderProperties && renderer.GetProperty(Property.BORDER) - != null; - if (generalBorderProperties) { - Border generalBorder = renderer.GetProperty(Property.BORDER); - Color generalBorderColor = generalBorder.GetColor(); - int borderType = generalBorder.GetBorderType(); - float borderWidth = generalBorder.GetWidth(); - if (generalBorderColor is DeviceRgb) { - attributes.Put(PdfName.BorderColor, new PdfArray(generalBorderColor.GetColorValue())); - attributes.Put(PdfName.BorderStyle, TransformBorderTypeToName(borderType)); - attributes.Put(PdfName.BorderThickness, new PdfNumber(borderWidth)); - } - } - if (specificBorderProperties) { + if (borderPropertiesSet) { PdfArray borderColors = new PdfArray(); PdfArray borderTypes = new PdfArray(); PdfArray borderWidths = new PdfArray(); diff --git a/itext/itext.layout/itext/layout/renderer/CollapsedTableBorders.cs b/itext/itext.layout/itext/layout/renderer/CollapsedTableBorders.cs index 920e0bf4ba..c0bf8eecb5 100644 --- a/itext/itext.layout/itext/layout/renderer/CollapsedTableBorders.cs +++ b/itext/itext.layout/itext/layout/renderer/CollapsedTableBorders.cs @@ -250,8 +250,7 @@ public virtual iText.Layout.Renderer.CollapsedTableBorders SetBottomBorderCollap } //endregion - protected internal override void BuildBordersArrays(CellRenderer cell, int row, int col, int[] rowspansToDeduct - ) { + protected internal override void BuildBordersArrays(CellRenderer cell, int row, int col) { // We should check if the row number is less than horizontal borders array size. It can happen if the cell with // big rowspan doesn't fit current area and is going to be placed partial. if (row > horizontalBorders.Count) { @@ -276,7 +275,7 @@ protected internal override void BuildBordersArrays(CellRenderer cell, int row, // process only valid cells which hasn't been processed yet if (j >= 0 && nextCellRow != rows.Count && nextCellRow > row) { CellRenderer nextCell = rows[nextCellRow][j]; - BuildBordersArrays(nextCell, nextCellRow, true); + BuildBordersArrays(nextCell, nextCellRow); } } // consider cells under the current one @@ -292,7 +291,7 @@ protected internal override void BuildBordersArrays(CellRenderer cell, int row, CellRenderer nextCell = rows[nextCellRow][col + j]; // otherwise the border was considered previously if (row == nextCellRow - (int)nextCell.GetPropertyAsInteger(Property.ROWSPAN)) { - BuildBordersArrays(nextCell, nextCellRow, true); + BuildBordersArrays(nextCell, nextCellRow); } j += (int)nextCell.GetPropertyAsInteger(Property.COLSPAN); } @@ -304,14 +303,14 @@ protected internal override void BuildBordersArrays(CellRenderer cell, int row, } if (nextCellRow != rows.Count) { CellRenderer nextCell = rows[nextCellRow][col + currCellColspan]; - BuildBordersArrays(nextCell, nextCellRow, true); + BuildBordersArrays(nextCell, nextCellRow); } } // consider current cell - BuildBordersArrays(cell, row, false); + BuildBordersArrays(cell, row); } - protected internal virtual void BuildBordersArrays(CellRenderer cell, int row, bool isNeighbourCell) { + protected internal virtual void BuildBordersArrays(CellRenderer cell, int row) { int colspan = (int)cell.GetPropertyAsInteger(Property.COLSPAN); int rowspan = (int)cell.GetPropertyAsInteger(Property.ROWSPAN); int colN = ((Cell)cell.GetModelElement()).GetCol(); diff --git a/itext/itext.layout/itext/layout/renderer/FlexContainerRenderer.cs b/itext/itext.layout/itext/layout/renderer/FlexContainerRenderer.cs index d6752d9507..4bba68eb68 100644 --- a/itext/itext.layout/itext/layout/renderer/FlexContainerRenderer.cs +++ b/itext/itext.layout/itext/layout/renderer/FlexContainerRenderer.cs @@ -23,6 +23,7 @@ You should have received a copy of the GNU Affero General Public License using System; using System.Collections.Generic; using System.Linq; +using iText.Commons.Datastructures; using iText.Commons.Utils; using iText.Kernel.Geom; using iText.Layout.Borders; @@ -34,17 +35,22 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Layout.Renderer { public class FlexContainerRenderer : DivRenderer { - /* Used for caching purposes in FlexUtil - * We couldn't find the real use case when this map contains more than 1 entry - * but let it still be a map to be on a safe(r) side - * Map mainSize (always width in our case) - hypotheticalCrossSize - */ + /// + /// Used for caching purposes in FlexUtil + /// We couldn't find the real use case when this map contains more than 1 entry + /// but let it still be a map to be on a safe(r) side + /// Map mainSize (always width in our case) - hypotheticalCrossSize + /// private readonly IDictionary hypotheticalCrossSizes = new Dictionary(); private IList> lines; private IFlexItemMainDirector flexItemMainDirector = null; + /// Child renderers and their heights and min heights before the layout. + private readonly IDictionary> heights = new Dictionary>(); + /// Creates a FlexContainerRenderer from its corresponding layout object. /// /// the @@ -90,8 +96,6 @@ public override LayoutResult Layout(LayoutContext layoutContext) { AddAllChildRenderers(renderers); IList renderersToOverflow = RetrieveRenderersToOverflow(layoutContextRectangle); IList previousWidths = new List(); - IList previousHeights = new List(); - IList previousMinHeights = new List(); foreach (IList line in lines) { foreach (FlexItemInfo itemInfo in line) { Rectangle rectangleWithoutBordersMarginsPaddings; @@ -103,9 +107,9 @@ public override LayoutResult Layout(LayoutContext layoutContext) { rectangleWithoutBordersMarginsPaddings = itemInfo.GetRenderer().ApplyMarginsBordersPaddings(itemInfo.GetRectangle ().Clone(), false); } + heights.Put(itemInfo.GetRenderer(), new Tuple2(itemInfo.GetRenderer().GetProperty(Property.HEIGHT), itemInfo.GetRenderer().GetProperty(Property.MIN_HEIGHT))); previousWidths.Add(itemInfo.GetRenderer().GetProperty(Property.WIDTH)); - previousHeights.Add(itemInfo.GetRenderer().GetProperty(Property.HEIGHT)); - previousMinHeights.Add(itemInfo.GetRenderer().GetProperty(Property.MIN_HEIGHT)); itemInfo.GetRenderer().SetProperty(Property.WIDTH, UnitValue.CreatePointValue(rectangleWithoutBordersMarginsPaddings .GetWidth())); itemInfo.GetRenderer().SetProperty(Property.HEIGHT, UnitValue.CreatePointValue(rectangleWithoutBordersMarginsPaddings @@ -131,8 +135,9 @@ public override LayoutResult Layout(LayoutContext layoutContext) { foreach (IList line in lines) { foreach (FlexItemInfo itemInfo in line) { itemInfo.GetRenderer().SetProperty(Property.WIDTH, previousWidths[counter]); - itemInfo.GetRenderer().SetProperty(Property.HEIGHT, previousHeights[counter]); - itemInfo.GetRenderer().SetProperty(Property.MIN_HEIGHT, previousMinHeights[counter]); + Tuple2 curHeights = heights.Get(itemInfo.GetRenderer()); + itemInfo.GetRenderer().SetProperty(Property.HEIGHT, curHeights.GetFirst()); + itemInfo.GetRenderer().SetProperty(Property.MIN_HEIGHT, curHeights.GetSecond()); ++counter; } } @@ -488,6 +493,7 @@ private static void AddSimulateDiv(AbstractRenderer overflowRenderer, float widt private void FillSplitOverflowRenderersForPartialResult(AbstractRenderer splitRenderer, AbstractRenderer overflowRenderer , IList line, IRenderer childRenderer, LayoutResult childResult) { + RestoreHeightForOverflowRenderer(childRenderer, childResult.GetOverflowRenderer()); float occupiedSpace = 0; float maxHeightInLine = 0; bool metChildRendererInLine = false; @@ -502,7 +508,7 @@ private void FillSplitOverflowRenderersForPartialResult(AbstractRenderer splitRe // Get rid of vertical alignment for item with partial result. For column direction, justify-content // is applied to the entire line, not the single item, so there is no point in getting rid of it if (!FlexUtil.IsColumnDirection(this)) { - childResult.GetOverflowRenderer().SetProperty(Property.ALIGN_SELF, AlignmentPropertyValue.START); + SetAlignSelfIfNotStretch(childResult.GetOverflowRenderer()); } overflowRenderer.AddChildRenderer(childResult.GetOverflowRenderer()); } @@ -526,6 +532,7 @@ private void FillSplitOverflowRenderersForPartialResult(AbstractRenderer splitRe ).GetY(), itemInfo.GetRectangle().GetWidth(), maxHeightInLine - itemInfo.GetRectangle().GetY()); LayoutResult neighbourLayoutResult = itemInfo.GetRenderer().Layout(new LayoutContext(new LayoutArea(childResult .GetOccupiedArea().GetPageNumber(), neighbourBbox))); + RestoreHeightForOverflowRenderer(itemInfo.GetRenderer(), neighbourLayoutResult.GetOverflowRenderer()); // Handle result if (neighbourLayoutResult.GetStatus() == LayoutResult.PARTIAL && neighbourLayoutResult.GetSplitRenderer() != null) { @@ -540,7 +547,7 @@ private void FillSplitOverflowRenderersForPartialResult(AbstractRenderer splitRe if (neighbourLayoutResult.GetOverflowRenderer() != null) { if (neighbourLayoutResult.GetStatus() == LayoutResult.PARTIAL) { // Get rid of cross alignment for item with partial result - neighbourLayoutResult.GetOverflowRenderer().SetProperty(Property.ALIGN_SELF, AlignmentPropertyValue.START); + SetAlignSelfIfNotStretch(neighbourLayoutResult.GetOverflowRenderer()); } overflowRenderer.AddChildRenderer(neighbourLayoutResult.GetOverflowRenderer()); } @@ -565,6 +572,31 @@ private void FillSplitOverflowRenderersForPartialResult(AbstractRenderer splitRe } } + private void SetAlignSelfIfNotStretch(IRenderer overflowRenderer) { + AlignmentPropertyValue alignItems = (AlignmentPropertyValue)this.GetProperty(Property + .ALIGN_ITEMS, AlignmentPropertyValue.STRETCH); + AlignmentPropertyValue alignSelf = (AlignmentPropertyValue)overflowRenderer.GetProperty(Property.ALIGN_SELF, alignItems); + if (alignSelf != AlignmentPropertyValue.STRETCH) { + overflowRenderer.SetProperty(Property.ALIGN_SELF, AlignmentPropertyValue.START); + } + } + + private void RestoreHeightForOverflowRenderer(IRenderer childRenderer, IRenderer overflowRenderer) { + if (overflowRenderer == null) { + return; + } + // childRenderer is the original renderer we set the height for before the layout + // And we need to remove the height from the corresponding overflow renderer + Tuple2 curHeights = heights.Get(childRenderer); + if (curHeights.GetFirst() == null) { + overflowRenderer.DeleteOwnProperty(Property.HEIGHT); + } + if (curHeights.GetSecond() == null) { + overflowRenderer.DeleteOwnProperty(Property.MIN_HEIGHT); + } + } + private void FindMinMaxWidthIfCorrespondingPropertiesAreNotSet(MinMaxWidth minMaxWidth, AbstractWidthHandler minMaxWidthHandler) { float initialMinWidth = minMaxWidth.GetChildrenMinWidth(); diff --git a/itext/itext.layout/itext/layout/renderer/GridContainerRenderer.cs b/itext/itext.layout/itext/layout/renderer/GridContainerRenderer.cs index b041c6838f..1b7115e5ec 100644 --- a/itext/itext.layout/itext/layout/renderer/GridContainerRenderer.cs +++ b/itext/itext.layout/itext/layout/renderer/GridContainerRenderer.cs @@ -158,8 +158,9 @@ private GridContainerRenderer.GridLayoutResult LayoutGrid(LayoutContext layoutCo cellToRender.SetProperty(Property.HEIGHT, UnitValue.CreatePointValue(itemHeight)); // Adjust cell BBox to the remaining part of the layout bbox // This way we can lay out elements partially - cellBBox.SetHeight(cellBBox.GetTop() - actualBBox.GetBottom()).SetY(actualBBox.GetY()); - cellToRender.SetProperty(Property.FILL_AVAILABLE_AREA, true); + cellBBox.SetHeight(cellBBox.GetTop() - layoutContext.GetArea().GetBBox().GetBottom()).SetY(layoutContext.GetArea + ().GetBBox().GetY()); + cellToRender.SetProperty(Property.FILL_AVAILABLE_AREA_ON_SPLIT, true); LayoutResult cellResult = cellToRender.Layout(cellContext); notLayoutedRow = Math.Min(notLayoutedRow, ProcessLayoutResult(layoutResult, cell, cellResult)); } @@ -241,15 +242,14 @@ private static LayoutContext GetCellLayoutContext(LayoutContext layoutContext, R private LayoutArea CalculateContainerOccupiedArea(LayoutContext layoutContext, bool isFull) { LayoutArea area = layoutContext.GetArea().Clone(); Rectangle areaBBox = area.GetBBox(); - float totalContainerHeight = GridMulticolUtil.UpdateOccupiedHeight(containerHeight, isFull, isFirstLayout, - this); + float totalContainerHeight = GridMulticolUtil.UpdateOccupiedHeight(containerHeight, isFull, this); if (totalContainerHeight < areaBBox.GetHeight() || isFull) { float? height = RetrieveHeight(); if (height == null) { areaBBox.SetHeight(totalContainerHeight); } else { - height = GridMulticolUtil.UpdateOccupiedHeight((float)height, isFull, isFirstLayout, this); + height = GridMulticolUtil.UpdateOccupiedHeight((float)height, isFull, this); areaBBox.SetHeight((float)height); } } diff --git a/itext/itext.layout/itext/layout/renderer/GridItemRenderer.cs b/itext/itext.layout/itext/layout/renderer/GridItemRenderer.cs index f7cd349256..15ec494643 100644 --- a/itext/itext.layout/itext/layout/renderer/GridItemRenderer.cs +++ b/itext/itext.layout/itext/layout/renderer/GridItemRenderer.cs @@ -101,7 +101,7 @@ public override void SetProperty(int property, Object value) { break; } - case Property.FILL_AVAILABLE_AREA: { + case Property.FILL_AVAILABLE_AREA_ON_SPLIT: { renderer.SetProperty(property, value); break; } @@ -160,7 +160,9 @@ internal virtual float CalculateHeight(float initialHeight) { rectangle.DecreaseHeight(paddingBottom.GetValue()); } Border borderBottom = renderer.GetBorders()[AbstractRenderer.BOTTOM_SIDE]; - rectangle.DecreaseHeight(borderBottom.GetWidth()); + if (borderBottom != null) { + rectangle.DecreaseHeight(borderBottom.GetWidth()); + } } else { renderer.ApplyMarginsBordersPaddings(rectangle, false); diff --git a/itext/itext.layout/itext/layout/renderer/GridMulticolUtil.cs b/itext/itext.layout/itext/layout/renderer/GridMulticolUtil.cs index 4766533db9..bc3df21644 100644 --- a/itext/itext.layout/itext/layout/renderer/GridMulticolUtil.cs +++ b/itext/itext.layout/itext/layout/renderer/GridMulticolUtil.cs @@ -62,41 +62,23 @@ internal static float UpdateOccupiedWidth(float initialWidth, AbstractRenderer r result += SafelyRetrieveFloatProperty(Property.PADDING_RIGHT, renderer); result += SafelyRetrieveFloatProperty(Property.MARGIN_LEFT, renderer); result += SafelyRetrieveFloatProperty(Property.MARGIN_RIGHT, renderer); - if (!renderer.HasOwnProperty(Property.BORDER) || renderer.GetProperty(Property.BORDER) == null) { - result += SafelyRetrieveFloatProperty(Property.BORDER_LEFT, renderer); - } - if (!renderer.HasOwnProperty(Property.BORDER) || renderer.GetProperty(Property.BORDER) == null) { - result += SafelyRetrieveFloatProperty(Property.BORDER_RIGHT, renderer); - } - result += SafelyRetrieveFloatProperty(Property.BORDER, renderer) * 2; + result += SafelyRetrieveFloatProperty(Property.BORDER_LEFT, renderer); + result += SafelyRetrieveFloatProperty(Property.BORDER_RIGHT, renderer); return result; } //\endcond //\cond DO_NOT_DOCUMENT - internal static float UpdateOccupiedHeight(float initialHeight, bool isFull, bool isFirstLayout, AbstractRenderer - renderer) { + internal static float UpdateOccupiedHeight(float initialHeight, bool isFull, AbstractRenderer renderer) { float result = initialHeight; if (isFull) { result += SafelyRetrieveFloatProperty(Property.PADDING_BOTTOM, renderer); result += SafelyRetrieveFloatProperty(Property.MARGIN_BOTTOM, renderer); - if (!renderer.HasOwnProperty(Property.BORDER) || renderer.GetProperty(Property.BORDER) == null) { - result += SafelyRetrieveFloatProperty(Property.BORDER_BOTTOM, renderer); - } + result += SafelyRetrieveFloatProperty(Property.BORDER_BOTTOM, renderer); } result += SafelyRetrieveFloatProperty(Property.PADDING_TOP, renderer); result += SafelyRetrieveFloatProperty(Property.MARGIN_TOP, renderer); - if (!renderer.HasOwnProperty(Property.BORDER) || renderer.GetProperty(Property.BORDER) == null) { - result += SafelyRetrieveFloatProperty(Property.BORDER_TOP, renderer); - } - // isFirstLayout is necessary to handle the case when multicol container layouted in more - // than 2 pages, and on the last page layout result is full, but there is no bottom border - float TOP_AND_BOTTOM = isFull && isFirstLayout ? 2 : 1; - // Multicol container layouted in more than 3 pages, and there is a page where there are no bottom and top borders - if (!isFull && !isFirstLayout) { - TOP_AND_BOTTOM = 0; - } - result += SafelyRetrieveFloatProperty(Property.BORDER, renderer) * TOP_AND_BOTTOM; + result += SafelyRetrieveFloatProperty(Property.BORDER_TOP, renderer); return result; } //\endcond diff --git a/itext/itext.layout/itext/layout/renderer/GridTrackSizer.cs b/itext/itext.layout/itext/layout/renderer/GridTrackSizer.cs index 8d9ddc1b63..9f241da29f 100644 --- a/itext/itext.layout/itext/layout/renderer/GridTrackSizer.cs +++ b/itext/itext.layout/itext/layout/renderer/GridTrackSizer.cs @@ -32,7 +32,6 @@ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT using iText.Commons.Utils; using iText.Kernel.Geom; using iText.Layout.Layout; -using iText.Layout.Properties; using iText.Layout.Properties.Grid; namespace iText.Layout.Renderer { @@ -941,7 +940,6 @@ private float CalculateMinMaxContribution(GridCell cell, bool minTypeContributio // https://drafts.csswg.org/css-sizing-3/#auto-box-sizes: // min-content block size - For block containers, tables, and // inline boxes, this is equivalent to the max-content block size. - cell.GetValue().SetProperty(Property.FILL_AVAILABLE_AREA, false); LayoutContext layoutContext = new LayoutContext(new LayoutArea(1, new Rectangle(cell.GetLayoutArea().GetWidth (), AbstractRenderer.INF))); LayoutResult inifiniteHeighLayoutResult = cell.GetValue().Layout(layoutContext); diff --git a/itext/itext.layout/itext/layout/renderer/LineRenderer.cs b/itext/itext.layout/itext/layout/renderer/LineRenderer.cs index 53ff59b119..7774be49b3 100644 --- a/itext/itext.layout/itext/layout/renderer/LineRenderer.cs +++ b/itext/itext.layout/itext/layout/renderer/LineRenderer.cs @@ -974,7 +974,7 @@ internal static LineRenderer.LineSplitIntoGlyphsData SplitLineIntoGlyphs(LineRen } if (child is TextRenderer) { GlyphLine childLine = ((TextRenderer)child).line; - for (int i = childLine.start; i < childLine.end; i++) { + for (int i = childLine.GetStart(); i < childLine.GetEnd(); i++) { if (iText.IO.Util.TextUtil.IsNewLine(childLine.Get(i))) { newLineFound = true; break; @@ -999,7 +999,7 @@ internal static void Reorder(LineRenderer toProcess, LineRenderer.LineSplitIntoG IList lineGlyphs = splitLineIntoGlyphsResult.GetLineGlyphs(); int initialPos = 0; for (int offset = initialPos; offset < lineGlyphs.Count; offset = initialPos) { - TextRenderer renderer = lineGlyphs[offset].renderer; + TextRenderer renderer = lineGlyphs[offset].GetRenderer(); TextRenderer newRenderer = new TextRenderer(renderer).RemoveReversedRanges(); toProcess.AddChildRenderer(newRenderer); // Insert non-text renderers @@ -1007,11 +1007,11 @@ internal static void Reorder(LineRenderer toProcess, LineRenderer.LineSplitIntoG newRenderer.line = new GlyphLine(newRenderer.line); IList replacementGlyphs = new List(); bool reversed = false; - for (int pos = offset; pos < lineGlyphs.Count && lineGlyphs[pos].renderer == renderer; ++pos) { - replacementGlyphs.Add(lineGlyphs[pos].glyph); - if (pos + 1 < lineGlyphs.Count && lineGlyphs[pos + 1].renderer == renderer && newOrder[pos] == newOrder[pos - + 1] + 1 && !iText.IO.Util.TextUtil.IsSpaceOrWhitespace(lineGlyphs[pos + 1].glyph) && !iText.IO.Util.TextUtil - .IsSpaceOrWhitespace(lineGlyphs[pos].glyph)) { + for (int pos = offset; pos < lineGlyphs.Count && lineGlyphs[pos].GetRenderer() == renderer; ++pos) { + replacementGlyphs.Add(lineGlyphs[pos].GetGlyph()); + if (pos + 1 < lineGlyphs.Count && lineGlyphs[pos + 1].GetRenderer() == renderer && newOrder[pos] == newOrder + [pos + 1] + 1 && !iText.IO.Util.TextUtil.IsSpaceOrWhitespace(lineGlyphs[pos + 1].GetGlyph()) && !iText.IO.Util.TextUtil + .IsSpaceOrWhitespace(lineGlyphs[pos].GetGlyph())) { reversed = true; continue; } @@ -1247,9 +1247,9 @@ internal virtual int TrimFirst() { TextRenderer textRenderer = (TextRenderer)renderer; GlyphLine currentText = textRenderer.GetText(); if (currentText != null) { - int prevTextStart = currentText.start; + int prevTextStart = currentText.GetStart(); textRenderer.TrimFirst(); - int numOfTrimmedGlyphs = textRenderer.GetText().start - prevTextStart; + int numOfTrimmedGlyphs = textRenderer.GetText().GetStart() - prevTextStart; totalNumberOfTrimmedGlyphs += numOfTrimmedGlyphs; } trimFinished = textRenderer.Length() > 0; @@ -1535,7 +1535,7 @@ private void UpdateBidiLevels(int totalNumberOfTrimmedGlyphs, BaseDirection? bas } if (child is TextRenderer) { GlyphLine text = ((TextRenderer)child).GetText(); - for (int i = text.start; i < text.end; i++) { + for (int i = text.GetStart(); i < text.GetEnd(); i++) { Glyph glyph = text.Get(i); if (iText.IO.Util.TextUtil.IsNewLine(glyph)) { newLineFound = true; @@ -1628,14 +1628,38 @@ private bool HasInlineBlocksWithVerticalAlignment() { } public class RendererGlyph { - public Glyph glyph; + private Glyph glyph; - public TextRenderer renderer; + private TextRenderer renderer; public RendererGlyph(Glyph glyph, TextRenderer textRenderer) { this.glyph = glyph; this.renderer = textRenderer; } + + /// Sets the glyph of the object. + /// glyph + public virtual void SetGlyph(Glyph glyph) { + this.glyph = glyph; + } + + /// Retrieves the glyph of the object. + /// glyph + public virtual Glyph GetGlyph() { + return glyph; + } + + /// Sets the renderer of the object. + /// renderer + public virtual void SetRenderer(TextRenderer renderer) { + this.renderer = renderer; + } + + /// Retrieves the renderer of the object. + /// renderer + public virtual TextRenderer GetRenderer() { + return renderer; + } } //\cond DO_NOT_DOCUMENT diff --git a/itext/itext.layout/itext/layout/renderer/MulticolRenderer.cs b/itext/itext.layout/itext/layout/renderer/MulticolRenderer.cs index 25b5fded51..e62abf2b7b 100644 --- a/itext/itext.layout/itext/layout/renderer/MulticolRenderer.cs +++ b/itext/itext.layout/itext/layout/renderer/MulticolRenderer.cs @@ -112,8 +112,8 @@ public override LayoutResult Layout(LayoutContext layoutContext) { } else { this.occupiedArea = CalculateContainerOccupiedArea(layoutContext, false); - return new LayoutResult(LayoutResult.PARTIAL, this.occupiedArea, CreateSplitRenderer(layoutResult.GetSplitRenderers - ()), CreateOverflowRenderer(layoutResult.GetOverflowRenderer())); + return new LayoutResult(LayoutResult.PARTIAL, this.occupiedArea, GridMulticolUtil.CreateSplitRenderer(layoutResult + .GetSplitRenderers(), this), CreateOverflowRenderer(layoutResult.GetOverflowRenderer())); } } } @@ -125,11 +125,16 @@ public override IRenderer GetNextRenderer() { } /// - /// Performs the drawing operation for the border of this renderer, if - /// defined by any of the - /// - /// values in either the layout - /// element or this + /// Performs the drawing operation for the border of this renderer, if defined by the + /// + /// , + /// + /// , + /// + /// and + /// + /// values in either + /// the layout element or this /// /// itself. /// @@ -180,19 +185,6 @@ protected internal virtual MulticolRenderer.MulticolLayoutResult LayoutInColumns return BalanceContentAndLayoutColumns(layoutContext, actualBBox); } - /// Creates a split renderer. - /// children of the split renderer - /// - /// a new - /// - /// instance - /// - [System.ObsoleteAttribute(@"use GridMulticolUtil.CreateSplitRenderer(System.Collections.Generic.IList{E}, AbstractRenderer)" - )] - protected internal virtual AbstractRenderer CreateSplitRenderer(IList children) { - return GridMulticolUtil.CreateSplitRenderer(children, this); - } - /// Creates an overflow renderer. /// an overflowed content renderer /// @@ -345,13 +337,12 @@ private void ClearOverFlowRendererIfNeeded(MulticolRenderer.MulticolLayoutResult private LayoutArea CalculateContainerOccupiedArea(LayoutContext layoutContext, bool isFull) { LayoutArea area = layoutContext.GetArea().Clone(); Rectangle areaBBox = area.GetBBox(); - float totalContainerHeight = GridMulticolUtil.UpdateOccupiedHeight(approximateHeight, isFull, isFirstLayout - , this); + float totalContainerHeight = GridMulticolUtil.UpdateOccupiedHeight(approximateHeight, isFull, this); if (totalContainerHeight < areaBBox.GetHeight() || isFull) { areaBBox.SetHeight(totalContainerHeight); float? height = DetermineHeight(areaBBox); if (height != null) { - height = GridMulticolUtil.UpdateOccupiedHeight((float)height, isFull, isFirstLayout, this); + height = GridMulticolUtil.UpdateOccupiedHeight((float)height, isFull, this); areaBBox.SetHeight((float)height); } } diff --git a/itext/itext.layout/itext/layout/renderer/SeparatedTableBorders.cs b/itext/itext.layout/itext/layout/renderer/SeparatedTableBorders.cs index 04e25f413d..47d39c68c6 100644 --- a/itext/itext.layout/itext/layout/renderer/SeparatedTableBorders.cs +++ b/itext/itext.layout/itext/layout/renderer/SeparatedTableBorders.cs @@ -158,8 +158,7 @@ public override float[] GetCellBorderIndents(int row, int col, int rowspan, int return new float[] { 0, 0, 0, 0 }; } - protected internal override void BuildBordersArrays(CellRenderer cell, int row, int col, int[] rowspansToDeduct - ) { + protected internal override void BuildBordersArrays(CellRenderer cell, int row, int col) { int colspan = (int)cell.GetPropertyAsInteger(Property.COLSPAN); int rowspan = (int)cell.GetPropertyAsInteger(Property.ROWSPAN); int colN = ((Cell)cell.GetModelElement()).GetCol(); diff --git a/itext/itext.layout/itext/layout/renderer/TableBorderUtil.cs b/itext/itext.layout/itext/layout/renderer/TableBorderUtil.cs index 9a1a3e4d80..d7c462573c 100644 --- a/itext/itext.layout/itext/layout/renderer/TableBorderUtil.cs +++ b/itext/itext.layout/itext/layout/renderer/TableBorderUtil.cs @@ -24,7 +24,6 @@ You should have received a copy of the GNU Affero General Public License using System.Collections.Generic; using iText.Layout.Borders; using iText.Layout.Element; -using iText.Layout.Properties; namespace iText.Layout.Renderer { //\cond DO_NOT_DOCUMENT @@ -35,10 +34,7 @@ private TableBorderUtil() { public static Border GetCellSideBorder(Cell cellModel, int borderType) { Border cellModelSideBorder = cellModel.GetProperty(borderType); if (null == cellModelSideBorder && !cellModel.HasProperty(borderType)) { - cellModelSideBorder = cellModel.GetProperty(Property.BORDER); - if (null == cellModelSideBorder && !cellModel.HasProperty(Property.BORDER)) { - cellModelSideBorder = cellModel.GetDefaultProperty(Property.BORDER); - } + cellModelSideBorder = cellModel.GetDefaultProperty(borderType); } return cellModelSideBorder; } diff --git a/itext/itext.layout/itext/layout/renderer/TableBorders.cs b/itext/itext.layout/itext/layout/renderer/TableBorders.cs index 214e6a93e2..780ef73e1f 100644 --- a/itext/itext.layout/itext/layout/renderer/TableBorders.cs +++ b/itext/itext.layout/itext/layout/renderer/TableBorders.cs @@ -157,9 +157,7 @@ protected internal abstract iText.Layout.Renderer.TableBorders ApplyCellIndents( protected internal abstract float GetCellVerticalAddition(float[] indents); // endregion - [System.ObsoleteAttribute(@"Remove rowspansToDeduct parameter which is not used anymore.")] - protected internal abstract void BuildBordersArrays(CellRenderer cell, int row, int col, int[] rowspansToDeduct - ); + protected internal abstract void BuildBordersArrays(CellRenderer cell, int row, int col); protected internal abstract iText.Layout.Renderer.TableBorders UpdateBordersOnNewPage(bool isOriginalNonSplitRenderer , bool isFooterOrHeader, TableRenderer currentRenderer, TableRenderer headerRenderer, TableRenderer footerRenderer @@ -183,7 +181,7 @@ protected internal virtual iText.Layout.Renderer.TableBorders ProcessAllBordersA row -= numOfRowsToRemove; numOfRowsToRemove = 0; } - BuildBordersArrays(currentRow[col], row, col, null); + BuildBordersArrays(currentRow[col], row, col); hasCells = true; int colspan = (int)currentRow[col].GetPropertyAsInteger(Property.COLSPAN); col += colspan - 1; diff --git a/itext/itext.layout/itext/layout/renderer/TableRenderer.cs b/itext/itext.layout/itext/layout/renderer/TableRenderer.cs index 479ccb2458..35de011089 100644 --- a/itext/itext.layout/itext/layout/renderer/TableRenderer.cs +++ b/itext/itext.layout/itext/layout/renderer/TableRenderer.cs @@ -477,16 +477,16 @@ public override LayoutResult Layout(LayoutContext layoutContext) { // if cell is in the last row on the page, its borders shouldn't collapse with the next row borders while (cellProcessingQueue.Count > 0) { TableRenderer.CellRendererInfo currentCellInfo = cellProcessingQueue.JRemoveFirst(); - col = currentCellInfo.column; - CellRenderer cell = currentCellInfo.cellRenderer; + col = currentCellInfo.GetColumn(); + CellRenderer cell = currentCellInfo.GetCellRenderer(); int colspan = (int)cell.GetPropertyAsInteger(Property.COLSPAN); int rowspan = (int)cell.GetPropertyAsInteger(Property.ROWSPAN); if (1 != rowspan) { cellWithBigRowspanAdded = true; } - targetOverflowRowIndex[col] = currentCellInfo.finishRowInd; + targetOverflowRowIndex[col] = currentCellInfo.GetFinishRowInd(); // This cell came from the future (split occurred and we need to place cell with big rowpsan into the current area) - bool currentCellHasBigRowspan = (row != currentCellInfo.finishRowInd); + bool currentCellHasBigRowspan = (row != currentCellInfo.GetFinishRowInd()); if (cell.HasOwnOrModelProperty(Property.HEIGHT)) { rowHasCellWithSetHeight = true; } @@ -499,7 +499,7 @@ public override LayoutResult Layout(LayoutContext layoutContext) { colOffset += countedColumnWidth[l]; } float rowspanOffset = 0; - for (int m = row - 1; m > currentCellInfo.finishRowInd - rowspan && m >= 0; m--) { + for (int m = row - 1; m > currentCellInfo.GetFinishRowInd() - rowspan && m >= 0; m--) { rowspanOffset += (float)heights[m]; } float cellLayoutBoxHeight = rowspanOffset + (!currentCellHasBigRowspan || hasContent ? layoutBox.GetHeight @@ -516,8 +516,8 @@ public override LayoutResult Layout(LayoutContext layoutContext) { cell.SetProperty(Property.WIDTH, UnitValue.CreatePointValue(cellWidth)); } // Apply cell borders - float[] cellIndents = bordersHandler.GetCellBorderIndents(currentCellInfo.finishRowInd, col, rowspan, colspan - ); + float[] cellIndents = bordersHandler.GetCellBorderIndents(currentCellInfo.GetFinishRowInd(), col, rowspan, + colspan); if (!(bordersHandler is SeparatedTableBorders)) { // Bottom indent to be applied consists of two parts which should be summed up: // a) half of the border of the current row (in case it is the last row on the area) @@ -592,9 +592,9 @@ public override LayoutResult Layout(LayoutContext layoutContext) { currentRow[col] = (CellRenderer)cellResult.GetSplitRenderer(); } else { - rows[currentCellInfo.finishRowInd][col] = null; + rows[currentCellInfo.GetFinishRowInd()][col] = null; currentRow[col] = cell; - rowMoves.Put(col, currentCellInfo.finishRowInd); + rowMoves.Put(col, currentCellInfo.GetFinishRowInd()); } } else { @@ -1810,7 +1810,6 @@ private void EnsureFooterOrHeaderHasTheSamePropertiesAsParentTableRenderer(iText )); headerOrFooterRenderer.SetProperty(Property.VERTICAL_BORDER_SPACING, this.GetPropertyAsFloat(Property.VERTICAL_BORDER_SPACING )); - headerOrFooterRenderer.SetProperty(Property.BORDER, Border.NO_BORDER); headerOrFooterRenderer.SetProperty(Property.BORDER_LEFT, Border.NO_BORDER); headerOrFooterRenderer.SetProperty(Property.BORDER_TOP, Border.NO_BORDER); headerOrFooterRenderer.SetProperty(Property.BORDER_RIGHT, Border.NO_BORDER); @@ -1881,11 +1880,11 @@ private float GetTableWidth() { /// This are a structs used for convenience in layout. private class CellRendererInfo { - public CellRenderer cellRenderer; + private readonly CellRenderer cellRenderer; - public int column; + private readonly int column; - public int finishRowInd; + private readonly int finishRowInd; public CellRendererInfo(CellRenderer cellRenderer, int column, int finishRow) { this.cellRenderer = cellRenderer; @@ -1894,6 +1893,24 @@ public CellRendererInfo(CellRenderer cellRenderer, int column, int finishRow) { // Otherwise, this is simply the index of the row of the cell in the {@link #rows} array. this.finishRowInd = finishRow; } + + /// Retrieves the cell renderer. + /// cell renderer + public virtual CellRenderer GetCellRenderer() { + return cellRenderer; + } + + /// Retrieves the column. + /// column + public virtual int GetColumn() { + return column; + } + + /// Retrieves the finish row index. + /// finish row index + public virtual int GetFinishRowInd() { + return finishRowInd; + } } /// Utility class that copies overflow renderer rows on cell replacement so it won't affect original renderer diff --git a/itext/itext.layout/itext/layout/renderer/TextRenderer.cs b/itext/itext.layout/itext/layout/renderer/TextRenderer.cs index 5e302e8a95..92f205661e 100644 --- a/itext/itext.layout/itext/layout/renderer/TextRenderer.cs +++ b/itext/itext.layout/itext/layout/renderer/TextRenderer.cs @@ -193,7 +193,7 @@ public override LayoutResult Layout(LayoutContext layoutContext) { .GetHeight(), 0, 0)); TargetCounterHandler.AddPageByID(this); bool anythingPlaced = false; - int currentTextPos = text.start; + int currentTextPos = text.GetStart(); UnitValue fontSize = (UnitValue)this.GetPropertyAsUnitValue(Property.FONT_SIZE); if (!fontSize.IsPointValue()) { ILogger logger = ITextLogManager.GetLogger(typeof(iText.Layout.Renderer.TextRenderer)); @@ -210,7 +210,8 @@ public override LayoutResult Layout(LayoutContext layoutContext) { float boldSimulationAddition = true.Equals(GetPropertyAsBoolean(Property.BOLD_SIMULATION)) ? BOLD_SIMULATION_STROKE_COEFF * fontSize.GetValue() : 0; line = new GlyphLine(text); - line.start = line.end = -1; + line.SetStart(-1); + line.SetEnd(-1); float ascender = 0; float descender = 0; float currentLineAscender = 0; @@ -247,19 +248,19 @@ public override LayoutResult Layout(LayoutContext layoutContext) { HyphenationConfig hyphenationConfig = this.GetProperty(Property.HYPHENATION); // For example, if a first character is a RTL mark (U+200F), and the second is a newline, we need to break anyway int firstPrintPos = currentTextPos; - while (firstPrintPos < text.end && NoPrint(text.Get(firstPrintPos))) { + while (firstPrintPos < text.GetEnd() && NoPrint(text.Get(firstPrintPos))) { firstPrintPos++; } - while (currentTextPos < text.end) { + while (currentTextPos < text.GetEnd()) { if (NoPrint(text.Get(currentTextPos))) { - if (line.start == -1) { - line.start = currentTextPos; + if (line.GetStart() == -1) { + line.SetStart(currentTextPos); } - line.end = Math.Max(line.end, currentTextPos + 1); + line.SetEnd(Math.Max(line.GetEnd(), currentTextPos + 1)); currentTextPos++; continue; } - int nonBreakablePartEnd = text.end - 1; + int nonBreakablePartEnd = text.GetEnd() - 1; float nonBreakablePartFullWidth = 0; float nonBreakablePartWidthWhichDoesNotExceedAllowedWidth = 0; float nonBreakablePartMaxAscender = 0; @@ -270,7 +271,7 @@ public override LayoutResult Layout(LayoutContext layoutContext) { int nonBreakingHyphenRelatedChunkStart = -1; float beforeNonBreakingHyphenRelatedChunkMaxAscender = 0; float beforeNonBreakingHyphenRelatedChunkMaxDescender = 0; - for (int ind = currentTextPos; ind < text.end; ind++) { + for (int ind = currentTextPos; ind < text.GetEnd(); ind++) { if (iText.IO.Util.TextUtil.IsNewLine(text.Get(ind))) { containsPossibleBreak = true; wordBreakGlyphAtLineEnding = text.Get(ind); @@ -283,24 +284,24 @@ public override LayoutResult Layout(LayoutContext layoutContext) { // Notice that in that case we do not need to ignore the new line symbol ('\n') forcePartialSplitOnFirstChar = true; } - if (line.start == -1) { - line.start = currentTextPos; + if (line.GetStart() == -1) { + line.SetStart(currentTextPos); } crlf = iText.IO.Util.TextUtil.IsCarriageReturnFollowedByLineFeed(text, currentTextPos); if (crlf) { currentTextPos++; } - line.end = Math.Max(line.end, firstCharacterWhichExceedsAllowedWidth - 1); + line.SetEnd(Math.Max(line.GetEnd(), firstCharacterWhichExceedsAllowedWidth - 1)); break; } Glyph currentGlyph = text.Get(ind); if (NoPrint(currentGlyph)) { - bool nextGlyphIsSpaceOrWhiteSpace = ind + 1 < text.end && (splitCharacters.IsSplitCharacter(text, ind + 1) - && iText.IO.Util.TextUtil.IsSpaceOrWhitespace(text.Get(ind + 1))); + bool nextGlyphIsSpaceOrWhiteSpace = ind + 1 < text.GetEnd() && (splitCharacters.IsSplitCharacter(text, ind + + 1) && iText.IO.Util.TextUtil.IsSpaceOrWhitespace(text.Get(ind + 1))); if (nextGlyphIsSpaceOrWhiteSpace && firstCharacterWhichExceedsAllowedWidth == -1) { containsPossibleBreak = true; } - if (ind + 1 == text.end || nextGlyphIsSpaceOrWhiteSpace || (ind + 1 >= indexOfFirstCharacterToBeForcedToOverflow + if (ind + 1 == text.GetEnd() || nextGlyphIsSpaceOrWhiteSpace || (ind + 1 >= indexOfFirstCharacterToBeForcedToOverflow )) { if (ind + 1 >= indexOfFirstCharacterToBeForcedToOverflow) { firstCharacterWhichExceedsAllowedWidth = currentTextPos; @@ -365,8 +366,8 @@ public override LayoutResult Layout(LayoutContext layoutContext) { nonBreakablePartMaxHeight = FontProgram.ConvertTextSpaceToGlyphSpace((nonBreakablePartMaxAscender - nonBreakablePartMaxDescender ) * fontSize.GetValue()) + textRise; previousCharPos = ind; - if (!noSoftWrap && symbolNotFitOnLine && (0 == nonBreakingHyphenRelatedChunkWidth || ind + 1 == text.end || - !GlyphBelongsToNonBreakingHyphenRelatedChunk(text, ind + 1))) { + if (!noSoftWrap && symbolNotFitOnLine && (0 == nonBreakingHyphenRelatedChunkWidth || ind + 1 == text.GetEnd + () || !GlyphBelongsToNonBreakingHyphenRelatedChunk(text, ind + 1))) { if (IsOverflowFit(overflowX)) { // we have extracted all the information we wanted and we do not want to continue. // we will have to split the word anyway. @@ -388,12 +389,12 @@ public override LayoutResult Layout(LayoutContext layoutContext) { bool endOfWordBelongingToSpecialScripts = TextContainsSpecialScriptGlyphs(true) && FindPossibleBreaksSplitPosition (specialScriptsWordBreakPoints, ind + 1, true) >= 0; bool endOfNonBreakablePartCausedBySplitCharacter = splitCharacters.IsSplitCharacter(text, ind) || (ind + 1 - < text.end && (splitCharacters.IsSplitCharacter(text, ind + 1) && iText.IO.Util.TextUtil.IsSpaceOrWhitespace + < text.GetEnd() && (splitCharacters.IsSplitCharacter(text, ind + 1) && iText.IO.Util.TextUtil.IsSpaceOrWhitespace (text.Get(ind + 1)))); if (endOfNonBreakablePartCausedBySplitCharacter && firstCharacterWhichExceedsAllowedWidth == -1) { containsPossibleBreak = true; } - if (ind + 1 == text.end || endOfNonBreakablePartCausedBySplitCharacter || endOfWordBelongingToSpecialScripts + if (ind + 1 == text.GetEnd() || endOfNonBreakablePartCausedBySplitCharacter || endOfWordBelongingToSpecialScripts || (ind + 1 >= indexOfFirstCharacterToBeForcedToOverflow)) { if (ind + 1 >= indexOfFirstCharacterToBeForcedToOverflow && !endOfNonBreakablePartCausedBySplitCharacter) { firstCharacterWhichExceedsAllowedWidth = currentTextPos; @@ -404,10 +405,10 @@ public override LayoutResult Layout(LayoutContext layoutContext) { } if (firstCharacterWhichExceedsAllowedWidth == -1) { // can fit the whole word in a line - if (line.start == -1) { - line.start = currentTextPos; + if (line.GetStart() == -1) { + line.SetStart(currentTextPos); } - line.end = Math.Max(line.end, nonBreakablePartEnd + 1); + line.SetEnd(Math.Max(line.GetEnd(), nonBreakablePartEnd + 1)); currentLineAscender = Math.Max(currentLineAscender, nonBreakablePartMaxAscender); currentLineDescender = Math.Min(currentLineDescender, nonBreakablePartMaxDescender); currentLineHeight = Math.Max(currentLineHeight, nonBreakablePartMaxHeight); @@ -438,10 +439,10 @@ public override LayoutResult Layout(LayoutContext layoutContext) { ApplyBorderBox(occupiedArea.GetBBox(), borders, true); ApplyMargins(occupiedArea.GetBBox(), margins, true); // Force to place what we can - if (line.start == -1) { - line.start = currentTextPos; + if (line.GetStart() == -1) { + line.SetStart(currentTextPos); } - line.end = Math.Max(line.end, firstCharacterWhichExceedsAllowedWidth); + line.SetEnd(Math.Max(line.GetEnd(), firstCharacterWhichExceedsAllowedWidth)); // the line does not fit because of height - full overflow iText.Layout.Renderer.TextRenderer[] splitResult = Split(initialLineTextPos); bool[] startsEnds = IsStartsWithSplitCharWhiteSpaceAndEndsWithSplitChar(splitCharacters); @@ -456,8 +457,8 @@ public override LayoutResult Layout(LayoutContext layoutContext) { if (hyphenationConfig != null && indexOfFirstCharacterToBeForcedToOverflow == UNDEFINED_FIRST_CHAR_TO_FORCE_OVERFLOW ) { if (-1 == nonBreakingHyphenRelatedChunkStart) { - int[] wordBounds = GetWordBoundsForHyphenation(text, currentTextPos, text.end, Math.Max(currentTextPos, firstCharacterWhichExceedsAllowedWidth - - 1)); + int[] wordBounds = GetWordBoundsForHyphenation(text, currentTextPos, text.GetEnd(), Math.Max(currentTextPos + , firstCharacterWhichExceedsAllowedWidth - 1)); if (wordBounds != null) { String word = text.ToUnicodeString(wordBounds[0], wordBounds[1]); iText.Layout.Hyphenation.Hyphenation hyph = hyphenationConfig.Hyphenate(word); @@ -471,13 +472,13 @@ public override LayoutResult Layout(LayoutContext layoutContext) { if (currentLineWidth + currentHyphenationChoicePreTextWidth + italicSkewAddition + boldSimulationAddition <= layoutBox.GetWidth()) { hyphenationApplied = true; - if (line.start == -1) { - line.start = currentTextPos; + if (line.GetStart() == -1) { + line.SetStart(currentTextPos); } - line.end = Math.Max(line.end, wordBounds[0] + pre.Length); - GlyphLine lineCopy = line.Copy(line.start, line.end); + line.SetEnd(Math.Max(line.GetEnd(), wordBounds[0] + pre.Length)); + GlyphLine lineCopy = line.Copy(line.GetStart(), line.GetEnd()); lineCopy.Add(font.GetGlyph(hyphenationConfig.GetHyphenSymbol())); - lineCopy.end++; + lineCopy.SetEnd(lineCopy.GetEnd() + 1); line = lineCopy; // TODO DEVSIX-7010 recalculate line properties in case of word hyphenation. // These values are based on whole word. Recalculate properly based on hyphenated part. @@ -502,7 +503,7 @@ public override LayoutResult Layout(LayoutContext layoutContext) { } } else { - if (text.start == nonBreakingHyphenRelatedChunkStart) { + if (text.GetStart() == nonBreakingHyphenRelatedChunkStart) { nonBreakingHyphenRelatedChunkWidth = 0; firstCharacterWhichExceedsAllowedWidth = previousCharPos + 1; } @@ -521,15 +522,15 @@ public override LayoutResult Layout(LayoutContext layoutContext) { // if the word is too long for a single line we will have to split it // we also need to split the word here if text contains glyphs from scripts // which require word wrapping for further processing in LineRenderer - if (line.start == -1) { - line.start = currentTextPos; + if (line.GetStart() == -1) { + line.SetStart(currentTextPos); } if (!crlf) { currentTextPos = (forcePartialSplitOnFirstChar || IsOverflowFit(overflowX) || specialScriptWordSplit) ? firstCharacterWhichExceedsAllowedWidth : nonBreakablePartEnd + 1; } - line.end = Math.Max(line.end, currentTextPos); - wordSplit = !forcePartialSplitOnFirstChar && (text.end != currentTextPos); + line.SetEnd(Math.Max(line.GetEnd(), currentTextPos)); + wordSplit = !forcePartialSplitOnFirstChar && (text.GetEnd() != currentTextPos); if (wordSplit || !(forcePartialSplitOnFirstChar || IsOverflowFit(overflowX))) { currentLineAscender = Math.Max(currentLineAscender, nonBreakablePartMaxAscender); currentLineDescender = Math.Min(currentLineDescender, nonBreakablePartMaxDescender); @@ -557,11 +558,11 @@ public override LayoutResult Layout(LayoutContext layoutContext) { currentLineDescender = descender; currentLineHeight = FontProgram.ConvertTextSpaceToGlyphSpace((currentLineAscender - currentLineDescender) * fontSize.GetValue()) + textRise; - currentLineWidth += FontProgram.ConvertTextSpaceToGlyphSpace(GetCharWidth(line.Get(line.start), fontSize.GetValue - (), hScale, characterSpacing, wordSpacing)); + currentLineWidth += FontProgram.ConvertTextSpaceToGlyphSpace(GetCharWidth(line.Get(line.GetStart()), fontSize + .GetValue(), hScale, characterSpacing, wordSpacing)); } } - if (line.end <= line.start) { + if (line.GetEnd() <= line.GetStart()) { bool[] startsEnds = IsStartsWithSplitCharWhiteSpaceAndEndsWithSplitChar(splitCharacters); return new TextLayoutResult(LayoutResult.NOTHING, occupiedArea, null, this, this).SetContainsPossibleBreak (containsPossibleBreak).SetStartsWithSplitCharacterWhiteSpace(startsEnds[0]).SetEndsWithSplitCharacter @@ -621,7 +622,7 @@ public override LayoutResult Layout(LayoutContext layoutContext) { split[0].SaveWordBreakIfNotYetSaved(wordBreakGlyphAtLineEnding); } // no sense to process empty renderer - if (split[1].text.start != split[1].text.end) { + if (split[1].text.GetStart() != split[1].text.GetEnd()) { result.SetOverflowRenderer(split[1]); } else { @@ -675,7 +676,7 @@ private void IncreaseYLineOffset(UnitValue[] paddings, Border[] borders, UnitVal public virtual void ApplyOtf() { UpdateFontAndText(); UnicodeScript? script = this.GetProperty(Property.FONT_SCRIPT); - if (!otfFeaturesApplied && TypographyUtils.IsPdfCalligraphAvailable() && text.start < text.end) { + if (!otfFeaturesApplied && TypographyUtils.IsPdfCalligraphAvailable() && text.GetStart() < text.GetEnd()) { PdfDocument pdfDocument = GetPdfDocument(); SequenceId sequenceId = pdfDocument == null ? null : pdfDocument.GetDocumentIdWrapper(); MetaInfoContainer metaInfoContainer = this.GetProperty(Property.META_INFO); @@ -691,13 +692,13 @@ public virtual void ApplyOtf() { } IList scriptsRanges = new List(); if (script != null) { - scriptsRanges.Add(new TextRenderer.ScriptRange(script, text.end)); + scriptsRanges.Add(new TextRenderer.ScriptRange(script, text.GetEnd())); } else { // Try to autodetect script. - TextRenderer.ScriptRange currRange = new TextRenderer.ScriptRange(null, text.end); + TextRenderer.ScriptRange currRange = new TextRenderer.ScriptRange(null, text.GetEnd()); scriptsRanges.Add(currRange); - for (int i = text.start; i < text.end; i++) { + for (int i = text.GetStart(); i < text.GetEnd(); i++) { int unicode = text.Get(i).GetUnicode(); if (unicode > -1) { UnicodeScript glyphScript = UnicodeScriptUtil.Of(unicode); @@ -711,7 +712,7 @@ public virtual void ApplyOtf() { } else { currRange.rangeEnd = i; - currRange = new TextRenderer.ScriptRange(glyphScript, text.end); + currRange = new TextRenderer.ScriptRange(glyphScript, text.GetEnd()); scriptsRanges.Add(currRange); } } @@ -719,16 +720,16 @@ public virtual void ApplyOtf() { } } int delta = 0; - int origTextStart = text.start; - int origTextEnd = text.end; - int shapingRangeStart = text.start; + int origTextStart = text.GetStart(); + int origTextEnd = text.GetEnd(); + int shapingRangeStart = text.GetStart(); foreach (TextRenderer.ScriptRange scriptsRange in scriptsRanges) { if (scriptsRange.script == null || !supportedScripts.Contains(EnumUtil.ThrowIfNull(scriptsRange.script))) { continue; } scriptsRange.rangeEnd += delta; - text.start = shapingRangeStart; - text.end = scriptsRange.rangeEnd; + text.SetStart(shapingRangeStart); + text.SetEnd(scriptsRange.rangeEnd); if ((scriptsRange.script == UnicodeScript.ARABIC || scriptsRange.script == UnicodeScript.HEBREW) && parent is LineRenderer) { // It's safe to set here BASE_DIRECTION to TextRenderer without additional checks, because @@ -740,11 +741,11 @@ public virtual void ApplyOtf() { } TypographyUtils.ApplyOtfScript(font.GetFontProgram(), text, scriptsRange.script, typographyConfig, sequenceId , metaInfo); - delta += text.end - scriptsRange.rangeEnd; - scriptsRange.rangeEnd = shapingRangeStart = text.end; + delta += text.GetEnd() - scriptsRange.rangeEnd; + scriptsRange.rangeEnd = shapingRangeStart = text.GetEnd(); } - text.start = origTextStart; - text.end = origTextEnd + delta; + text.SetStart(origTextStart); + text.SetEnd(origTextEnd + delta); } FontKerning fontKerning = (FontKerning)this.GetProperty(Property.FONT_KERNING, FontKerning.NO ); @@ -789,7 +790,7 @@ public override void Draw(DrawContext drawContext) { ApplyRelativePositioningTranslation(false); } float leftBBoxX = GetInnerAreaBBox().GetX(); - if (line.end > line.start || savedWordBreakAtLineEnding != null) { + if (line.GetEnd() > line.GetStart() || savedWordBreakAtLineEnding != null) { UnitValue fontSize = this.GetPropertyAsUnitValue(Property.FONT_SIZE); if (!fontSize.IsPointValue()) { ILogger logger = ITextLogManager.GetLogger(typeof(iText.Layout.Renderer.TextRenderer)); @@ -868,7 +869,7 @@ public override void Draw(DrawContext drawContext) { // It does not apply to occurrences of the byte value 32 in multiple-byte codes. // // For PdfType0Font we must add word manually with glyph offsets - for (int gInd = line.start; gInd < line.end; gInd++) { + for (int gInd = line.GetStart(); gInd < line.GetEnd(); gInd++) { if (iText.IO.Util.TextUtil.IsUni0020(line.Get(gInd))) { short advance = (short)(FontProgram.ConvertGlyphSpaceToTextSpace((float)wordSpacing) / fontSize.GetValue() ); @@ -890,7 +891,7 @@ public override void Draw(DrawContext drawContext) { if (GetReversedRanges() != null) { bool writeReversedChars = !appearanceStreamLayout; List removedIds = new List(); - for (int i = line.start; i < line.end; i++) { + for (int i = line.GetStart(); i < line.GetEnd(); i++) { if (!filter.Accept(line.Get(i))) { removedIds.Add(i); } @@ -908,7 +909,7 @@ public override void Draw(DrawContext drawContext) { } else { if (appearanceStreamLayout) { - line.SetActualText(line.start, line.end, null); + line.SetActualText(line.GetStart(), line.GetEnd(), null); } canvas.ShowText(line.Filter(filter)); } @@ -956,9 +957,9 @@ public virtual void TrimFirst() { UpdateFontAndText(); if (text != null) { Glyph glyph; - while (text.start < text.end && iText.IO.Util.TextUtil.IsWhitespace(glyph = text.Get(text.start)) && !iText.IO.Util.TextUtil - .IsNewLine(glyph)) { - text.start++; + while (text.GetStart() < text.GetEnd() && iText.IO.Util.TextUtil.IsWhitespace(glyph = text.Get(text.GetStart + ())) && !iText.IO.Util.TextUtil.IsNewLine(glyph)) { + text.SetStart(text.GetStart() + 1); } } /* Between two sentences separated by one or more whitespaces, @@ -969,7 +970,7 @@ we need to remove this point from the list (or replace it with -1 thus marking that text contains special scripts, in case if the removed break point was the only possible break point). */ - if (TextContainsSpecialScriptGlyphs(true) && specialScriptsWordBreakPoints[0] == text.start) { + if (TextContainsSpecialScriptGlyphs(true) && specialScriptsWordBreakPoints[0] == text.GetStart()) { if (specialScriptsWordBreakPoints.Count == 1) { specialScriptsWordBreakPoints[0] = -1; } @@ -982,7 +983,7 @@ we need to remove this point from the list //\cond DO_NOT_DOCUMENT internal virtual float TrimLast() { float trimmedSpace = 0; - if (line.end <= 0) { + if (line.GetEnd() <= 0) { return trimmedSpace; } UnitValue fontSize = (UnitValue)this.GetPropertyAsUnitValue(Property.FONT_SIZE); @@ -994,8 +995,8 @@ internal virtual float TrimLast() { float? characterSpacing = this.GetPropertyAsFloat(Property.CHARACTER_SPACING); float? wordSpacing = this.GetPropertyAsFloat(Property.WORD_SPACING); float hScale = (float)this.GetPropertyAsFloat(Property.HORIZONTAL_SCALING, 1f); - int firstNonSpaceCharIndex = line.end - 1; - while (firstNonSpaceCharIndex >= line.start) { + int firstNonSpaceCharIndex = line.GetEnd() - 1; + while (firstNonSpaceCharIndex >= line.GetStart()) { Glyph currentGlyph = line.Get(firstNonSpaceCharIndex); if (!iText.IO.Util.TextUtil.IsWhitespace(currentGlyph)) { break; @@ -1003,13 +1004,13 @@ internal virtual float TrimLast() { SaveWordBreakIfNotYetSaved(currentGlyph); float currentCharWidth = FontProgram.ConvertTextSpaceToGlyphSpace(GetCharWidth(currentGlyph, fontSize.GetValue (), hScale, characterSpacing, wordSpacing)); - float xAdvance = firstNonSpaceCharIndex > line.start ? FontProgram.ConvertTextSpaceToGlyphSpace(ScaleXAdvance + float xAdvance = firstNonSpaceCharIndex > line.GetStart() ? FontProgram.ConvertTextSpaceToGlyphSpace(ScaleXAdvance (line.Get(firstNonSpaceCharIndex - 1).GetXAdvance(), fontSize.GetValue(), hScale)) : 0; trimmedSpace += currentCharWidth - xAdvance; occupiedArea.GetBBox().SetWidth(occupiedArea.GetBBox().GetWidth() - currentCharWidth); firstNonSpaceCharIndex--; } - line.end = firstNonSpaceCharIndex + 1; + line.SetEnd(firstNonSpaceCharIndex + 1); return trimmedSpace; } //\endcond @@ -1087,7 +1088,7 @@ public virtual GlyphLine GetText() { /// The length of the whole text assigned to this renderer. /// the text length public virtual int Length() { - return text == null ? 0 : text.end - text.start; + return text == null ? 0 : text.GetEnd() - text.GetStart(); } public override String ToString() { @@ -1098,7 +1099,7 @@ public override String ToString() { /// the position in range [0; length()) /// Unicode char code public virtual int CharAt(int pos) { - return text.Get(pos + text.start).GetUnicode(); + return text.Get(pos + text.GetStart()).GetUnicode(); } public virtual float GetTabAnchorCharacterPosition() { @@ -1267,7 +1268,7 @@ internal virtual bool TextContainsSpecialScriptGlyphs(bool analyzeSpecialScripts if (splitCharacters is BreakAllSplitCharacters) { specialScriptsWordBreakPoints = new List(); } - for (int i = text.start; i < text.end; i++) { + for (int i = text.GetStart(); i < text.GetEnd(); i++) { int unicode = text.Get(i).GetUnicode(); if (unicode > -1) { if (CodePointIsOfSpecialScript(unicode)) { @@ -1344,12 +1345,12 @@ protected internal override Rectangle GetBackgroundArea(Rectangle occupiedAreaWi /// /// the length of the line protected internal virtual int LineLength() { - return line.end > 0 ? line.end - line.start : 0; + return line.GetEnd() > 0 ? line.GetEnd() - line.GetStart() : 0; } protected internal virtual int BaseCharactersCount() { int count = 0; - for (int i = line.start; i < line.end; i++) { + for (int i = line.GetStart(); i < line.GetEnd(); i++) { Glyph glyph = line.Get(i); if (!glyph.HasPlacement()) { count++; @@ -1365,11 +1366,11 @@ public override MinMaxWidth GetMinMaxWidth() { } protected internal virtual int GetNumberOfSpaces() { - if (line.end <= 0) { + if (line.GetEnd() <= 0) { return 0; } int spaces = 0; - for (int i = line.start; i < line.end; i++) { + for (int i = line.GetStart(); i < line.GetEnd(); i++) { Glyph currentGlyph = line.Get(i); if (currentGlyph.GetUnicode() == ' ') { spaces++; @@ -1389,8 +1390,8 @@ protected internal virtual iText.Layout.Renderer.TextRenderer CreateOverflowRend protected internal virtual iText.Layout.Renderer.TextRenderer[] Split(int initialOverflowTextPos) { iText.Layout.Renderer.TextRenderer splitRenderer = CreateSplitRenderer(); GlyphLine newText = new GlyphLine(text); - newText.start = text.start; - newText.end = initialOverflowTextPos; + newText.SetStart(text.GetStart()); + newText.SetEnd(initialOverflowTextPos); splitRenderer.SetProcessedGlyphLineAndFont(newText, font); splitRenderer.line = line; splitRenderer.occupiedArea = occupiedArea.Clone(); @@ -1401,8 +1402,8 @@ protected internal virtual iText.Layout.Renderer.TextRenderer[] Split(int initia splitRenderer.AddAllProperties(GetOwnProperties()); iText.Layout.Renderer.TextRenderer overflowRenderer = CreateOverflowRenderer(); newText = new GlyphLine(text); - newText.start = initialOverflowTextPos; - newText.end = text.end; + newText.SetStart(initialOverflowTextPos); + newText.SetEnd(text.GetEnd()); overflowRenderer.SetProcessedGlyphLineAndFont(newText, font); overflowRenderer.otfFeaturesApplied = otfFeaturesApplied; overflowRenderer.parent = parent; @@ -1690,15 +1691,16 @@ internal override PdfFont ResolveFirstPdfFont(String[] font, FontProvider provid /// internal virtual bool[] IsStartsWithSplitCharWhiteSpaceAndEndsWithSplitChar(ISplitCharacters splitCharacters ) { - bool startsWithBreak = line.start < line.end && splitCharacters.IsSplitCharacter(text, line.start) && iText.IO.Util.TextUtil - .IsSpaceOrWhitespace(text.Get(line.start)); - bool endsWithBreak = line.start < line.end && splitCharacters.IsSplitCharacter(text, line.end - 1); + bool startsWithBreak = line.GetStart() < line.GetEnd() && splitCharacters.IsSplitCharacter(text, line.GetStart + ()) && iText.IO.Util.TextUtil.IsSpaceOrWhitespace(text.Get(line.GetStart())); + bool endsWithBreak = line.GetStart() < line.GetEnd() && splitCharacters.IsSplitCharacter(text, line.GetEnd + () - 1); if (specialScriptsWordBreakPoints == null || specialScriptsWordBreakPoints.IsEmpty()) { return new bool[] { startsWithBreak, endsWithBreak }; } else { if (!endsWithBreak) { - endsWithBreak = specialScriptsWordBreakPoints.Contains(line.end); + endsWithBreak = specialScriptsWordBreakPoints.Contains(line.GetEnd()); } return new bool[] { startsWithBreak, endsWithBreak }; } @@ -1738,12 +1740,12 @@ private float ScaleXAdvance(float xAdvance, float fontSize, float? hScale) { private float GetGlyphLineWidth(GlyphLine glyphLine, float fontSize, float hScale, float? characterSpacing , float? wordSpacing) { float width = 0; - for (int i = glyphLine.start; i < glyphLine.end; i++) { + for (int i = glyphLine.GetStart(); i < glyphLine.GetEnd(); i++) { if (!NoPrint(glyphLine.Get(i))) { float charWidth = GetCharWidth(glyphLine.Get(i), fontSize, hScale, characterSpacing, wordSpacing); width += charWidth; - float xAdvance = (i != glyphLine.start) ? ScaleXAdvance(glyphLine.Get(i - 1).GetXAdvance(), fontSize, hScale - ) : 0; + float xAdvance = (i != glyphLine.GetStart()) ? ScaleXAdvance(glyphLine.Get(i - 1).GetXAdvance(), fontSize, + hScale) : 0; width += xAdvance; } } @@ -1837,8 +1839,8 @@ private static bool NoPrint(Glyph g) { } private static bool GlyphBelongsToNonBreakingHyphenRelatedChunk(GlyphLine text, int ind) { - return iText.IO.Util.TextUtil.IsNonBreakingHyphen(text.Get(ind)) || (ind + 1 < text.end && iText.IO.Util.TextUtil - .IsNonBreakingHyphen(text.Get(ind + 1))) || ind - 1 >= text.start && iText.IO.Util.TextUtil.IsNonBreakingHyphen + return iText.IO.Util.TextUtil.IsNonBreakingHyphen(text.Get(ind)) || (ind + 1 < text.GetEnd() && iText.IO.Util.TextUtil + .IsNonBreakingHyphen(text.Get(ind + 1))) || ind - 1 >= text.GetStart() && iText.IO.Util.TextUtil.IsNonBreakingHyphen (text.Get(ind - 1)); } @@ -1882,8 +1884,8 @@ public ReversedCharsIterator(IList reversedRange, GlyphLine line) { } } else { - outStart.Add(line.start); - outEnd.Add(line.end); + outStart.Add(line.GetStart()); + outEnd.Add(line.GetEnd()); reversed.Add(false); } } diff --git a/itext/itext.layout/itext/layout/renderer/TextSequenceWordWrapping.cs b/itext/itext.layout/itext/layout/renderer/TextSequenceWordWrapping.cs index 0d27e1d4e7..bde70d3e1a 100644 --- a/itext/itext.layout/itext/layout/renderer/TextSequenceWordWrapping.cs +++ b/itext/itext.layout/itext/layout/renderer/TextSequenceWordWrapping.cs @@ -193,7 +193,7 @@ public static TextSequenceWordWrapping.LastFittingChildRendererData GetIndexAndL break; } if (textLayoutResult.IsContainsPossibleBreak() && textLayoutResult.GetStatus() != LayoutResult.NOTHING) { - textRenderer.SetIndexOfFirstCharacterToBeForcedToOverflow(textRenderer.line.end); + textRenderer.SetIndexOfFirstCharacterToBeForcedToOverflow(textRenderer.line.GetEnd()); LayoutArea layoutArea = textRenderer.GetOccupiedArea().Clone(); layoutArea.GetBBox().IncreaseHeight(OCCUPIED_AREA_RELAYOUT_EPS).IncreaseWidth(OCCUPIED_AREA_RELAYOUT_EPS); // Here we relayout the child with the possible break using its own occupied area as @@ -287,8 +287,8 @@ public static TextSequenceWordWrapping.LastFittingChildRendererData GetIndexAndL GlyphLine splitText = splitTextRenderer.text; if (splitTextRenderer.Length() > 0) { fittingLengthWithTrailingRightSideSpaces = splitTextRenderer.Length(); - while (splitText.end + amountOfTrailingRightSideSpaces < splitText.Size() && iText.IO.Util.TextUtil.IsWhitespace - (splitText.Get(splitText.end + amountOfTrailingRightSideSpaces))) { + while (splitText.GetEnd() + amountOfTrailingRightSideSpaces < splitText.Size() && iText.IO.Util.TextUtil.IsWhitespace + (splitText.Get(splitText.GetEnd() + amountOfTrailingRightSideSpaces))) { fittingLengthWithTrailingRightSideSpaces++; amountOfTrailingRightSideSpaces++; } @@ -300,10 +300,10 @@ public static TextSequenceWordWrapping.LastFittingChildRendererData GetIndexAndL IList breakPoints = textRenderer.GetSpecialScriptsWordBreakPoints(); if (breakPoints != null && breakPoints.Count > 0 && breakPoints[0] != -1) { int possibleBreakPointPosition = TextRenderer.FindPossibleBreaksSplitPosition(textRenderer.GetSpecialScriptsWordBreakPoints - (), fittingLengthWithTrailingRightSideSpaces + textRenderer.text.start, false); + (), fittingLengthWithTrailingRightSideSpaces + textRenderer.text.GetStart(), false); if (possibleBreakPointPosition > -1) { splitPosition = breakPoints[possibleBreakPointPosition] - amountOfTrailingRightSideSpaces; - needToSplitRendererContainingLastFullyFittingWord = splitPosition != textRenderer.text.end; + needToSplitRendererContainingLastFullyFittingWord = splitPosition != textRenderer.text.GetEnd(); if (!needToSplitRendererContainingLastFullyFittingWord) { analyzedTextRendererIndex++; } @@ -349,7 +349,7 @@ public static TextSequenceWordWrapping.LastFittingChildRendererData GetIndexAndL ]; if (needToSplitRendererContainingLastFullyFittingWord) { int amountOfFitOnTheFirstLayout = fittingLengthWithTrailingRightSideSpaces - amountOfTrailingRightSideSpaces - + childRenderer.text.start; + + childRenderer.text.GetStart(); if (amountOfFitOnTheFirstLayout != splitPosition) { LayoutArea layoutArea = childRenderer.GetOccupiedArea().Clone(); layoutArea.GetBBox().IncreaseHeight(OCCUPIED_AREA_RELAYOUT_EPS).IncreaseWidth(OCCUPIED_AREA_RELAYOUT_EPS); @@ -700,15 +700,15 @@ private static void FillActualTextChunkRelatedLists(GlyphLine glyphLine, IList. +*/ +using iText.Kernel.Validation; +using iText.Layout.Renderer; + +namespace iText.Layout.Validation.Context { + /// + /// Class for + /// + /// validation context. + /// + public class LayoutValidationContext : IValidationContext { + private readonly IRenderer renderer; + + /// + /// Instantiates a new + /// + /// based on renderer. + /// + /// the renderer + public LayoutValidationContext(IRenderer renderer) { + this.renderer = renderer; + } + + /// Gets the renderer. + /// the renderer + public virtual IRenderer GetRenderer() { + return renderer; + } + + public virtual ValidationType GetType() { + return ValidationType.LAYOUT; + } + } +} diff --git a/itext/itext.pdfa/Properties/AssemblyInfo.cs b/itext/itext.pdfa/Properties/AssemblyInfo.cs index 8d1bea0107..6ac2a63bcd 100644 --- a/itext/itext.pdfa/Properties/AssemblyInfo.cs +++ b/itext/itext.pdfa/Properties/AssemblyInfo.cs @@ -21,6 +21,6 @@ [assembly: Guid("9fc2f0b3-a8d2-46da-8724-72e00e67a8fa")] -[assembly: AssemblyVersion("8.0.5.0")] -[assembly: AssemblyFileVersion("8.0.5.0")] -[assembly: AssemblyInformationalVersion("8.0.5")] +[assembly: AssemblyVersion("9.0.0.0")] +[assembly: AssemblyFileVersion("9.0.0.0")] +[assembly: AssemblyInformationalVersion("9.0.0")] diff --git a/itext/itext.pdfa/itext/pdfa/PdfAAgnosticPdfDocument.cs b/itext/itext.pdfa/itext/pdfa/PdfAAgnosticPdfDocument.cs deleted file mode 100644 index 11a3794fb6..0000000000 --- a/itext/itext.pdfa/itext/pdfa/PdfAAgnosticPdfDocument.cs +++ /dev/null @@ -1,86 +0,0 @@ -/* -This file is part of the iText (R) project. -Copyright (c) 1998-2024 Apryse Group NV -Authors: Apryse Software. - -This program is offered under a commercial and under the AGPL license. -For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. - -AGPL licensing: -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . -*/ -using iText.Kernel.Pdf; - -namespace iText.Pdfa { - /// - /// This class extends - /// - /// and serves as - /// - /// for - /// PDF/A compliant documents and as - /// - /// for non PDF/A documents. - /// - /// - /// This class extends - /// - /// and serves as - /// - /// for - /// PDF/A compliant documents and as - /// - /// for non PDF/A documents. - /// - /// This class can throw various exceptions like - /// - /// as well as - /// - /// for PDF/A documents. - /// - public class PdfAAgnosticPdfDocument : PdfADocument { - /// Opens a PDF/A document in stamping mode. - /// - /// the - /// - /// - /// - /// the - /// - /// object to write to - /// - public PdfAAgnosticPdfDocument(PdfReader reader, PdfWriter writer) - : this(reader, writer, new StampingProperties()) { - } - - /// Opens a PDF/A document in stamping mode. - /// - /// the - /// - /// - /// - /// the - /// - /// object to write to - /// - /// - /// - /// - /// of the stamping process - /// - public PdfAAgnosticPdfDocument(PdfReader reader, PdfWriter writer, StampingProperties properties) - : base(reader, writer, properties, true) { - } - } -} diff --git a/itext/itext.pdfa/itext/pdfa/PdfADefaultFontStrategy.cs b/itext/itext.pdfa/itext/pdfa/PdfADefaultFontStrategy.cs new file mode 100644 index 0000000000..3f3fb194c7 --- /dev/null +++ b/itext/itext.pdfa/itext/pdfa/PdfADefaultFontStrategy.cs @@ -0,0 +1,49 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Font; +using iText.Kernel.Pdf; + +namespace iText.Pdfa { + /// + /// The class presents default font strategy for PDF/A documents which + /// doesn't provide default font because all used fonts must be embedded. + /// + public class PdfADefaultFontStrategy : DefaultFontStrategy { + /// + /// Instantiates a new + /// + /// instance based on the document which will use that strategy. + /// + /// the pdf document which will use that strategy + public PdfADefaultFontStrategy(PdfDocument pdfDocument) + : base(pdfDocument) { + } + + /// + /// . + /// + public override PdfFont GetFont() { + return null; + } + } +} diff --git a/itext/itext.pdfa/itext/pdfa/PdfADocument.cs b/itext/itext.pdfa/itext/pdfa/PdfADocument.cs index 0e1b2580c0..bfe63814dd 100644 --- a/itext/itext.pdfa/itext/pdfa/PdfADocument.cs +++ b/itext/itext.pdfa/itext/pdfa/PdfADocument.cs @@ -23,11 +23,9 @@ You should have received a copy of the GNU Affero General Public License using System; using Microsoft.Extensions.Logging; using iText.Commons; -using iText.Kernel.Font; +using iText.Commons.Utils; using iText.Kernel.Pdf; -using iText.Kernel.Pdf.Tagutils; -using iText.Kernel.Utils; -using iText.Kernel.XMP; +using iText.Kernel.Validation; using iText.Pdfa.Checker; using iText.Pdfa.Exceptions; using iText.Pdfa.Logs; @@ -44,32 +42,24 @@ namespace iText.Pdfa { /// /// and is in charge of creating files /// that comply with the PDF/A standard. + /// /// Client code is still responsible for making sure the file is actually PDF/A /// compliant: multiple steps must be undertaken (depending on the - /// + /// /// ) to ensure that the PDF/A standard is followed. + /// /// This class will throw exceptions, mostly /// /// , /// and thus refuse to output a PDF/A file if at any point the document does not /// adhere to the PDF/A guidelines specified by the - /// . + /// . /// public class PdfADocument : PdfDocument { - private static IPdfPageFactory pdfAPageFactory = new PdfAPageFactory(); - - protected internal PdfAChecker checker; - - private bool alreadyLoggedThatObjectFlushingWasNotPerformed = false; - - private bool alreadyLoggedThatPageFlushingWasNotPerformed = false; - - private bool isPdfADocument = true; - /// Constructs a new PdfADocument for writing purposes, i.e. from scratch. /// /// Constructs a new PdfADocument for writing purposes, i.e. from scratch. A - /// PDF/A file has a conformance level, and must have an explicit output + /// PDF/A file has a conformance, and must have an explicit output /// intent. /// /// @@ -77,19 +67,19 @@ public class PdfADocument : PdfDocument { /// /// object to write to /// - /// the generation and strictness level of the PDF/A that must be followed. + /// the generation and strictness level of the PDF/A that must be followed. /// /// a /// /// - public PdfADocument(PdfWriter writer, PdfAConformanceLevel conformanceLevel, PdfOutputIntent outputIntent) - : this(writer, conformanceLevel, outputIntent, new DocumentProperties()) { + public PdfADocument(PdfWriter writer, PdfAConformance aConformance, PdfOutputIntent outputIntent) + : this(writer, aConformance, outputIntent, new DocumentProperties()) { } /// Constructs a new PdfADocument for writing purposes, i.e. from scratch. /// /// Constructs a new PdfADocument for writing purposes, i.e. from scratch. A - /// PDF/A file has a conformance level, and must have an explicit output + /// PDF/A file has a conformance, and must have an explicit output /// intent. /// /// @@ -97,7 +87,7 @@ public PdfADocument(PdfWriter writer, PdfAConformanceLevel conformanceLevel, Pdf /// /// object to write to /// - /// the generation and strictness level of the PDF/A that must be followed. + /// the generation and strictness level of the PDF/A that must be followed. /// /// a /// @@ -106,25 +96,19 @@ public PdfADocument(PdfWriter writer, PdfAConformanceLevel conformanceLevel, Pdf /// a /// /// - public PdfADocument(PdfWriter writer, PdfAConformanceLevel conformanceLevel, PdfOutputIntent outputIntent, - DocumentProperties properties) - : base(writer, properties) { - SetChecker(conformanceLevel); + public PdfADocument(PdfWriter writer, PdfAConformance aConformance, PdfOutputIntent outputIntent, DocumentProperties + properties) + : base(ConfigureWriterProperties(writer, aConformance), properties) { + PdfAChecker checker = GetCorrectCheckerFromConformance(GetConformance().GetAConformance()); + ValidationContainer validationContainer = new ValidationContainer(); + validationContainer.AddChecker(checker); + GetDiContainer().Register(typeof(ValidationContainer), validationContainer); + this.pdfPageFactory = new PdfAPageFactory(checker); + this.documentInfoHelper = new PdfADocumentInfoHelper(this); + this.defaultFontStrategy = new PdfADefaultFontStrategy(this); AddOutputIntent(outputIntent); } - /// No default font for PDF/A documents. - /// - /// - /// . - /// - public override PdfFont GetDefaultFont() { - if (isPdfADocument) { - return null; - } - return base.GetDefaultFont(); - } - /// Opens a PDF/A document in the stamping mode. /// PDF reader. /// PDF writer. @@ -137,197 +121,47 @@ public PdfADocument(PdfReader reader, PdfWriter writer) /// PDF writer. /// properties of the stamping process public PdfADocument(PdfReader reader, PdfWriter writer, StampingProperties properties) - : this(reader, writer, properties, false) { - } - -//\cond DO_NOT_DOCUMENT - internal PdfADocument(PdfReader reader, PdfWriter writer, StampingProperties properties, bool tolerant) : base(reader, writer, properties) { - PdfAConformanceLevel conformanceLevel = reader.GetPdfAConformanceLevel(); - if (conformanceLevel == null) { - if (tolerant) { - isPdfADocument = false; - } - else { - throw new PdfAConformanceException(PdfaExceptionMessageConstant.DOCUMENT_TO_READ_FROM_SHALL_BE_A_PDFA_CONFORMANT_FILE_WITH_VALID_XMP_METADATA - ); - } - } - SetChecker(conformanceLevel); - } -//\endcond - - /// - public override IConformanceLevel GetConformanceLevel() { - if (isPdfADocument) { - return checker.GetConformanceLevel(); - } - else { - return null; - } - } - - /// - /// - /// - /// - /// - public override void AddOutputIntent(PdfOutputIntent outputIntent) { - base.AddOutputIntent(outputIntent); - checker.SetPdfAOutputIntentColorSpace(GetCatalog().GetPdfObject()); - } - -//\cond DO_NOT_DOCUMENT - internal virtual void LogThatPdfAPageFlushingWasNotPerformed() { - if (!alreadyLoggedThatPageFlushingWasNotPerformed) { - alreadyLoggedThatPageFlushingWasNotPerformed = true; - // This log message will be printed once for one instance of the document. - ITextLogManager.GetLogger(typeof(iText.Pdfa.PdfADocument)).LogWarning(PdfALogMessageConstant.PDFA_PAGE_FLUSHING_WAS_NOT_PERFORMED + if (!GetConformance().IsPdfA()) { + throw new PdfAConformanceException(PdfaExceptionMessageConstant.DOCUMENT_TO_READ_FROM_SHALL_BE_A_PDFA_CONFORMANT_FILE_WITH_VALID_XMP_METADATA ); } - } -//\endcond - - protected override void AddCustomMetadataExtensions(XMPMeta xmpMeta) { - if (!isPdfADocument) { - base.AddCustomMetadataExtensions(xmpMeta); - return; - } - if (this.IsTagged()) { - try { - if (xmpMeta.GetPropertyInteger(XMPConst.NS_PDFUA_ID, XMPConst.PART) != null) { - XMPMeta taggedExtensionMeta = XMPMetaFactory.ParseFromString(PdfAXMPUtil.PDF_UA_EXTENSION); - XMPUtils.AppendProperties(taggedExtensionMeta, xmpMeta, true, false); - } - } - catch (XMPException exc) { - ILogger logger = ITextLogManager.GetLogger(typeof(iText.Pdfa.PdfADocument)); - logger.LogError(exc, iText.IO.Logs.IoLogMessageConstant.EXCEPTION_WHILE_UPDATING_XMPMETADATA); - } - } - } - - protected override void UpdateXmpMetadata() { - if (!isPdfADocument) { - base.UpdateXmpMetadata(); - return; - } - try { - XMPMeta xmpMeta = UpdateDefaultXmpMetadata(); - xmpMeta.SetProperty(XMPConst.NS_PDFA_ID, XMPConst.PART, checker.GetConformanceLevel().GetPart()); - if (checker.GetConformanceLevel().GetConformance() != null) { - xmpMeta.SetProperty(XMPConst.NS_PDFA_ID, XMPConst.CONFORMANCE, checker.GetConformanceLevel().GetConformance - ()); - } - if ("4".Equals(checker.GetConformanceLevel().GetPart())) { - xmpMeta.SetProperty(XMPConst.NS_PDFA_ID, XMPConst.REV, PdfAConformanceLevel.PDF_A_4_REVISION); - } - AddCustomMetadataExtensions(xmpMeta); - SetXmpMetadata(xmpMeta); - } - catch (XMPException e) { - ILogger logger = ITextLogManager.GetLogger(typeof(iText.Pdfa.PdfADocument)); - logger.LogError(e, iText.IO.Logs.IoLogMessageConstant.EXCEPTION_WHILE_UPDATING_XMPMETADATA); - } - } - - protected override void CheckIsoConformance() { - SetCheckerIfChanged(); - base.CheckIsoConformance(); - } - - /// an object to conform. - /// type of object to conform. - /// - /// - /// - /// associated with an object to check. - /// - /// current content stream. - /// extra data required for the check. - public override void CheckIsoConformance(Object obj, IsoKey key, PdfResources resources, PdfStream contentStream - , Object extra) { - SetCheckerIfChanged(); - base.CheckIsoConformance(obj, key, resources, contentStream, extra); - } - - protected override void FlushObject(PdfObject pdfObject, bool canBeInObjStm) { - if (!isPdfADocument) { - base.FlushObject(pdfObject, canBeInObjStm); - return; - } - MarkObjectAsMustBeFlushed(pdfObject); - if (isClosing || checker.ObjectIsChecked(pdfObject)) { - base.FlushObject(pdfObject, canBeInObjStm); - } - else { - if (!alreadyLoggedThatObjectFlushingWasNotPerformed) { - alreadyLoggedThatObjectFlushingWasNotPerformed = true; - // This log message will be printed once for one instance of the document. - ITextLogManager.GetLogger(typeof(iText.Pdfa.PdfADocument)).LogWarning(PdfALogMessageConstant.PDFA_OBJECT_FLUSHING_WAS_NOT_PERFORMED - ); - } - } - } - - /// - /// Sets the checker that defines the requirements of the PDF/A standard - /// depending on conformance level. - /// - /// - /// - /// - /// - protected internal virtual void SetChecker(PdfAConformanceLevel conformanceLevel) { - if (!isPdfADocument) { - return; - } - SetChecker(GetCorrectCheckerFromConformance(conformanceLevel)); - } - - protected internal virtual void SetChecker(PdfAChecker checker) { - if (!isPdfADocument) { - return; - } - this.checker = checker; + PdfAChecker checker = GetCorrectCheckerFromConformance(GetConformance().GetAConformance()); ValidationContainer validationContainer = new ValidationContainer(); validationContainer.AddChecker(checker); - this.GetDiContainer().Register(typeof(ValidationContainer), validationContainer); + GetDiContainer().Register(typeof(ValidationContainer), validationContainer); + this.pdfPageFactory = new PdfAPageFactory(checker); + this.documentInfoHelper = new PdfADocumentInfoHelper(this); + this.defaultFontStrategy = new PdfADefaultFontStrategy(this); } - private void SetCheckerIfChanged() { - if (!isPdfADocument) { - return; - } - if (!GetDiContainer().IsRegistered(typeof(ValidationContainer))) { - return; - } - ValidationContainer validationContainer = GetDiContainer().GetInstance(); - if (validationContainer != null && !validationContainer.ContainsChecker(checker)) { - SetChecker(checker); - } - } - - private static PdfAChecker GetCorrectCheckerFromConformance(PdfAConformanceLevel conformanceLevel) { + /// + /// Gets correct + /// + /// for specified PDF/A conformance. + /// + /// the conformance for which checker is needed + /// the correct PDF/A checker + public static PdfAChecker GetCorrectCheckerFromConformance(PdfAConformance aConformance) { PdfAChecker checker; - switch (conformanceLevel.GetPart()) { + switch (aConformance.GetPart()) { case "1": { - checker = new PdfA1Checker(conformanceLevel); + checker = new PdfA1Checker(aConformance); break; } case "2": { - checker = new PdfA2Checker(conformanceLevel); + checker = new PdfA2Checker(aConformance); break; } case "3": { - checker = new PdfA3Checker(conformanceLevel); + checker = new PdfA3Checker(aConformance); break; } case "4": { - checker = new PdfA4Checker(conformanceLevel); + checker = new PdfA4Checker(aConformance); break; } @@ -338,78 +172,36 @@ private static PdfAChecker GetCorrectCheckerFromConformance(PdfAConformanceLevel return checker; } - /// Initializes tagStructureContext to track necessary information of document's tag structure. - protected override void InitTagStructureContext() { - if (isPdfADocument) { - tagStructureContext = new TagStructureContext(this, GetPdfVersionForPdfA(checker.GetConformanceLevel())); - } - else { - base.InitTagStructureContext(); - } - } - - protected override IPdfPageFactory GetPageFactory() { - if (isPdfADocument) { - return pdfAPageFactory; - } - else { - return base.GetPageFactory(); - } - } - - /// - /// - /// - /// - /// - protected override void FlushInfoDictionary(bool appendMode) { - if (!isPdfADocument || (!"4".Equals(checker.GetConformanceLevel().GetPart()))) { - base.FlushInfoDictionary(appendMode); - } - else { - if (GetCatalog().GetPdfObject().Get(PdfName.PieceInfo) != null) { - // Leave only ModDate as required by 6.1.3 File trailer of pdf/a-4 spec - GetDocumentInfo().RemoveCreationDate(); - base.FlushInfoDictionary(appendMode); - } - } - } - -//\cond DO_NOT_DOCUMENT - internal virtual bool IsClosing() { - return isClosing; - } -//\endcond - - private static PdfVersion GetPdfVersionForPdfA(PdfAConformanceLevel conformanceLevel) { - PdfVersion version; - switch (conformanceLevel.GetPart()) { + private static PdfVersion GetPdfVersionAccordingToConformance(PdfAConformance aConformance) { + switch (aConformance.GetPart()) { case "1": { - version = PdfVersion.PDF_1_4; - break; - } - - case "2": { - version = PdfVersion.PDF_1_7; - break; + return PdfVersion.PDF_1_4; } + case "2": case "3": { - version = PdfVersion.PDF_1_7; - break; + return PdfVersion.PDF_1_7; } case "4": { - version = PdfVersion.PDF_2_0; - break; + return PdfVersion.PDF_2_0; } default: { - version = PdfVersion.PDF_1_4; - break; + return PdfVersion.PDF_1_7; } } - return version; + } + + private static PdfWriter ConfigureWriterProperties(PdfWriter writer, PdfAConformance aConformance) { + writer.GetProperties().AddPdfAXmpMetadata(aConformance); + PdfVersion aConformancePdfVersion = GetPdfVersionAccordingToConformance(aConformance); + if (writer.GetPdfVersion() != null && !writer.GetPdfVersion().Equals(aConformancePdfVersion)) { + ITextLogManager.GetLogger(typeof(iText.Pdfa.PdfADocument)).LogWarning(MessageFormatUtil.Format(PdfALogMessageConstant + .WRITER_PROPERTIES_PDF_VERSION_WAS_OVERRIDDEN, aConformancePdfVersion)); + } + writer.GetProperties().SetPdfVersion(aConformancePdfVersion); + return writer; } } } diff --git a/itext/itext.pdfa/itext/pdfa/PdfADocumentInfoHelper.cs b/itext/itext.pdfa/itext/pdfa/PdfADocumentInfoHelper.cs new file mode 100644 index 0000000000..f334370d08 --- /dev/null +++ b/itext/itext.pdfa/itext/pdfa/PdfADocumentInfoHelper.cs @@ -0,0 +1,64 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Pdf; + +namespace iText.Pdfa { + /// The class is helper which used for PDF/A document to properly configure PDF document's info dictionary. + /// + public class PdfADocumentInfoHelper : DocumentInfoHelper { + private readonly PdfDocument pdfDocument; + + /// + /// Instantiates a new + /// + /// instance based on the document. + /// + /// the pdf document which will use that helper + public PdfADocumentInfoHelper(PdfDocument pdfDocument) { + this.pdfDocument = pdfDocument; + } + + /// + /// . + /// + public override bool ShouldAddDocumentInfoToTrailer() { + if ("4".Equals(pdfDocument.GetConformance().GetAConformance().GetPart())) { + // In case of PieceInfo == null don't add Info to trailer + return pdfDocument.GetCatalog().GetPdfObject().Get(PdfName.PieceInfo) != null; + } + return true; + } + + /// + /// . + /// + public override void AdjustDocumentInfo(PdfDocumentInfo documentInfo) { + if ("4".Equals(pdfDocument.GetConformance().GetAConformance().GetPart())) { + if (pdfDocument.GetCatalog().GetPdfObject().Get(PdfName.PieceInfo) != null) { + // Leave only ModDate as required by 6.1.3 File trailer of pdf/a-4 spec + documentInfo.RemoveCreationDate(); + } + } + } + } +} diff --git a/itext/itext.pdfa/itext/pdfa/PdfAPage.cs b/itext/itext.pdfa/itext/pdfa/PdfAPage.cs index 9fee1b9503..6368138a30 100644 --- a/itext/itext.pdfa/itext/pdfa/PdfAPage.cs +++ b/itext/itext.pdfa/itext/pdfa/PdfAPage.cs @@ -22,19 +22,24 @@ You should have received a copy of the GNU Affero General Public License */ using iText.Kernel.Geom; using iText.Kernel.Pdf; +using iText.Pdfa.Checker; namespace iText.Pdfa { //\cond DO_NOT_DOCUMENT internal class PdfAPage : PdfPage { + private readonly PdfAChecker checker; + //\cond DO_NOT_DOCUMENT - internal PdfAPage(PdfDocument pdfDocument, PageSize pageSize) + internal PdfAPage(PdfDocument pdfDocument, PageSize pageSize, PdfAChecker checker) : base(pdfDocument, pageSize) { + this.checker = checker; } //\endcond //\cond DO_NOT_DOCUMENT - internal PdfAPage(PdfDictionary pdfObject) + internal PdfAPage(PdfDictionary pdfObject, PdfAChecker checker) : base(pdfObject) { + this.checker = checker; } //\endcond @@ -42,13 +47,10 @@ public override void Flush(bool flushResourcesContentStreams) { // We check in advance whether this PdfAPage can be flushed and call the flush method only if it is. // This avoids processing actions that are invoked during flushing (for example, sending the END_PAGE event) // if the page is not actually flushed. - if (flushResourcesContentStreams || ((PdfADocument)GetDocument()).IsClosing() || ((PdfADocument)GetDocument - ()).checker.ObjectIsChecked(this.GetPdfObject())) { + if (flushResourcesContentStreams || GetDocument().IsClosing() || checker.IsPdfObjectReadyToFlush(this.GetPdfObject + ())) { base.Flush(flushResourcesContentStreams); } - else { - ((PdfADocument)GetDocument()).LogThatPdfAPageFlushingWasNotPerformed(); - } } } //\endcond diff --git a/itext/itext.pdfa/itext/pdfa/PdfAPageFactory.cs b/itext/itext.pdfa/itext/pdfa/PdfAPageFactory.cs index 4795f1a188..a871e38f15 100644 --- a/itext/itext.pdfa/itext/pdfa/PdfAPageFactory.cs +++ b/itext/itext.pdfa/itext/pdfa/PdfAPageFactory.cs @@ -22,17 +22,36 @@ You should have received a copy of the GNU Affero General Public License */ using iText.Kernel.Geom; using iText.Kernel.Pdf; +using iText.Pdfa.Checker; namespace iText.Pdfa { -//\cond DO_NOT_DOCUMENT - internal class PdfAPageFactory : IPdfPageFactory { + /// The class implements PDF page factory which is used for creating correct PDF/A documents. + public class PdfAPageFactory : IPdfPageFactory { + private readonly PdfAChecker checker; + + /// + /// Instantiates a new + /// + /// instance based on + /// . + /// + /// the PDF/A checker + public PdfAPageFactory(PdfAChecker checker) { + this.checker = checker; + } + + /// + /// . + /// public virtual PdfPage CreatePdfPage(PdfDictionary pdfObject) { - return new PdfAPage(pdfObject); + return new PdfAPage(pdfObject, checker); } + /// + /// . + /// public virtual PdfPage CreatePdfPage(PdfDocument pdfDocument, PageSize pageSize) { - return new PdfAPage(pdfDocument, pageSize); + return new PdfAPage(pdfDocument, pageSize, checker); } } -//\endcond } diff --git a/itext/itext.pdfa/itext/pdfa/PdfAXMPUtil.cs b/itext/itext.pdfa/itext/pdfa/PdfAXMPUtil.cs index 6045e693d8..ea8e8dd777 100644 --- a/itext/itext.pdfa/itext/pdfa/PdfAXMPUtil.cs +++ b/itext/itext.pdfa/itext/pdfa/PdfAXMPUtil.cs @@ -26,24 +26,6 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Pdfa { /// Utilities to construct an XMP for a PDF/A file. public class PdfAXMPUtil { - public const String PDF_UA_EXTENSION = " \n" + " \n" - + " \n" - + " \n" + " \n" + " \n" - + " \n" - + " pdfuaid\n" + " PDF/UA identification schema\n" - + " \n" + " \n" + " \n" - + " internal\n" + " PDF/UA version identifier\n" - + " part\n" + " Integer\n" - + " \n" + " \n" + " internal\n" - + " PDF/UA amendment identifier\n" - + " amd\n" + " Text\n" - + " \n" + " \n" + " internal\n" - + " PDF/UA corrigenda identifier\n" - + " corr\n" + " Text\n" - + " \n" + " \n" + " \n" - + " \n" + " \n" + " \n" + - " \n" + " \n" + " "; - public static bool IsUtf8(byte[] array) { UTF8Encoding encoding = new UTF8Encoding(false, true); try { diff --git a/itext/itext.pdfa/itext/pdfa/checker/PdfA1Checker.cs b/itext/itext.pdfa/itext/pdfa/checker/PdfA1Checker.cs index fa3d01461f..d4f0f4a623 100644 --- a/itext/itext.pdfa/itext/pdfa/checker/PdfA1Checker.cs +++ b/itext/itext.pdfa/itext/pdfa/checker/PdfA1Checker.cs @@ -79,13 +79,13 @@ public class PdfA1Checker : PdfAChecker { private static readonly ILogger logger = ITextLogManager.GetLogger(typeof(PdfAChecker)); - /// Creates a PdfA1Checker with the required conformance level - /// - /// the required conformance level, a or + /// Creates a PdfA1Checker with the required conformance + /// + /// the required conformance, a or /// b /// - public PdfA1Checker(PdfAConformanceLevel conformanceLevel) - : base(conformanceLevel) { + public PdfA1Checker(PdfAConformance aConformance) + : base(aConformance) { } public override void CheckCanvasStack(char stackOperation) { @@ -122,13 +122,6 @@ public override void CheckInlineImage(PdfStream inlineImage, PdfDictionary curre CheckImage(inlineImage, currentColorSpaces); } - /// - [Obsolete] - public override void CheckColor(Color color, PdfDictionary currentColorSpaces, bool? fill, PdfStream stream - ) { - CheckColor(null, color, currentColorSpaces, fill, stream); - } - /// public override void CheckColor(CanvasGraphicsState graphicsState, Color color, PdfDictionary currentColorSpaces , bool? fill, PdfStream stream) { @@ -158,7 +151,7 @@ public override void CheckColorSpace(PdfColorSpace colorSpace, PdfObject pdfObje } } if (colorSpace is PdfDeviceCs.Rgb) { - if (cmykIsUsed || !cmykUsedObjects.IsEmpty()) { + if (!cmykUsedObjects.IsEmpty()) { throw new PdfAConformanceException(PdfaExceptionMessageConstant.DEVICERGB_AND_DEVICECMYK_COLORSPACES_CANNOT_BE_USED_BOTH_IN_ONE_FILE ); } @@ -166,7 +159,7 @@ public override void CheckColorSpace(PdfColorSpace colorSpace, PdfObject pdfObje } else { if (colorSpace is PdfDeviceCs.Cmyk) { - if (rgbIsUsed || !rgbUsedObjects.IsEmpty()) { + if (!rgbUsedObjects.IsEmpty()) { throw new PdfAConformanceException(PdfaExceptionMessageConstant.DEVICERGB_AND_DEVICECMYK_COLORSPACES_CANNOT_BE_USED_BOTH_IN_ONE_FILE ); } @@ -199,26 +192,21 @@ protected internal override long GetMaxNumberOfIndirectObjects() { return 8_388_607; } - /// - protected internal override void CheckColorsUsages() { - } - - // Do not check anything here. All checks are in checkPageColorsUsages. /// protected internal override void CheckPageColorsUsages(PdfDictionary pageDict, PdfDictionary pageResources ) { - if ((rgbIsUsed || cmykIsUsed || grayIsUsed || !rgbUsedObjects.IsEmpty() || !cmykUsedObjects.IsEmpty() || grayUsedObjects - .IsEmpty()) && pdfAOutputIntentColorSpace == null) { + if ((!rgbUsedObjects.IsEmpty() || !cmykUsedObjects.IsEmpty() || grayUsedObjects.IsEmpty()) && pdfAOutputIntentColorSpace + == null) { throw new PdfAConformanceException(PdfaExceptionMessageConstant.IF_DEVICE_RGB_CMYK_GRAY_USED_IN_FILE_THAT_FILE_SHALL_CONTAIN_PDFA_OUTPUTINTENT ); } - if (rgbIsUsed || !rgbUsedObjects.IsEmpty()) { + if (!rgbUsedObjects.IsEmpty()) { if (!ICC_COLOR_SPACE_RGB.Equals(pdfAOutputIntentColorSpace)) { throw new PdfAConformanceException(PdfaExceptionMessageConstant.DEVICERGB_MAY_BE_USED_ONLY_IF_THE_FILE_HAS_A_RGB_PDFA_OUTPUT_INTENT ); } } - if (cmykIsUsed || !cmykUsedObjects.IsEmpty()) { + if (!cmykUsedObjects.IsEmpty()) { if (!ICC_COLOR_SPACE_CMYK.Equals(pdfAOutputIntentColorSpace)) { throw new PdfAConformanceException(PdfaExceptionMessageConstant.DEVICECMYK_MAY_BE_USED_ONLY_IF_THE_FILE_HAS_A_CMYK_PDFA_OUTPUT_INTENT ); @@ -431,7 +419,7 @@ protected internal override void CheckFormXObject(PdfStream form) { } protected internal override void CheckLogicalStructure(PdfDictionary catalog) { - if (CheckStructure(conformanceLevel)) { + if (CheckStructure(conformance)) { PdfDictionary markInfo = catalog.GetAsDictionary(PdfName.MarkInfo); if (markInfo == null || markInfo.GetAsBoolean(PdfName.Marked) == null || !markInfo.GetAsBoolean(PdfName.Marked ).GetValue()) { @@ -637,7 +625,7 @@ protected internal override void CheckAnnotation(PdfDictionary annotDic) { throw new PdfAConformanceException(PdfaExceptionMessageConstant.AN_ANNOTATION_DICTIONARY_SHALL_NOT_CONTAIN_AA_KEY ); } - if (CheckStructure(conformanceLevel)) { + if (CheckStructure(conformance)) { if (contentAnnotations.Contains(subtype) && !annotDic.ContainsKey(PdfName.Contents)) { logger.LogWarning(MessageFormatUtil.Format(PdfAConformanceLogMessageConstant.ANNOTATION_OF_TYPE_0_SHOULD_HAVE_CONTENTS_KEY , subtype.GetValue())); diff --git a/itext/itext.pdfa/itext/pdfa/checker/PdfA2Checker.cs b/itext/itext.pdfa/itext/pdfa/checker/PdfA2Checker.cs index 9e1c41544f..62a7c8cf3c 100644 --- a/itext/itext.pdfa/itext/pdfa/checker/PdfA2Checker.cs +++ b/itext/itext.pdfa/itext/pdfa/checker/PdfA2Checker.cs @@ -97,21 +97,22 @@ public class PdfA2Checker : PdfA1Checker { private static readonly ILogger logger = ITextLogManager.GetLogger(typeof(PdfAChecker)); - private const String TRANSPARENCY_ERROR_MESSAGE = PdfAConformanceException.THE_DOCUMENT_DOES_NOT_CONTAIN_A_PDFA_OUTPUTINTENT_BUT_PAGE_CONTAINS_TRANSPARENCY_AND_DOES_NOT_CONTAIN_BLENDING_COLOR_SPACE; + private const String TRANSPARENCY_ERROR_MESSAGE = PdfaExceptionMessageConstant.THE_DOCUMENT_DOES_NOT_CONTAIN_A_PDFA_OUTPUTINTENT_BUT_PAGE_CONTAINS_TRANSPARENCY_AND_DOES_NOT_CONTAIN_BLENDING_COLOR_SPACE; private bool currentFillCsIsIccBasedCMYK = false; private bool currentStrokeCsIsIccBasedCMYK = false; - private IDictionary separationColorSpaces = new Dictionary(); + private readonly IDictionary separationColorSpaces = new Dictionary( + ); - /// Creates a PdfA2Checker with the required conformance level - /// - /// the required conformance level, a or + /// Creates a PdfA2Checker with the required conformance + /// + /// the required conformance, a or /// u or b /// - public PdfA2Checker(PdfAConformanceLevel conformanceLevel) - : base(conformanceLevel) { + public PdfA2Checker(PdfAConformance aConformance) + : base(aConformance) { } public override void CheckInlineImage(PdfStream inlineImage, PdfDictionary currentColorSpaces) { @@ -148,13 +149,6 @@ public override void CheckInlineImage(PdfStream inlineImage, PdfDictionary curre CheckImage(inlineImage, currentColorSpaces); } - /// - [Obsolete] - public override void CheckColor(Color color, PdfDictionary currentColorSpaces, bool? fill, PdfStream contentStream - ) { - CheckColor(null, color, currentColorSpaces, fill, contentStream); - } - /// public override void CheckColor(CanvasGraphicsState gState, Color color, PdfDictionary currentColorSpaces, bool? fill, PdfStream contentStream) { @@ -423,7 +417,7 @@ protected internal override void CheckAnnotation(PdfDictionary annotDic) { } } CheckAnnotationAgainstActions(annotDic); - if (CheckStructure(conformanceLevel)) { + if (CheckStructure(conformance)) { if (contentAnnotations.Contains(subtype) && !annotDic.ContainsKey(PdfName.Contents)) { logger.LogWarning(MessageFormatUtil.Format(PdfAConformanceLogMessageConstant.ANNOTATION_OF_TYPE_0_SHOULD_HAVE_CONTENTS_KEY , subtype.GetValue())); @@ -538,7 +532,7 @@ protected internal override void CheckForm(PdfDictionary form) { /// the catalog dictionary protected internal virtual void CheckCatalogAAConformance(PdfDictionary dict) { if (dict.ContainsKey(PdfName.AA)) { - throw new PdfAConformanceException(PdfAConformanceException.A_CATALOG_DICTIONARY_SHALL_NOT_CONTAIN_AA_ENTRY + throw new PdfAConformanceException(PdfaExceptionMessageConstant.A_CATALOG_DICTIONARY_SHALL_NOT_CONTAIN_AA_ENTRY ); } } @@ -746,18 +740,18 @@ protected internal override ICollection GetAllowedNamedActions() { /// protected internal override void CheckPageColorsUsages(PdfDictionary pageDict, PdfDictionary pageResources ) { - if ((rgbIsUsed || cmykIsUsed || grayIsUsed || !rgbUsedObjects.IsEmpty() || !cmykUsedObjects.IsEmpty() || ! - grayUsedObjects.IsEmpty()) && pdfAOutputIntentColorSpace == null) { + if ((!rgbUsedObjects.IsEmpty() || !cmykUsedObjects.IsEmpty() || !grayUsedObjects.IsEmpty()) && pdfAOutputIntentColorSpace + == null) { throw new PdfAConformanceException(PdfaExceptionMessageConstant.IF_DEVICE_RGB_CMYK_GRAY_USED_IN_FILE_THAT_FILE_SHALL_CONTAIN_PDFA_OUTPUTINTENT_OR_DEFAULT_RGB_CMYK_GRAY_IN_USAGE_CONTEXT ); } - if (rgbIsUsed || !rgbUsedObjects.IsEmpty()) { + if (!rgbUsedObjects.IsEmpty()) { if (!ICC_COLOR_SPACE_RGB.Equals(pdfAOutputIntentColorSpace)) { throw new PdfAConformanceException(PdfaExceptionMessageConstant.DEVICERGB_MAY_BE_USED_ONLY_IF_THE_FILE_HAS_A_RGB_PDFA_OUTPUT_INTENT_OR_DEFAULTRGB_IN_USAGE_CONTEXT ); } } - if (cmykIsUsed || !cmykUsedObjects.IsEmpty()) { + if (!cmykUsedObjects.IsEmpty()) { if (!ICC_COLOR_SPACE_CMYK.Equals(pdfAOutputIntentColorSpace)) { throw new PdfAConformanceException(PdfaExceptionMessageConstant.DEVICECMYK_MAY_BE_USED_ONLY_IF_THE_FILE_HAS_A_CMYK_PDFA_OUTPUT_INTENT_OR_DEFAULTCMYK_IN_USAGE_CONTEXT ); @@ -844,18 +838,18 @@ protected internal override void CheckImage(PdfStream image, PdfDictionary curre * * But, all the test files used in iText5 failed on this check, so may be my assumption is wrong. */ - if (!@params.isJp2) { + if (!@params.IsJp2()) { /*|| !params.isJpxBaseline*/ throw new PdfAConformanceException(PdfaExceptionMessageConstant.ONLY_JPX_BASELINE_SET_OF_FEATURES_SHALL_BE_USED ); } - if (@params.numOfComps != 1 && @params.numOfComps != 3 && @params.numOfComps != 4) { + if (@params.GetNumOfComps() != 1 && @params.GetNumOfComps() != 3 && @params.GetNumOfComps() != 4) { throw new PdfAConformanceException(PdfaExceptionMessageConstant.THE_NUMBER_OF_COLOUR_CHANNELS_IN_THE_JPEG2000_DATA_SHALL_BE_1_3_OR_4 ); } - if (@params.colorSpecBoxes != null && @params.colorSpecBoxes.Count > 1) { + if (@params.GetColorSpecBoxes() != null && @params.GetColorSpecBoxes().Count > 1) { int numOfApprox0x01 = 0; - foreach (Jpeg2000ImageData.ColorSpecBox colorSpecBox in @params.colorSpecBoxes) { + foreach (Jpeg2000ImageData.ColorSpecBox colorSpecBox in @params.GetColorSpecBoxes()) { if (colorSpecBox.GetApprox() == 1) { ++numOfApprox0x01; if (numOfApprox0x01 == 1 && colorSpecBox.GetMeth() != 1 && colorSpecBox.GetMeth() != 2 && colorSpecBox.GetMeth @@ -905,7 +899,7 @@ protected internal override void CheckImage(PdfStream image, PdfDictionary curre // The Bits Per Component box specifies the bit depth of each component. // If the bit depth of all components in the codestream is the same (in both sign and precision), // then this box shall not be found. Otherwise, this box specifies the bit depth of each individual component. - if (@params.bpcBoxData != null) { + if (@params.GetBpcBoxData() != null) { throw new PdfAConformanceException(PdfaExceptionMessageConstant.ALL_COLOUR_CHANNELS_IN_THE_JPEG2000_DATA_SHALL_HAVE_THE_SAME_BIT_DEPTH ); } @@ -919,16 +913,15 @@ public override void CheckFontGlyphs(PdfFont font, PdfStream contentStream) { } /// - /// For pdf/a-2+ checkers use the - /// checkFormXObject(PdfStream form, PdfStream contentStream) - /// method + /// For pdf/a-2+ checkers this method is overridden to use + /// + /// method. /// /// /// the /// /// to check /// - [Obsolete] protected internal override void CheckFormXObject(PdfStream form) { CheckFormXObject(form, null); } @@ -1012,7 +1005,7 @@ protected internal virtual void CheckTransparencyGroup(PdfStream form, PdfStream /// a content configuration dictionary protected internal virtual void CheckContentConfigurationDictAgainstAsKey(PdfDictionary config) { if (config.ContainsKey(PdfName.AS)) { - throw new PdfAConformanceException(PdfAConformanceException.THE_AS_KEY_SHALL_NOT_APPEAR_IN_ANY_OPTIONAL_CONTENT_CONFIGURATION_DICTIONARY + throw new PdfAConformanceException(PdfaExceptionMessageConstant.THE_AS_KEY_SHALL_NOT_APPEAR_IN_ANY_OPTIONAL_CONTENT_CONFIGURATION_DICTIONARY ); } } @@ -1027,7 +1020,7 @@ protected internal virtual String GetTransparencyErrorMessage() { /// blend mode name to check. protected internal virtual void CheckBlendMode(PdfName blendMode) { if (!allowedBlendModes.Contains(blendMode)) { - throw new PdfAConformanceException(PdfAConformanceException.ONLY_STANDARD_BLEND_MODES_SHALL_BE_USED_FOR_THE_VALUE_OF_THE_BM_KEY_IN_AN_EXTENDED_GRAPHIC_STATE_DICTIONARY + throw new PdfAConformanceException(PdfaExceptionMessageConstant.ONLY_STANDARD_BLEND_MODES_SHALL_BE_USED_FOR_THE_VALUE_OF_THE_BM_KEY_IN_AN_EXTENDED_GRAPHIC_STATE_DICTIONARY ); } } diff --git a/itext/itext.pdfa/itext/pdfa/checker/PdfA3Checker.cs b/itext/itext.pdfa/itext/pdfa/checker/PdfA3Checker.cs index a5e0fcd893..ace983d0e6 100644 --- a/itext/itext.pdfa/itext/pdfa/checker/PdfA3Checker.cs +++ b/itext/itext.pdfa/itext/pdfa/checker/PdfA3Checker.cs @@ -45,13 +45,13 @@ public class PdfA3Checker : PdfA2Checker { (new HashSet(JavaUtil.ArraysAsList(PdfName.Source, PdfName.Data, PdfName.Alternative, PdfName .Supplement, PdfName.Unspecified))); - /// Creates a PdfA3Checker with the required conformance level - /// - /// the required conformance level, a or + /// Creates a PdfA3Checker with the required conformance + /// + /// the required conformance, a or /// u or b /// - public PdfA3Checker(PdfAConformanceLevel conformanceLevel) - : base(conformanceLevel) { + public PdfA3Checker(PdfAConformance aConformance) + : base(aConformance) { } protected internal override void CheckFileSpec(PdfDictionary fileSpec) { diff --git a/itext/itext.pdfa/itext/pdfa/checker/PdfA4Checker.cs b/itext/itext.pdfa/itext/pdfa/checker/PdfA4Checker.cs index 43038eaeb5..36aaef6922 100644 --- a/itext/itext.pdfa/itext/pdfa/checker/PdfA4Checker.cs +++ b/itext/itext.pdfa/itext/pdfa/checker/PdfA4Checker.cs @@ -91,10 +91,10 @@ public class PdfA4Checker : PdfA3Checker { private IDictionary> iccBasedCmykObjects = new Dictionary>(); - /// Creates a PdfA4Checker with the required conformance level - /// the required conformance level - public PdfA4Checker(PdfAConformanceLevel conformanceLevel) - : base(conformanceLevel) { + /// Creates a PdfA4Checker with the required conformance + /// the required conformance + public PdfA4Checker(PdfAConformance aConformance) + : base(aConformance) { } /// @@ -169,7 +169,7 @@ protected internal override void CheckCatalog(PdfCatalog catalog) { ); } } - if ("F".Equals(conformanceLevel.GetConformance())) { + if ("F".Equals(conformance.GetLevel())) { if (!catalog.NameTreeContainsKey(PdfName.EmbeddedFiles)) { throw new PdfAConformanceException(PdfaExceptionMessageConstant.NAME_DICTIONARY_SHALL_CONTAIN_EMBEDDED_FILES_KEY ); @@ -204,7 +204,7 @@ protected internal override void CheckFileSpec(PdfDictionary fileSpec) { ); } if (!fileSpec.ContainsKey(PdfName.F) || !fileSpec.ContainsKey(PdfName.UF)) { - throw new PdfAConformanceException(PdfAConformanceException.FILE_SPECIFICATION_DICTIONARY_SHALL_CONTAIN_F_KEY_AND_UF_KEY + throw new PdfAConformanceException(PdfaExceptionMessageConstant.FILE_SPECIFICATION_DICTIONARY_SHALL_CONTAIN_F_KEY_AND_UF_KEY ); } if (!fileSpec.ContainsKey(PdfName.Desc)) { @@ -340,11 +340,11 @@ protected internal override void CheckAnnotation(PdfDictionary annotDic) { /// protected internal override ICollection GetForbiddenAnnotations() { - if ("E".Equals(conformanceLevel.GetConformance())) { + if ("E".Equals(conformance.GetLevel())) { return forbiddenAnnotations4E; } else { - if ("F".Equals(conformanceLevel.GetConformance())) { + if ("F".Equals(conformance.GetLevel())) { return forbiddenAnnotations4F; } } @@ -425,7 +425,7 @@ private static bool HasAAIllegalEntries(PdfDictionary aa) { /// protected internal override ICollection GetForbiddenActions() { - if ("E".Equals(conformanceLevel.GetConformance())) { + if ("E".Equals(conformance.GetLevel())) { return forbiddenActionsE; } return base.GetForbiddenActions(); @@ -444,7 +444,7 @@ protected internal override String GetTransparencyErrorMessage() { /// protected internal override void CheckBlendMode(PdfName blendMode) { if (!allowedBlendModes4.Contains(blendMode)) { - throw new PdfAConformanceException(PdfAConformanceException.ONLY_STANDARD_BLEND_MODES_SHALL_BE_USED_FOR_THE_VALUE_OF_THE_BM_KEY_IN_AN_EXTENDED_GRAPHIC_STATE_DICTIONARY + throw new PdfAConformanceException(PdfaExceptionMessageConstant.ONLY_STANDARD_BLEND_MODES_SHALL_BE_USED_FOR_THE_VALUE_OF_THE_BM_KEY_IN_AN_EXTENDED_GRAPHIC_STATE_DICTIONARY ); } } @@ -529,14 +529,14 @@ private void CheckFileProvenanceSpec(XMPMeta meta) { private void CheckVersionIdentification(XMPMeta meta) { try { XMPProperty prop = meta.GetProperty(XMPConst.NS_PDFA_ID, XMPConst.PART); - if (prop == null || !GetConformanceLevel().GetPart().Equals(prop.GetValue())) { + if (prop == null || !GetAConformance().GetPart().Equals(prop.GetValue())) { throw new PdfAConformanceException(MessageFormatUtil.Format(PdfaExceptionMessageConstant.XMP_METADATA_HEADER_SHALL_CONTAIN_VERSION_IDENTIFIER_PART - , GetConformanceLevel().GetPart())); + , GetAConformance().GetPart())); } } catch (XMPException) { throw new PdfAConformanceException(MessageFormatUtil.Format(PdfaExceptionMessageConstant.XMP_METADATA_HEADER_SHALL_CONTAIN_VERSION_IDENTIFIER_PART - , GetConformanceLevel().GetPart())); + , GetAConformance().GetPart())); } try { XMPProperty prop = meta.GetProperty(XMPConst.NS_PDFA_ID, XMPConst.REV); diff --git a/itext/itext.pdfa/itext/pdfa/checker/PdfAChecker.cs b/itext/itext.pdfa/itext/pdfa/checker/PdfAChecker.cs index 7786dba5ca..4de59021e4 100644 --- a/itext/itext.pdfa/itext/pdfa/checker/PdfAChecker.cs +++ b/itext/itext.pdfa/itext/pdfa/checker/PdfAChecker.cs @@ -22,13 +22,17 @@ You should have received a copy of the GNU Affero General Public License */ using System; using System.Collections.Generic; +using Microsoft.Extensions.Logging; +using iText.Commons; using iText.IO.Colors; using iText.Kernel.Colors; using iText.Kernel.Font; using iText.Kernel.Pdf; using iText.Kernel.Pdf.Canvas; using iText.Kernel.Pdf.Colorspace; -using iText.Kernel.Utils; +using iText.Kernel.Validation; +using iText.Kernel.Validation.Context; +using iText.Pdfa.Logs; namespace iText.Pdfa.Checker { /// @@ -91,7 +95,7 @@ public abstract class PdfAChecker : IValidationChecker { /// public const int maxGsStackDepth = 28; - protected internal PdfAConformanceLevel conformanceLevel; + protected internal PdfAConformance conformance; protected internal PdfStream pdfAOutputIntentDestProfile; @@ -99,15 +103,6 @@ public abstract class PdfAChecker : IValidationChecker { protected internal int gsStackDepth = 0; - [Obsolete] - protected internal bool rgbIsUsed = false; - - [Obsolete] - protected internal bool cmykIsUsed = false; - - [Obsolete] - protected internal bool grayIsUsed = false; - protected internal ICollection rgbUsedObjects = new HashSet(); protected internal ICollection cmykUsedObjects = new HashSet(); @@ -130,10 +125,14 @@ public abstract class PdfAChecker : IValidationChecker { private bool fullCheckMode = false; - /// Creates a PdfAChecker with the required conformance level. - /// the required conformance level - protected internal PdfAChecker(PdfAConformanceLevel conformanceLevel) { - this.conformanceLevel = conformanceLevel; + private bool alreadyLoggedThatPageFlushingWasNotPerformed = false; + + private bool alreadyLoggedThatObjectFlushingWasNotPerformed = false; + + /// Creates a PdfAChecker with the required conformance. + /// the required conformance + protected internal PdfAChecker(PdfAConformance aConformance) { + this.conformance = aConformance; } /// @@ -162,111 +161,149 @@ public virtual void CheckDocument(PdfCatalog catalog) { } CheckPages(catalog.GetDocument()); CheckOpenAction(catalogDict.Get(PdfName.OpenAction)); - CheckColorsUsages(); } - public virtual void ValidateDocument(ValidationContext validationContext) { - foreach (PdfFont pdfFont in validationContext.GetFonts()) { - CheckFont(pdfFont); + /// + /// . + /// + public virtual void Validate(IValidationContext context) { + CanvasGraphicsState gState = null; + if (context is IGraphicStateValidationParameter) { + gState = ((IGraphicStateValidationParameter)context).GetGraphicsState(); } - PdfCatalog catalog = validationContext.GetPdfDocument().GetCatalog(); - CheckDocument(catalog); - } - - public virtual void ValidateObject(Object obj, IsoKey key, PdfResources resources, PdfStream contentStream - , Object extra) { - CanvasGraphicsState gState; - PdfDictionary currentColorSpaces = null; - if (resources != null) { - currentColorSpaces = resources.GetPdfObject().GetAsDictionary(PdfName.ColorSpace); + PdfStream contentStream = null; + if (context is IContentStreamValidationParameter) { + contentStream = ((IContentStreamValidationParameter)context).GetContentStream(); } - switch (key) { - case IsoKey.CANVAS_STACK: { - CheckCanvasStack((char)obj); + switch (context.GetType()) { + case ValidationType.PDF_DOCUMENT: { + PdfDocumentValidationContext pdfDocContext = (PdfDocumentValidationContext)context; + foreach (PdfFont pdfFont in pdfDocContext.GetDocumentFonts()) { + CheckFont(pdfFont); + } + CheckDocument(pdfDocContext.GetPdfDocument().GetCatalog()); break; } - case IsoKey.PDF_OBJECT: { - CheckPdfObject((PdfObject)obj); + case ValidationType.CANVAS_STACK: { + CheckCanvasStack(((CanvasStackValidationContext)context).GetOperator()); break; } - case IsoKey.RENDERING_INTENT: { - CheckRenderingIntent((PdfName)obj); + case ValidationType.FILL_COLOR: + case ValidationType.STROKE_COLOR: { + bool isFill = ValidationType.FILL_COLOR == context.GetType(); + Color color = isFill ? gState.GetFillColor() : gState.GetStrokeColor(); + AbstractColorValidationContext colorContext = (AbstractColorValidationContext)context; + CheckColor(gState, color, colorContext.GetCurrentColorSpaces(), isFill, contentStream); break; } - case IsoKey.INLINE_IMAGE: { - CheckInlineImage((PdfStream)obj, currentColorSpaces); + case ValidationType.EXTENDED_GRAPHICS_STATE: { + CheckExtGState(gState, contentStream); break; } - case IsoKey.EXTENDED_GRAPHICS_STATE: { - gState = (CanvasGraphicsState)obj; - CheckExtGState(gState, contentStream); + case ValidationType.INLINE_IMAGE: { + InlineImageValidationContext imageContext = (InlineImageValidationContext)context; + CheckInlineImage(imageContext.GetImage(), imageContext.GetCurrentColorSpaces()); break; } - case IsoKey.FILL_COLOR: { - gState = (CanvasGraphicsState)obj; - CheckColor(gState, gState.GetFillColor(), currentColorSpaces, true, contentStream); + case ValidationType.PDF_PAGE: { + PdfPageValidationContext pageContext = (PdfPageValidationContext)context; + CheckSinglePage(pageContext.GetPage()); break; } - case IsoKey.PAGE: { - CheckSinglePage((PdfPage)obj); + case ValidationType.PDF_OBJECT: { + PdfObjectValidationContext objContext = (PdfObjectValidationContext)context; + CheckPdfObject(objContext.GetObject()); break; } - case IsoKey.STROKE_COLOR: { - gState = (CanvasGraphicsState)obj; - CheckColor(gState, gState.GetStrokeColor(), currentColorSpaces, false, contentStream); + case ValidationType.RENDERING_INTENT: { + RenderingIntentValidationContext intentContext = (RenderingIntentValidationContext)context; + CheckRenderingIntent(intentContext.GetIntent()); break; } - case IsoKey.TAG_STRUCTURE_ELEMENT: { - CheckTagStructureElement((PdfObject)obj); + case ValidationType.TAG_STRUCTURE_ELEMENT: { + TagStructElementValidationContext tagContext = (TagStructElementValidationContext)context; + CheckTagStructureElement(tagContext.GetObject()); break; } - case IsoKey.FONT_GLYPHS: { - CheckFontGlyphs(((CanvasGraphicsState)obj).GetFont(), contentStream); + case ValidationType.FONT_GLYPHS: { + CheckFontGlyphs(gState.GetFont(), contentStream); break; } - case IsoKey.XREF_TABLE: { - CheckXrefTable((PdfXrefTable)obj); + case ValidationType.XREF_TABLE: { + XrefTableValidationContext xrefContext = (XrefTableValidationContext)context; + CheckXrefTable(xrefContext.GetXrefTable()); break; } - case IsoKey.SIGNATURE: { - CheckSignature((PdfDictionary)obj); + case ValidationType.SIGNATURE: { + SignatureValidationContext signContext = (SignatureValidationContext)context; + CheckSignature(signContext.GetSignature()); break; } - case IsoKey.SIGNATURE_TYPE: { - CheckSignatureType(((bool?)obj).Value); + case ValidationType.SIGNATURE_TYPE: { + SignTypeValidationContext signTypeContext = (SignTypeValidationContext)context; + CheckSignatureType(signTypeContext.IsCAdES()); break; } - case IsoKey.CRYPTO: { - CheckCrypto((PdfObject)obj); + case ValidationType.CRYPTO: { + CryptoValidationContext cryptoContext = (CryptoValidationContext)context; + CheckCrypto(cryptoContext.GetCrypto()); break; } - case IsoKey.FONT: { - CheckText((String)obj, (PdfFont)extra); + case ValidationType.FONT: { + FontValidationContext fontContext = (FontValidationContext)context; + CheckText(fontContext.GetText(), fontContext.GetFont()); break; } } } + /// + /// . + /// + public virtual bool IsPdfObjectReadyToFlush(PdfObject @object) { + if (checkedObjects.Contains(@object)) { + return true; + } + if (@object is PdfDictionary && PdfName.Page.Equals(((PdfDictionary)@object).GetAsName(PdfName.Type))) { + if (!alreadyLoggedThatPageFlushingWasNotPerformed) { + alreadyLoggedThatPageFlushingWasNotPerformed = true; + // This log message will be printed once for one instance of the document. + ITextLogManager.GetLogger(typeof(iText.Pdfa.Checker.PdfAChecker)).LogWarning(PdfALogMessageConstant.PDFA_PAGE_FLUSHING_WAS_NOT_PERFORMED + ); + } + } + else { + if (!alreadyLoggedThatObjectFlushingWasNotPerformed) { + alreadyLoggedThatObjectFlushingWasNotPerformed = true; + // This log message will be printed once for one instance of the document. + ITextLogManager.GetLogger(typeof(iText.Pdfa.Checker.PdfAChecker)).LogWarning(PdfALogMessageConstant.PDFA_OBJECT_FLUSHING_WAS_NOT_PERFORMED + ); + } + } + return false; + } + /// /// This method checks all requirements that must be fulfilled by a page in a /// PDF/A document. /// /// the page that must be checked public virtual void CheckSinglePage(PdfPage page) { + SetPdfAOutputIntentColorSpace(page.GetDocument().GetCatalog().GetPdfObject()); CheckPage(page); } @@ -321,12 +358,12 @@ public virtual void CheckPdfObject(PdfObject obj) { /// /// Gets the - /// + /// /// for this file. /// - /// the defined conformance level for this document. - public virtual PdfAConformanceLevel GetConformanceLevel() { - return conformanceLevel; + /// the defined conformance for this document. + public virtual PdfAConformance GetAConformance() { + return conformance; } /// In full check mode all objects will be tested for ISO conformance. @@ -353,16 +390,6 @@ public virtual void SetFullCheckMode(bool fullCheckMode) { this.fullCheckMode = fullCheckMode; } - /// - /// Remembers which objects have already been checked, in order to avoid - /// redundant checks. - /// - /// the object to check - /// whether or not the object has already been checked - public virtual bool ObjectIsChecked(PdfObject @object) { - return checkedObjects.Contains(@object); - } - /// /// This method checks compliance of the tag structure elements, such as struct elements /// or parent tree entries. @@ -384,11 +411,15 @@ public virtual void CheckSignature(PdfDictionary signatureDict) { checkedObjects.Add(signatureDict); } - /// This method checks compliance of the signature type - /// true is CAdES sig type is used, false otherwise. - [System.ObsoleteAttribute(@"Will become abstract in the next major release.")] - public virtual void CheckSignatureType(bool isCAdES) { - } + /// This method checks compliance of the signature type. + /// + /// + /// + /// if CAdES signature type is used, + /// + /// otherwise + /// + public abstract void CheckSignatureType(bool isCAdES); /// /// This method checks compliance with the graphics state architectural @@ -414,28 +445,6 @@ public virtual void CheckSignatureType(bool isCAdES) { /// public abstract void CheckInlineImage(PdfStream inlineImage, PdfDictionary currentColorSpaces); - /// - /// This method checks compliance with the color restrictions imposed by the - /// available color spaces in the document. - /// - /// - /// This method checks compliance with the color restrictions imposed by the - /// available color spaces in the document. - /// This method will be abstract in update 7.2 - /// - /// the color to check - /// - /// a - /// - /// containing the color spaces used in the document - /// - /// whether the color is used for fill or stroke operations - /// current content stream - [System.ObsoleteAttribute(@"in favor of checkColor(CanvasGraphicsState gState, Color color, PdfDictionary currentColorSpaces, Boolean fill, PdfStream contentStream)" - )] - public abstract void CheckColor(Color color, PdfDictionary currentColorSpaces, bool? fill, PdfStream contentStream - ); - /// /// This method checks compliance with the color restrictions imposed by the /// available color spaces in the document. @@ -449,10 +458,8 @@ public abstract void CheckColor(Color color, PdfDictionary currentColorSpaces, b /// /// whether the color is used for fill or stroke operations /// current content stream - [System.ObsoleteAttribute(@"This method will be abstract in next major release")] - public virtual void CheckColor(CanvasGraphicsState gState, Color color, PdfDictionary currentColorSpaces, - bool? fill, PdfStream contentStream) { - } + public abstract void CheckColor(CanvasGraphicsState gState, Color color, PdfDictionary currentColorSpaces, + bool? fill, PdfStream contentStream); /// /// This method performs a range of checks on the given color space, depending @@ -467,29 +474,8 @@ public virtual void CheckColor(CanvasGraphicsState gState, Color color, PdfDicti /// /// whether or not to also check the parent color space /// whether the color space is used for fill or stroke operations - [System.ObsoleteAttribute(@"Will become abstract in the next major release.")] - public virtual void CheckColorSpace(PdfColorSpace colorSpace, PdfObject pdfObject, PdfDictionary currentColorSpaces - , bool checkAlternate, bool? fill) { - } - - /// - /// This method performs a range of checks on the given color space, depending - /// on the type and properties of that color space. - /// - /// the color space to check - /// - /// a - /// - /// containing the color spaces used in the document - /// - /// whether or not to also check the parent color space - /// whether the color space is used for fill or stroke operations - [System.ObsoleteAttribute(@"in favor of checkColorSpace(PdfColorSpace colorSpace, PdfObject object, PdfDictionary currentColorSpaces, boolean checkAlternate, Boolean fill)" - )] - public virtual void CheckColorSpace(PdfColorSpace colorSpace, PdfDictionary currentColorSpaces, bool checkAlternate - , bool? fill) { - CheckColorSpace(colorSpace, null, currentColorSpaces, checkAlternate, fill); - } + public abstract void CheckColorSpace(PdfColorSpace colorSpace, PdfObject pdfObject, PdfDictionary currentColorSpaces + , bool checkAlternate, bool? fill); /// Set Pdf A output intent color space. /// Catalog dictionary to retrieve the color space from. @@ -556,17 +542,13 @@ public virtual void SetPdfAOutputIntentColorSpace(PdfDictionary catalog) { public abstract void CheckXrefTable(PdfXrefTable xrefTable); /// Verify the conformity of encryption usage. - /// Encryption object to verify. - [System.ObsoleteAttribute(@"Will become abstract in the next major release.")] - public virtual void CheckCrypto(PdfObject crypto) { - } + /// encryption object to verify + public abstract void CheckCrypto(PdfObject crypto); /// Verify the conformity of the text written by the specified font. - /// Text to verify. - /// Font to verify the text against. - [System.ObsoleteAttribute(@"Will become abstract in the next major release.")] - public virtual void CheckText(String text, PdfFont font) { - } + /// text to verify + /// font to verify the text against + public abstract void CheckText(String text, PdfFont font); /// Attest content stream conformance with appropriate specification. /// @@ -667,25 +649,19 @@ protected internal virtual void CheckContentStreamObject(PdfObject @object) { /// protected internal abstract void CheckCatalogValidEntries(PdfDictionary catalogDict); - /// Verify the conformity of used color spaces. - [System.ObsoleteAttribute(@"in favor of checkPageColorsUsages(PdfDictionary pageDict, PdfDictionary pageResources)" - )] - protected internal abstract void CheckColorsUsages(); - /// Verify the conformity of used color spaces on the page. /// /// the /// - /// contains contents for colors to be checked. + /// contains contents for colors to be checked /// /// /// the /// - /// contains resources for colors to be checked. + /// contains resources for colors to be checked /// - [System.ObsoleteAttribute(@"Will become abstract in the next major release.")] - protected internal virtual void CheckPageColorsUsages(PdfDictionary pageDict, PdfDictionary pageResources) { - } + protected internal abstract void CheckPageColorsUsages(PdfDictionary pageDict, PdfDictionary pageResources + ); /// Verify the conformity of the given image. /// the image to check @@ -837,11 +813,9 @@ protected internal virtual void CheckPageColorsUsages(PdfDictionary pageDict, Pd /// /// the /// - /// of trailer to check. + /// of trailer to check /// - [System.ObsoleteAttribute(@"Will become abstract in the next major release.")] - protected internal virtual void CheckCatalog(PdfCatalog catalog) { - } + protected internal abstract void CheckCatalog(PdfCatalog catalog); /// Verify the conformity of the page transparency. /// @@ -857,17 +831,6 @@ protected internal virtual void CheckCatalog(PdfCatalog catalog) { protected internal abstract void CheckPageTransparency(PdfDictionary pageDict, PdfDictionary pageResources ); - /// Verify the conformity of the resources dictionary. - /// - /// the - /// - /// to be checked - /// - [System.ObsoleteAttribute(@"in favor of checkResources(PdfDictionary resources, PdfObject pdfObject)")] - protected internal virtual void CheckResources(PdfDictionary resources) { - CheckResources(resources, null); - } - /// Verify the conformity of the resources dictionary. /// /// the @@ -930,16 +893,16 @@ protected internal static bool CheckFlag(int flags, int flag) { return (flags & flag) != 0; } - /// Checks conformance level of PDF/A standard. - /// + /// Checks conformance of PDF/A standard. + /// /// the - /// + /// /// to be checked /// - /// true if the specified conformanceLevel is a for PDF/A-1, PDF/A-2 or PDF/A-3 - protected internal static bool CheckStructure(PdfAConformanceLevel conformanceLevel) { - return conformanceLevel == PdfAConformanceLevel.PDF_A_1A || conformanceLevel == PdfAConformanceLevel.PDF_A_2A - || conformanceLevel == PdfAConformanceLevel.PDF_A_3A; + /// true if the specified aConformance is a for PDF/A-1, PDF/A-2 or PDF/A-3 + protected internal static bool CheckStructure(PdfAConformance aConformance) { + return aConformance == PdfAConformance.PDF_A_1A || aConformance == PdfAConformance.PDF_A_2A || aConformance + == PdfAConformance.PDF_A_3A; } /// Checks whether the specified dictionary has a transparency group. diff --git a/itext/itext.pdfa/itext/pdfa/exceptions/PdfAConformanceException.cs b/itext/itext.pdfa/itext/pdfa/exceptions/PdfAConformanceException.cs index cd11f07b33..2348ba19b2 100644 --- a/itext/itext.pdfa/itext/pdfa/exceptions/PdfAConformanceException.cs +++ b/itext/itext.pdfa/itext/pdfa/exceptions/PdfAConformanceException.cs @@ -26,338 +26,6 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Pdfa.Exceptions { /// Exception that is thrown when the PDF Document doesn't adhere to the PDF/A specification. public class PdfAConformanceException : PdfException { - [Obsolete] - public const String _0_ACTIONS_ARE_NOT_ALLOWED = "{0} actions are not allowed"; - - [Obsolete] - public const String A_CATALOG_DICTIONARY_SHALL_CONTAIN_METADATA_ENTRY = "A catalog dictionary shall contain metadata entry"; - - [Obsolete] - public const String A_CATALOG_DICTIONARY_SHALL_NOT_CONTAIN_AA_ENTRY = "A catalog dictionary shall not contain aa entry"; - - public const String A_CATALOG_DICTIONARY_SHALL_NOT_CONTAIN_ALTERNATEPRESENTATIONS_NAMES_ENTRY = "A catalog dictionary shall not contain alternatepresentations names entry"; - - [Obsolete] - public const String A_CATALOG_DICTIONARY_SHALL_NOT_CONTAIN_OCPROPERTIES_KEY = "A catalog dictionary shall not contain the ocproperties key"; - - [Obsolete] - public const String A_CATALOG_DICTIONARY_SHALL_NOT_CONTAIN_REQUIREMENTS_ENTRY = "A catalog dictionary shall not contain a requirements entry"; - - [Obsolete] - public const String A_CATALOG_SHALL_INCLUDE_MARK_INFO_DICTIONARY_WITH_MARKED_TRUE_VALUE = "A catalog dictionary shall include a markinfo dictionary whose entry marked shall have a value of true"; - - [Obsolete] - public const String A_FORM_XOBJECT_DICTIONARY_SHALL_NOT_CONTAIN_OPI_KEY = "A form xobject dictionary shall not contain opi key"; - - [Obsolete] - public const String A_FORM_XOBJECT_DICTIONARY_SHALL_NOT_CONTAIN_PS_KEY = "A form xobject dictionary shall not contain PS key"; - - [Obsolete] - public const String A_FORM_XOBJECT_DICTIONARY_SHALL_NOT_CONTAIN_SUBTYPE2_KEY_WITH_A_VALUE_OF_PS = "A form xobject dictionary shall not contain subtype2 key with a value of PS"; - - [Obsolete] - public const String A_GROUP_OBJECT_WITH_AN_S_KEY_WITH_A_VALUE_OF_TRANSPARENCY_SHALL_NOT_BE_INCLUDED_IN_A_FORM_XOBJECT - = "A group object with an s key with a value of transparency shall not be included in a form xobject"; - - [Obsolete] - public const String A_GROUP_OBJECT_WITH_AN_S_KEY_WITH_A_VALUE_OF_TRANSPARENCY_SHALL_NOT_BE_INCLUDED_IN_A_PAGE_XOBJECT - = "A group object with an s key with a value of transparency shall not be included in a page xobject"; - - [Obsolete] - public const String A_NAME_DICTIONARY_SHALL_NOT_CONTAIN_THE_EMBEDDED_FILES_KEY = "A name dictionary shall not contain the EmbeddedFiles key"; - - [Obsolete] - public const String ALL_COLOUR_CHANNELS_IN_THE_JPEG2000_DATA_SHALL_HAVE_THE_SAME_BIT_DEPTH = "All colour channels in the jpeg2000 data shall have the same bit-depth"; - - [Obsolete] - public const String ALL_HALFTONES_SHALL_HAVE_HALFTONETYPE_1_OR_5 = "All halftones shall have halftonetype 1 or 5"; - - [Obsolete] - public const String ALL_NON_SYMBOLIC_TRUE_TYPE_FONT_SHALL_SPECIFY_MAC_ROMAN_ENCODING_OR_WIN_ANSI_ENCODING = - "All non-symbolic TrueType fonts shall specify MacRomanEncoding or WinAnsiEncoding as the value of the Encoding entry in the font dictionary "; - - [Obsolete] - public const String ALL_NON_SYMBOLIC_TRUE_TYPE_FONT_SHALL_SPECIFY_MAC_ROMAN_OR_WIN_ANSI_ENCODING_AS_THE_ENCODING_ENTRY - = "All non-symbolic TrueType fonts shall specify MacRomanEncoding or WinAnsiEncoding as the value of the Encoding entry in the font dictionary This also means that Encoding entry in the font dictionary shall not be an encoding dictionary "; - - [Obsolete] - public const String ALL_SYMBOLIC_TRUE_TYPE_FONTS_SHALL_NOT_SPECIFY_ENCODING = "All symbolic TrueType fonts shall not specify an Encoding entry in the font dictionary "; - - [Obsolete] - public const String ALL_THE_FONTS_MUST_BE_EMBEDDED_THIS_ONE_IS_NOT_0 = "All the fonts must be embedded. This one is not: {0}"; - - [Obsolete] - public const String AN_ANNOTATION_DICTIONARY_SHALL_CONTAIN_THE_F_KEY = "An annotation dictionary shall contain the f key"; - - [Obsolete] - public const String AN_ANNOTATION_DICTIONARY_SHALL_NOT_CONTAIN_AA_KEY = "An annotation dictionary shall not contain aa key"; - - [Obsolete] - public const String AN_ANNOTATION_DICTIONARY_SHALL_NOT_CONTAIN_THE_CA_KEY_WITH_A_VALUE_OTHER_THAN_1 = "An annotation dictionary shall not contain the ca key with a value other than 1"; - - [Obsolete] - public const String AN_EXTGSTATE_DICTIONARY_SHALL_NOT_CONTAIN_THE_HTP_KEY = "An extgstate dictionary shall not contain the HTP key"; - - [Obsolete] - public const String AN_EXTGSTATE_DICTIONARY_SHALL_NOT_CONTAIN_THE_TR_2_KEY_WITH_A_VALUE_OTHER_THAN_DEFAULT - = "An extgstate dictionary shall not contain the TR2 key with a value other than default"; - - [Obsolete] - public const String AN_EXTGSTATE_DICTIONARY_SHALL_NOT_CONTAIN_THE_TR_KEY = "An extgstate dictionary shall not contain the tr key"; - - [Obsolete] - public const String AN_IMAGE_DICTIONARY_SHALL_NOT_CONTAIN_ALTERNATES_KEY = "An image dictionary shall not contain alternates key"; - - [Obsolete] - public const String AN_IMAGE_DICTIONARY_SHALL_NOT_CONTAIN_OPI_KEY = "An image dictionary shall not contain opi key"; - - [Obsolete] - public const String ANNOTATION_OF_TYPE_0_SHOULD_HAVE_CONTENTS_KEY = "Annotation of type {0} should have contents key"; - - [Obsolete] - public const String ANNOTATION_TYPE_0_IS_NOT_PERMITTED = "Annotation type {0} is not permitted"; - - [Obsolete] - public const String APPEARANCE_DICTIONARY_OF_WIDGET_SUBTYPE_AND_BTN_FIELD_TYPE_SHALL_CONTAIN_ONLY_THE_N_KEY_WITH_DICTIONARY_VALUE - = "Appearance dictionary of widget subtype and btn field type shall contain only the n key with dictionary value"; - - [Obsolete] - public const String APPEARANCE_DICTIONARY_SHALL_CONTAIN_ONLY_THE_N_KEY_WITH_STREAM_VALUE = "Appearance dictionary shall contain only the n key with stream value"; - - [Obsolete] - public const String BLEND_MODE_SHALL_HAVE_VALUE_NORMAL_OR_COMPATIBLE = "Blend mode shall have value normal or compatible"; - - [Obsolete] - public const String COLOR_SPACE_0_SHALL_BE_DEVICE_INDEPENDENT = "Color space {0} shall be device independent"; - - [Obsolete] - public const String COLOR_SPACE_0_SHALL_HAVE_1_COMPONENTS = "Color space {0} shall have {1} components"; - - [Obsolete] - public const String CRYPT_FILTER_IS_NOT_PERMITTED_INLINE_IMAGE = "Crypt filter is not permitted inline image"; - - [Obsolete] - public const String DEPRECATED_SETSTATE_AND_NOOP_ACTIONS_ARE_NOT_ALLOWED = "Deprecated setstate and noop actions are not allowed"; - - [Obsolete] - public const String DESTOUTPUTPROFILE_IN_THE_PDFA1_OUTPUTINTENT_DICTIONARY_SHALL_BE_RGB = "Destoutputprofile in the pdfa1 outputintent dictionary shall be rgb"; - - [Obsolete] - public const String DEVICECMYK_MAY_BE_USED_ONLY_IF_THE_FILE_HAS_A_CMYK_PDFA_OUTPUT_INTENT = "Devicecmyk may be used only if the file has a cmyk pdfa outputIntent"; - - [Obsolete] - public const String DEVICECMYK_MAY_BE_USED_ONLY_IF_THE_FILE_HAS_A_CMYK_PDFA_OUTPUT_INTENT_OR_DEFAULTCMYK_IN_USAGE_CONTEXT - = "Devicecmyk may be used only if the file has a cmyk pdfa outputIntent or defaultcmyk in usage context"; - - [Obsolete] - public const String DEVICERGB_AND_DEVICECMYK_COLORSPACES_CANNOT_BE_USED_BOTH_IN_ONE_FILE = "Devicergb and devicecmyk colorspaces cannot be used both in one file"; - - [Obsolete] - public const String DEVICERGB_MAY_BE_USED_ONLY_IF_THE_FILE_HAS_A_RGB_PDFA_OUTPUT_INTENT = "Devicergb may be used only if the file has a rgb pdfa outputIntent"; - - [Obsolete] - public const String DEVICERGB_MAY_BE_USED_ONLY_IF_THE_FILE_HAS_A_RGB_PDFA_OUTPUT_INTENT_OR_DEFAULTRGB_IN_USAGE_CONTEXT - = "Devicergb may be used only if the file has a rgb pdfa outputIntent or defaultrgb in usage context"; - - [Obsolete] - public const String DOCUMENT_TO_READ_FROM_SHALL_BE_A_PDFA_CONFORMANT_FILE_WITH_VALID_XMP_METADATA = "Document to read from shall be a pdfa conformant file with valid xmp metadata"; - - [Obsolete] - public const String EF_KEY_OF_FILE_SPECIFICATION_DICTIONARY_SHALL_CONTAIN_DICTIONARY_WITH_VALID_F_KEY = "Ef key of file specification dictionary shall contain dictionary with valid f key"; - - [Obsolete] - public const String EMBEDDED_FILE_SHALL_CONTAIN_PARAMS_KEY_WITH_DICTIONARY_AS_VALUE = "Embedded file shall contain params key with dictionary as value"; - - [Obsolete] - public const String EMBEDDED_FILE_SHALL_CONTAIN_PARAMS_KEY_WITH_VALID_MODDATE_KEY = "Embedded file shall contain params key with valid moddate key"; - - [Obsolete] - public const String KEYWORD_ENCRYPT_SHALL_NOT_BE_USED_IN_THE_TRAILER_DICTIONARY = "Keyword encrypt shall not be used in the trailer dictionary"; - - [Obsolete] - public const String EVERY_ANNOTATION_SHALL_HAVE_AT_LEAST_ONE_APPEARANCE_DICTIONARY = "Every annotation shall have at least one appearance dictionary"; - - [Obsolete] - public const String EXACTLY_ONE_COLOUR_SPACE_SPECIFICATION_SHALL_HAVE_THE_VALUE_0X01_IN_THE_APPROX_FIELD = - "Exactly one colour space specification shall have the value 0x01 in the approx field"; - - [Obsolete] - public const String FILE_SPECIFICATION_DICTIONARY_SHALL_CONTAIN_F_KEY_AND_UF_KEY = "File specification dictionary shall contain f key and uf key"; - - [Obsolete] - public const String FILE_SPECIFICATION_DICTIONARY_SHALL_CONTAIN_ONE_OF_THE_PREDEFINED_AFRELATIONSHIP_KEYS = - "File specification dictionary shall contain one of the predefined afrelationship keys"; - - [Obsolete] - public const String FILE_SPECIFICATION_DICTIONARY_SHALL_NOT_CONTAIN_THE_EF_KEY = "File specification dictionary shall not contain the EF key"; - - [Obsolete] - public const String GRAPHICS_STATE_STACK_DEPTH_IS_GREATER_THAN_28 = "Graphics state stack depth is greater than 28"; - - [Obsolete] - public const String HALFTONES_SHALL_NOT_CONTAIN_HALFTONENAME = "Halftones shall not contain halftonename"; - - [Obsolete] - public const String IF_DEVICE_RGB_CMYK_GRAY_USED_IN_FILE_THAT_FILE_SHALL_CONTAIN_PDFA_OUTPUTINTENT = "If device rgb cmyk gray used in file, that file shall contain pdfa outputintent"; - - [Obsolete] - public const String IF_DEVICE_RGB_CMYK_GRAY_USED_IN_FILE_THAT_FILE_SHALL_CONTAIN_PDFA_OUTPUTINTENT_OR_DEFAULT_RGB_CMYK_GRAY_IN_USAGE_CONTEXT - = "If device rgb cmyk gray used in file that file shall contain pdfa outputintent or DefaultRgb Cmyk Gray in usage context"; - - [Obsolete] - public const String IF_OUTPUTINTENTS_ARRAY_HAS_MORE_THAN_ONE_ENTRY_WITH_DESTOUTPUTPROFILE_KEY_THE_SAME_INDIRECT_OBJECT_SHALL_BE_USED_AS_THE_VALUE_OF_THAT_OBJECT - = "If outputintents array has more than one entry with destoutputprofile key the same indirect object shall be used as the value of that object"; - - [Obsolete] - public const String IF_SPECIFIED_RENDERING_SHALL_BE_ONE_OF_THE_FOLLOWING_RELATIVECOLORIMETRIC_ABSOLUTECOLORIMETRIC_PERCEPTUAL_OR_SATURATION - = "If specified rendering shall be one of the following relativecolorimetric absolutecolorimetric perceptual or saturation"; - - [Obsolete] - public const String INTEGER_NUMBER_IS_OUT_OF_RANGE = "Integer number is out of range"; - - [Obsolete] - public const String THE_DOCUMENT_DOES_NOT_CONTAIN_A_PDFA_OUTPUTINTENT_BUT_PAGE_CONTAINS_TRANSPARENCY_AND_DOES_NOT_CONTAIN_BLENDING_COLOR_SPACE - = "If the document does not contain a OutputIntent, then page with transparency shall include the dictionary with Group key that include a CS with blending colour space"; - - [Obsolete] - public const String JPEG2000_ENUMERATED_COLOUR_SPACE_19_CIEJAB_SHALL_NOT_BE_USED = "jpeg2000 enumerated colour space 19 (CIEJab) shall not be used"; - - [Obsolete] - public const String LZWDECODE_FILTER_IS_NOT_PERMITTED = "LZWDecode filter is not permitted"; - - [Obsolete] - public const String MAXIMUM_ARRAY_CAPACITY_IS_EXCEEDED = "Maximum array capacity is exceeded"; - - [Obsolete] - public const String MAXIMUM_DICTIONARY_CAPACITY_IS_EXCEEDED = "Maximum dictionary capacity is exceeded"; - - [Obsolete] - public const String MAXIMUM_NUMBER_OF_INDIRECT_OBJECTS_EXCEEDED = "Maximum number of indirect objects exceeded"; - - [Obsolete] - public const String MIME_TYPE_SHALL_BE_SPECIFIED_USING_THE_SUBTYPE_KEY_OF_THE_FILE_SPECIFICATION_STREAM_DICTIONARY - = "Mime type shall be specified using the subtype key of the file specification stream dictionary"; - - [Obsolete] - public const String N_KEY_SHALL_BE_APPEARANCE_SUBDICTIONARY = "If an annotation dictionary's Subtype key has a value of Widget and its FT key has a value of Btn, the value of the N key shall be an appearance subdictionary"; - - [Obsolete] - public const String NAMED_ACTION_TYPE_0_IS_NOT_ALLOWED = "Named action type {0} not allowed"; - - [Obsolete] - public const String NEEDAPPEARANCES_FLAG_OF_THE_INTERACTIVE_FORM_DICTIONARY_SHALL_EITHER_NOT_BE_PRESENTED_OR_SHALL_BE_FALSE - = "Needappearances flag of the interactive form dictionary shall either not be presented or shall be false"; - - [Obsolete] - public const String NO_KEYS_OTHER_THAN_UR3_AND_DOC_MDP_SHALL_BE_PRESENT_IN_A_PERMISSIONS_DICTIONARY = "No keys other than UR3 and DocMDP shall be present in a permissions dictionary"; - - [Obsolete] - public const String NOT_IDENTITY_CRYPT_FILTER_IS_NOT_PERMITTED = "Not identity crypt filter is not permitted"; - - [Obsolete] - public const String ONLY_JPX_BASELINE_SET_OF_FEATURES_SHALL_BE_USED = "Only jpx baseline set of features shall be used"; - - [Obsolete] - public const String ONLY_STANDARD_BLEND_MODES_SHALL_BE_USED_FOR_THE_VALUE_OF_THE_BM_KEY_IN_AN_EXTENDED_GRAPHIC_STATE_DICTIONARY - = "Only standard blend modes shall be used for the value of the BM key in an extended graphic state dictionary"; - - [Obsolete] - public const String OPTIONAL_CONTENT_CONFIGURATION_DICTIONARY_SHALL_CONTAIN_NAME_ENTRY = "Optional content configuration dictionary shall contain name entry"; - - [Obsolete] - public const String ORDER_ARRAY_SHALL_CONTAIN_REFERENCES_TO_ALL_OCGS = "Order array shall contain references to all ocgs"; - - [Obsolete] - public const String OUTPUT_INTENT_COLOR_SPACE_SHALL_BE_EITHER_GRAY_RGB_OR_CMYK = "Output intent color space shall be either gray rgb or cmyk"; - - [Obsolete] - public const String OVERPRINT_MODE_SHALL_NOT_BE_ONE_WHEN_AN_ICCBASED_CMYK_COLOUR_SPACE_IS_USED_AND_WHEN_OVERPRINTING_IS_SET_TO_TRUE - = "Overprint mode shall not be one when an ICCBased CMYK colour space is used and when overprinting is set to true"; - - [Obsolete] - public const String PDF_NAME_IS_TOO_LONG = "PdfName is too long"; - - [Obsolete] - public const String PDF_STRING_IS_TOO_LONG = "PdfString is too long"; - - [Obsolete] - public const String PROFILE_STREAM_OF_OUTPUTINTENT_SHALL_BE_OUTPUT_PROFILE_PRTR_OR_MONITOR_PROFILE_MNTR = - "Profile stream of outputintent shall be output profile (prtr) or monitor profile (mntr)"; - - [Obsolete] - public const String REAL_NUMBER_IS_OUT_OF_RANGE = "Real number is out of range"; - - [Obsolete] - public const String SIGNATURE_REFERENCES_DICTIONARY_SHALL_NOT_CONTAIN_DIGESTLOCATION_DIGESTMETHOD_DIGESTVALUE - = "Signature references dictionary shall not contain digestlocation digestmethod digestvalue"; - - [Obsolete] - public const String STREAM_OBJECT_DICTIONARY_SHALL_NOT_CONTAIN_THE_F_FFILTER_OR_FDECODEPARAMS_KEYS = "Stream object dictionary shall not contain the f ffilter or fdecodeparams keys"; - - [Obsolete] - public const String THE_AS_KEY_SHALL_NOT_APPEAR_IN_ANY_OPTIONAL_CONTENT_CONFIGURATION_DICTIONARY = "The as key shall not appear in any optional content configuration dictionary"; - - [Obsolete] - public const String THE_BIT_DEPTH_OF_THE_JPEG2000_DATA_SHALL_HAVE_A_VALUE_IN_THE_RANGE_1_TO_38 = "The bit-depth of the jpeg2000 data shall have a value in the range 1 to 38"; - - [Obsolete] - public const String THE_CATALOG_DICTIONARY_SHALL_NOT_CONTAIN_THE_NEEDSRENDERING_KEY = "The catalog dictionary shall not contain the needsrendering key"; - - [Obsolete] - public const String THE_F_KEYS_PRINT_FLAG_BIT_SHALL_BE_SET_TO_1_AND_ITS_HIDDEN_INVISIBLE_AND_NOVIEW_FLAG_BITS_SHALL_BE_SET_TO_0 - = "The f keys print flag bit shall be set to 1 and its hidden invisible and noview flag bits shall be set to 0"; - - [Obsolete] - public const String THE_F_KEYS_PRINT_FLAG_BIT_SHALL_BE_SET_TO_1_AND_ITS_HIDDEN_INVISIBLE_NOVIEW_AND_TOGGLENOVIEW_FLAG_BITS_SHALL_BE_SET_TO_0 - = "The f keys print flag bit shall be set to 1 and its hidden invisible noview and togglenoview flag bits shall be set to 0"; - - [Obsolete] - public const String THE_INTERACTIVE_FORM_DICTIONARY_SHALL_NOT_CONTAIN_THE_XFA_KEY = "The interactive form dictionary shall not contain the xfa key"; - - [Obsolete] - public const String THE_NUMBER_OF_COLOR_COMPONENTS_IN_DEVICE_N_COLORSPACE_SHOULD_NOT_EXCEED = "The number of color components in DeviceN colorspace should not exceed {0}"; - - [Obsolete] - public const String THE_NUMBER_OF_COLOUR_CHANNELS_IN_THE_JPEG2000_DATA_SHALL_BE_1_3_OR_4 = "The number of colour channels in the jpeg2000 data shall be 1, 3 or 4"; - - [Obsolete] - public const String THE_PAGE_DICTIONARY_SHALL_NOT_CONTAIN_AA_ENTRY = "The page dictionary shall not contain aa entry"; - - [Obsolete] - public const String THE_PAGE_DICTIONARY_SHALL_NOT_CONTAIN_PRESSTEPS_ENTRY = "The page dictionary shall not contain pressteps entry"; - - [Obsolete] - public const String THE_PAGE_LESS_3_UNITS_NO_GREATER_14400_IN_EITHER_DIRECTION = "The page is less than 3 units or greater than 14400 in either direction"; - - [Obsolete] - public const String THE_SMASK_KEY_IS_NOT_ALLOWED_IN_EXTGSTATE = "The smask key is not allowed in extgstate"; - - [Obsolete] - public const String THE_SMASK_KEY_IS_NOT_ALLOWED_IN_XOBJECTS = "The smask key is not allowed in xobjects"; - - [Obsolete] - public const String THE_VALUE_OF_INTERPOLATE_KEY_SHALL_BE_FALSE = "The value of interpolate key shall not be true"; - - [Obsolete] - public const String THE_VALUE_OF_THE_METH_ENTRY_IN_COLR_BOX_SHALL_BE_1_2_OR_3 = "The value of the meth entry in colr box shall be 1, 2 or 3"; - - [Obsolete] - public const String TINT_TRANSFORM_AND_ALTERNATE_SPACE_SHALL_BE_THE_SAME_FOR_THE_ALL_SEPARATION_CS_WITH_THE_SAME_NAME - = "TintTransform and alternateSpace shall be the same for the all separation cs with the same name"; - - [Obsolete] - public const String TRANSPARENCY_IS_NOT_ALLOWED_AND_CA_SHALL_BE_EQUAL_TO_1 = "Transparency is not allowed. ca shall be equal to 1"; - - [Obsolete] - public const String TRANSPARENCY_IS_NOT_ALLOWED_CA_SHALL_BE_EQUAL_TO_1 = "Transparency is not allowed. CA shall be equal to 1"; - - [Obsolete] - public const String VALUE_OF_NAME_ENTRY_SHALL_BE_UNIQUE_AMONG_ALL_OPTIONAL_CONTENT_CONFIGURATION_DICTIONARIES - = "Value of name entry shall be unique among all optional content configuration dictionaries"; - - [Obsolete] - public const String WIDGET_ANNOTATION_DICTIONARY_OR_FIELD_DICTIONARY_SHALL_NOT_INCLUDE_A_OR_AA_ENTRY = "Widget annotation dictionary or field dictionary shall not include a or aa entry"; - /// Creates a PdfAConformanceException. /// the error message public PdfAConformanceException(String message) diff --git a/itext/itext.pdfa/itext/pdfa/exceptions/PdfaExceptionMessageConstant.cs b/itext/itext.pdfa/itext/pdfa/exceptions/PdfaExceptionMessageConstant.cs index 5932693b9c..67febcaa05 100644 --- a/itext/itext.pdfa/itext/pdfa/exceptions/PdfaExceptionMessageConstant.cs +++ b/itext/itext.pdfa/itext/pdfa/exceptions/PdfaExceptionMessageConstant.cs @@ -309,7 +309,7 @@ public const String ONLY_STANDARD_BLEND_MODES_SHALL_BE_USED_FOR_THE_VALUE_OF_THE + " contain version identifier pdfaid:rev with four digit integer value"; public const String XMP_METADATA_HEADER_SHALL_CONTAIN_VERSION_IDENTIFIER_CONFORMANCE = "XMP metadata header shall" - + " contain version identifier pdfaid:rev F or E or absent if no conformance level is specified"; + + " contain version identifier pdfaid:rev F or E or absent if no conformance is specified"; public const String XMP_METADATA_HISTORY_ENTRY_SHALL_CONTAIN_KEY = "XMP metadata history entry shall" + " contain key {0}"; diff --git a/itext/itext.pdfa/itext/pdfa/logs/PdfALogMessageConstant.cs b/itext/itext.pdfa/itext/pdfa/logs/PdfALogMessageConstant.cs index 7baf45638f..205aa0d66b 100644 --- a/itext/itext.pdfa/itext/pdfa/logs/PdfALogMessageConstant.cs +++ b/itext/itext.pdfa/itext/pdfa/logs/PdfALogMessageConstant.cs @@ -31,6 +31,8 @@ public class PdfALogMessageConstant { public const String PDFA_OBJECT_FLUSHING_WAS_NOT_PERFORMED = "Object flushing was not performed. Object in PDF/A mode can only be flushed if the document is closed or " + "if this object has already been checked for compliance with PDF/A rules."; + public const String WRITER_PROPERTIES_PDF_VERSION_WAS_OVERRIDDEN = "Pdf version from writer properties isn't compatible with specified PDF/A conformance, it was overridden to {0} version."; + private PdfALogMessageConstant() { } //Private constructor will prevent the instantiation of this class directly diff --git a/itext/itext.pdftest/Properties/AssemblyInfo.cs b/itext/itext.pdftest/Properties/AssemblyInfo.cs index ee4f179625..fceb088ed2 100644 --- a/itext/itext.pdftest/Properties/AssemblyInfo.cs +++ b/itext/itext.pdftest/Properties/AssemblyInfo.cs @@ -20,6 +20,6 @@ [assembly: Guid("f9880dc4-f015-4413-af86-66d0e9512774")] -[assembly: AssemblyVersion("8.0.5.0")] -[assembly: AssemblyFileVersion("8.0.5.0")] -[assembly: AssemblyInformationalVersion("8.0.5")] +[assembly: AssemblyVersion("9.0.0.0")] +[assembly: AssemblyFileVersion("9.0.0.0")] +[assembly: AssemblyInformationalVersion("9.0.0")] diff --git a/itext/itext.pdftest/itext-pdftest.nuspec b/itext/itext.pdftest/itext-pdftest.nuspec index 126fb24eca..3c3841f55b 100644 --- a/itext/itext.pdftest/itext-pdftest.nuspec +++ b/itext/itext.pdftest/itext-pdftest.nuspec @@ -2,7 +2,7 @@ itext.pdftest - 8.0.5 + 9.0.0 iText pdftest module Apryse Software Apryse Software diff --git a/itext/itext.pdfua/Properties/AssemblyInfo.cs b/itext/itext.pdfua/Properties/AssemblyInfo.cs index 5939679209..35fe331366 100644 --- a/itext/itext.pdfua/Properties/AssemblyInfo.cs +++ b/itext/itext.pdfua/Properties/AssemblyInfo.cs @@ -21,6 +21,6 @@ [assembly: Guid("661fd317-7340-42a4-a7f0-07a60ad3d278")] -[assembly: AssemblyVersion("8.0.5.0")] -[assembly: AssemblyFileVersion("8.0.5.0")] -[assembly: AssemblyInformationalVersion("8.0.5")] +[assembly: AssemblyVersion("9.0.0.0")] +[assembly: AssemblyFileVersion("9.0.0.0")] +[assembly: AssemblyInformationalVersion("9.0.0")] diff --git a/itext/itext.pdfua/itext/pdfua/PdfUAConfig.cs b/itext/itext.pdfua/itext/pdfua/PdfUAConfig.cs index 6769a3982a..d3ed959802 100644 --- a/itext/itext.pdfua/itext/pdfua/PdfUAConfig.cs +++ b/itext/itext.pdfua/itext/pdfua/PdfUAConfig.cs @@ -26,29 +26,29 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Pdfua { /// Class that holds the configuration for the PDF/UA document. public class PdfUAConfig { - private readonly PdfUAConformanceLevel conformanceLevel; + private readonly PdfUAConformance conformance; private readonly String title; private readonly String language; /// Creates a new PdfUAConfig instance. - /// The conformance level of the PDF/UA document. - /// The title of the PDF/UA document. - /// The language of the PDF/UA document. - public PdfUAConfig(PdfUAConformanceLevel conformanceLevel, String title, String language) { - this.conformanceLevel = conformanceLevel; + /// the conformance of the PDF/UA document + /// the title of the PDF/UA document + /// the language of the PDF/UA document + public PdfUAConfig(PdfUAConformance conformance, String title, String language) { + this.conformance = conformance; this.title = title; this.language = language; } - /// Gets the conformance level. + /// Gets the UA conformance. /// /// The - /// . + /// . /// - public virtual PdfUAConformanceLevel GetConformanceLevel() { - return conformanceLevel; + public virtual PdfUAConformance GetConformance() { + return conformance; } /// Gets the title. diff --git a/itext/itext.pdfua/itext/pdfua/PdfUADocument.cs b/itext/itext.pdfua/itext/pdfua/PdfUADocument.cs index bba64cc21f..3ea149f7de 100644 --- a/itext/itext.pdfua/itext/pdfua/PdfUADocument.cs +++ b/itext/itext.pdfua/itext/pdfua/PdfUADocument.cs @@ -22,10 +22,11 @@ You should have received a copy of the GNU Affero General Public License */ using Microsoft.Extensions.Logging; using iText.Commons; +using iText.Commons.Utils; using iText.Kernel.Pdf; -using iText.Kernel.Utils; +using iText.Kernel.Validation; using iText.Pdfua.Checkers; -using iText.Pdfua.Exceptions; +using iText.Pdfua.Logs; namespace iText.Pdfua { /// Creates a Pdf/UA document. @@ -35,14 +36,8 @@ namespace iText.Pdfua { /// It will add necessary validation to guide the user to create a PDF/UA compliant document. /// public class PdfUADocument : PdfDocument { - private static readonly IPdfPageFactory pdfPageFactory = new PdfUAPageFactory(); - private static readonly ILogger LOGGER = ITextLogManager.GetLogger(typeof(iText.Pdfua.PdfUADocument)); - private PdfUAConfig config; - - private bool warnedOnPageFlush = false; - /// Creates a PdfUADocument instance. /// The writer to write the PDF document. /// The configuration for the PDF/UA document. @@ -56,7 +51,13 @@ public PdfUADocument(PdfWriter writer, PdfUAConfig config) /// The configuration for the PDF/UA document. public PdfUADocument(PdfWriter writer, DocumentProperties properties, PdfUAConfig config) : base(ConfigureWriterProperties(writer), properties) { + this.pdfConformance = new PdfConformance(config.GetConformance()); SetupUAConfiguration(config); + ValidationContainer validationContainer = new ValidationContainer(); + PdfUA1Checker checker = new PdfUA1Checker(this); + validationContainer.AddChecker(checker); + this.GetDiContainer().Register(typeof(ValidationContainer), validationContainer); + this.pdfPageFactory = new PdfUAPageFactory(checker); } /// Creates a PdfUADocument instance. @@ -64,8 +65,7 @@ public PdfUADocument(PdfWriter writer, DocumentProperties properties, PdfUAConfi /// The writer to write the PDF document. /// The configuration for the PDF/UA document. public PdfUADocument(PdfReader reader, PdfWriter writer, PdfUAConfig config) - : base(reader, ConfigureWriterProperties(writer)) { - SetupUAConfiguration(config); + : this(reader, writer, new StampingProperties(), config) { } /// Creates a PdfUADocument instance. @@ -75,64 +75,35 @@ public PdfUADocument(PdfReader reader, PdfWriter writer, PdfUAConfig config) /// The configuration for the PDF/UA document. public PdfUADocument(PdfReader reader, PdfWriter writer, StampingProperties properties, PdfUAConfig config ) - : base(reader, ConfigureWriterProperties(writer), properties) { + : base(reader, writer, properties) { + if (!GetConformance().IsPdfUA()) { + LOGGER.LogWarning(PdfUALogMessageConstants.PDF_TO_PDF_UA_CONVERSION_IS_NOT_SUPPORTED); + } SetupUAConfiguration(config); + ValidationContainer validationContainer = new ValidationContainer(); + PdfUA1Checker checker = new PdfUA1Checker(this); + validationContainer.AddChecker(checker); + this.GetDiContainer().Register(typeof(ValidationContainer), validationContainer); + this.pdfPageFactory = new PdfUAPageFactory(checker); } - /// {inheritDoc} - public override IConformanceLevel GetConformanceLevel() { - return config.GetConformanceLevel(); - } - - /// The PageFactory for the PDF/UA document. - protected override IPdfPageFactory GetPageFactory() { - return pdfPageFactory; - } - -//\cond DO_NOT_DOCUMENT - /// Returns if the document is in the closing state. - /// true if the document is closing, false otherwise. - internal virtual bool IsClosing() { - return this.isClosing; - } -//\endcond - -//\cond DO_NOT_DOCUMENT - /// Warns the user that the page is being flushed. - /// - /// Warns the user that the page is being flushed. - /// Will only warn once. - /// - internal virtual void WarnOnPageFlush() { - if (!warnedOnPageFlush) { - LOGGER.LogWarning(PdfUALogMessageConstants.PAGE_FLUSHING_DISABLED); - warnedOnPageFlush = true; + private static PdfWriter ConfigureWriterProperties(PdfWriter writer) { + writer.GetProperties().AddPdfUaXmpMetadata(PdfUAConformance.PDF_UA_1); + if (writer.GetPdfVersion() != null && !writer.GetPdfVersion().Equals(PdfVersion.PDF_1_7)) { + ITextLogManager.GetLogger(typeof(iText.Pdfua.PdfUADocument)).LogWarning(MessageFormatUtil.Format(PdfUALogMessageConstants + .WRITER_PROPERTIES_PDF_VERSION_WAS_OVERRIDDEN, PdfVersion.PDF_1_7)); + writer.GetProperties().SetPdfVersion(PdfVersion.PDF_1_7); } - } -//\endcond - - /// Disables the warning for page flushing. - public virtual void DisablePageFlushingWarning() { - warnedOnPageFlush = true; + return writer; } private void SetupUAConfiguration(PdfUAConfig config) { //basic configuration - this.config = config; this.SetTagged(); this.GetCatalog().SetViewerPreferences(new PdfViewerPreferences().SetDisplayDocTitle(true)); this.GetCatalog().SetLang(new PdfString(config.GetLanguage())); PdfDocumentInfo info = this.GetDocumentInfo(); info.SetTitle(config.GetTitle()); - //validation - ValidationContainer validationContainer = new ValidationContainer(); - validationContainer.AddChecker(new PdfUA1Checker(this)); - this.GetDiContainer().Register(typeof(ValidationContainer), validationContainer); - } - - private static PdfWriter ConfigureWriterProperties(PdfWriter writer) { - writer.GetProperties().AddUAXmpMetadata(); - return writer; } } } diff --git a/itext/itext.pdfua/itext/pdfua/PdfUAPage.cs b/itext/itext.pdfua/itext/pdfua/PdfUAPage.cs index 604f5aad52..94b221a6a7 100644 --- a/itext/itext.pdfua/itext/pdfua/PdfUAPage.cs +++ b/itext/itext.pdfua/itext/pdfua/PdfUAPage.cs @@ -22,25 +22,29 @@ You should have received a copy of the GNU Affero General Public License */ using iText.Kernel.Geom; using iText.Kernel.Pdf; +using iText.Pdfua.Checkers; namespace iText.Pdfua { //\cond DO_NOT_DOCUMENT internal class PdfUAPage : PdfPage { - protected internal PdfUAPage(PdfDictionary pdfObject) + private readonly PdfUA1Checker checker; + + protected internal PdfUAPage(PdfDictionary pdfObject, PdfUA1Checker checker) : base(pdfObject) { + this.checker = checker; } - protected internal PdfUAPage(PdfDocument pdfDocument, PageSize pageSize) + protected internal PdfUAPage(PdfDocument pdfDocument, PageSize pageSize, PdfUA1Checker checker) : base(pdfDocument, pageSize) { + this.checker = checker; } public override void Flush(bool flushResourcesContentStreams) { - PdfDocument document = GetDocument(); - if (((PdfUADocument)document).IsClosing()) { + if (GetDocument().IsClosing()) { base.Flush(flushResourcesContentStreams); return; } - ((PdfUADocument)document).WarnOnPageFlush(); + checker.WarnOnPageFlush(); } } //\endcond diff --git a/itext/itext.pdfua/itext/pdfua/PdfUAPageFactory.cs b/itext/itext.pdfua/itext/pdfua/PdfUAPageFactory.cs index b074c5a8b2..fc7a8b0643 100644 --- a/itext/itext.pdfua/itext/pdfua/PdfUAPageFactory.cs +++ b/itext/itext.pdfua/itext/pdfua/PdfUAPageFactory.cs @@ -22,14 +22,25 @@ You should have received a copy of the GNU Affero General Public License */ using iText.Kernel.Geom; using iText.Kernel.Pdf; +using iText.Pdfua.Checkers; namespace iText.Pdfua { //\cond DO_NOT_DOCUMENT + /// The class implements PDF page factory which is used for creating correct PDF/UA documents. internal class PdfUAPageFactory : IPdfPageFactory { - public PdfUAPageFactory() { + private readonly PdfUA1Checker checker; + + /// + /// Instantiates a new + /// + /// instance based on + /// . + /// + /// the PDF/UA checker + public PdfUAPageFactory(PdfUA1Checker checker) { + this.checker = checker; } - //empty constructor /// /// the /// @@ -39,7 +50,7 @@ public PdfUAPageFactory() { /// /// The pdf page. public virtual PdfPage CreatePdfPage(PdfDictionary pdfObject) { - return new PdfUAPage(pdfObject); + return new PdfUAPage(pdfObject, checker); } /// @@ -54,7 +65,7 @@ public virtual PdfPage CreatePdfPage(PdfDictionary pdfObject) { /// /// The Pdf page. public virtual PdfPage CreatePdfPage(PdfDocument pdfDocument, PageSize pageSize) { - return new PdfUAPage(pdfDocument, pageSize); + return new PdfUAPage(pdfDocument, pageSize, checker); } } //\endcond diff --git a/itext/itext.pdfua/itext/pdfua/checkers/PdfUA1Checker.cs b/itext/itext.pdfua/itext/pdfua/checkers/PdfUA1Checker.cs index 8185bf9ff5..58fcd1cbbe 100644 --- a/itext/itext.pdfua/itext/pdfua/checkers/PdfUA1Checker.cs +++ b/itext/itext.pdfua/itext/pdfua/checkers/PdfUA1Checker.cs @@ -22,19 +22,24 @@ You should have received a copy of the GNU Affero General Public License */ using System; using System.Collections.Generic; +using Microsoft.Extensions.Logging; +using iText.Commons; using iText.Commons.Datastructures; using iText.Commons.Utils; using iText.Kernel.Font; using iText.Kernel.Pdf; using iText.Kernel.Pdf.Tagging; using iText.Kernel.Pdf.Tagutils; -using iText.Kernel.Utils; using iText.Kernel.Utils.Checkers; +using iText.Kernel.Validation; +using iText.Kernel.Validation.Context; using iText.Kernel.XMP; +using iText.Layout.Validation.Context; using iText.Pdfua.Checkers.Utils; using iText.Pdfua.Checkers.Utils.Headings; using iText.Pdfua.Checkers.Utils.Tables; using iText.Pdfua.Exceptions; +using iText.Pdfua.Logs; namespace iText.Pdfua.Checkers { /// The class defines the requirements of the PDF/UA-1 standard. @@ -52,6 +57,8 @@ public class PdfUA1Checker : IValidationChecker { private readonly PdfUAValidationContext context; + private bool warnedOnPageFlush = false; + /// Creates PdfUA1Checker instance with PDF document which will be validated against PDF/UA-1 standard. /// /// the document to validate @@ -62,53 +69,78 @@ public PdfUA1Checker(PdfDocument pdfDocument) { this.headingsChecker = new HeadingsChecker(context); } - /// - public virtual void ValidateDocument(ValidationContext validationContext) { - CheckCatalog(validationContext.GetPdfDocument().GetCatalog()); - CheckStructureTreeRoot(validationContext.GetPdfDocument().GetStructTreeRoot()); - CheckFonts(validationContext.GetFonts()); - XfaCheckUtil.Check(validationContext.GetPdfDocument()); - } - - /// - public virtual void ValidateObject(Object obj, IsoKey key, PdfResources resources, PdfStream contentStream - , Object extra) { - switch (key) { - case IsoKey.LAYOUT: { - new LayoutCheckUtil(context).CheckRenderer(obj); - headingsChecker.CheckLayoutElement(obj); + /// + /// . + /// + public virtual void Validate(IValidationContext context) { + switch (context.GetType()) { + case ValidationType.PDF_DOCUMENT: { + PdfDocumentValidationContext pdfDocContext = (PdfDocumentValidationContext)context; + CheckCatalog(pdfDocContext.GetPdfDocument().GetCatalog()); + CheckStructureTreeRoot(pdfDocContext.GetPdfDocument().GetStructTreeRoot()); + CheckFonts(pdfDocContext.GetDocumentFonts()); + XfaCheckUtil.Check(pdfDocContext.GetPdfDocument()); break; } - case IsoKey.CANVAS_WRITING_CONTENT: { - CheckOnWritingCanvasToContent(obj); + case ValidationType.PDF_OBJECT: { + PdfObjectValidationContext objContext = (PdfObjectValidationContext)context; + CheckPdfObject(objContext.GetObject()); break; } - case IsoKey.CANVAS_BEGIN_MARKED_CONTENT: { - CheckOnOpeningBeginMarkedContent(obj, extra); + case ValidationType.CRYPTO: { + CryptoValidationContext cryptoContext = (CryptoValidationContext)context; + CheckCrypto((PdfDictionary)cryptoContext.GetCrypto()); break; } - case IsoKey.FONT: { - CheckText((String)obj, (PdfFont)extra); + case ValidationType.FONT: { + FontValidationContext fontContext = (FontValidationContext)context; + CheckText(fontContext.GetText(), fontContext.GetFont()); break; } - case IsoKey.DUPLICATE_ID_ENTRY: { - throw new PdfUAConformanceException(MessageFormatUtil.Format(PdfUAExceptionMessageConstants.NON_UNIQUE_ID_ENTRY_IN_STRUCT_TREE_ROOT - , obj)); + case ValidationType.CANVAS_BEGIN_MARKED_CONTENT: { + CanvasBmcValidationContext bmcContext = (CanvasBmcValidationContext)context; + CheckOnOpeningBeginMarkedContent(bmcContext.GetTagStructureStack(), bmcContext.GetCurrentBmc()); + break; } - case IsoKey.PDF_OBJECT: { - CheckPdfObject((PdfObject)obj); + case ValidationType.CANVAS_WRITING_CONTENT: { + CanvasWritingContentValidationContext writingContext = (CanvasWritingContentValidationContext)context; + CheckOnWritingCanvasToContent(writingContext.GetTagStructureStack()); break; } - case IsoKey.CRYPTO: { - CheckCrypto((PdfDictionary)obj); + case ValidationType.LAYOUT: { + LayoutValidationContext layoutContext = (LayoutValidationContext)context; + new LayoutCheckUtil(this.context).CheckRenderer(layoutContext.GetRenderer()); + headingsChecker.CheckLayoutElement(layoutContext.GetRenderer()); break; } + + case ValidationType.DUPLICATE_ID_ENTRY: { + DuplicateIdEntryValidationContext idContext = (DuplicateIdEntryValidationContext)context; + throw new PdfUAConformanceException(MessageFormatUtil.Format(PdfUAExceptionMessageConstants.NON_UNIQUE_ID_ENTRY_IN_STRUCT_TREE_ROOT + , idContext.GetId())); + } + } + } + + /// + /// . + /// + public virtual bool IsPdfObjectReadyToFlush(PdfObject @object) { + return true; + } + + /// Logs a warn on page flushing that page flushing is disabled in PDF/UA mode. + public virtual void WarnOnPageFlush() { + if (!warnedOnPageFlush) { + ITextLogManager.GetLogger(typeof(iText.Pdfua.Checkers.PdfUA1Checker)).LogWarning(PdfUALogMessageConstants. + PAGE_FLUSHING_DISABLED); + warnedOnPageFlush = true; } } @@ -139,14 +171,12 @@ protected internal virtual void CheckMetadata(PdfCatalog catalog) { if (catalog.GetDocument().GetPdfVersion().CompareTo(PdfVersion.PDF_1_7) > 0) { throw new PdfUAConformanceException(PdfUAExceptionMessageConstants.INVALID_PDF_VERSION); } - PdfObject pdfMetadata = catalog.GetPdfObject().Get(PdfName.Metadata); - if (pdfMetadata == null || !pdfMetadata.IsStream()) { - throw new PdfUAConformanceException(PdfUAExceptionMessageConstants.DOCUMENT_SHALL_CONTAIN_XMP_METADATA_STREAM - ); - } - byte[] metaBytes = ((PdfStream)pdfMetadata).GetBytes(); try { - XMPMeta metadata = XMPMetaFactory.ParseFromBuffer(metaBytes); + XMPMeta metadata = catalog.GetDocument().GetXmpMetadata(); + if (metadata == null) { + throw new PdfUAConformanceException(PdfUAExceptionMessageConstants.DOCUMENT_SHALL_CONTAIN_XMP_METADATA_STREAM + ); + } int? part = metadata.GetPropertyInteger(XMPConst.NS_PDFUA_ID, XMPConst.PART); if (!Convert.ToInt32(1).Equals(part)) { throw new PdfUAConformanceException(PdfUAExceptionMessageConstants.METADATA_SHALL_CONTAIN_UA_VERSION_IDENTIFIER @@ -176,8 +206,7 @@ private void CheckViewerPreferences(PdfCatalog catalog) { } } - private void CheckOnWritingCanvasToContent(Object data) { - Stack> tagStack = GetTagStack(data); + private void CheckOnWritingCanvasToContent(Stack> tagStack) { if (tagStack.IsEmpty()) { throw new PdfUAConformanceException(PdfUAExceptionMessageConstants.TAG_HASNT_BEEN_ADDED_BEFORE_CONTENT_ADDING ); @@ -196,14 +225,9 @@ private void CheckOnWritingCanvasToContent(Object data) { } } - private Stack> GetTagStack(Object data) { - return (Stack>)data; - } - - private void CheckOnOpeningBeginMarkedContent(Object obj, Object extra) { - Tuple2 currentBmc = (Tuple2)extra; + private void CheckOnOpeningBeginMarkedContent(Stack> stack, Tuple2 currentBmc) { CheckStandardRoleMapping(currentBmc); - Stack> stack = GetTagStack(obj); if (stack.IsEmpty()) { return; } @@ -253,8 +277,7 @@ private bool IsRealContent(Tuple2 tag) { if (properties == null || !properties.ContainsKey(PdfName.MCID)) { return false; } - PdfMcr mcr = this.pdfDocument.GetStructTreeRoot().FindMcrByMcid(pdfDocument, (int)properties.GetAsInt(PdfName - .MCID)); + PdfMcr mcr = McrExists(pdfDocument, (int)properties.GetAsInt(PdfName.MCID)); if (mcr == null) { throw new PdfUAConformanceException(PdfUAExceptionMessageConstants.CONTENT_WITH_MCID_BUT_MCID_NOT_FOUND_IN_STRUCT_TREE_ROOT ); @@ -262,6 +285,18 @@ private bool IsRealContent(Tuple2 tag) { return true; } + private PdfMcr McrExists(PdfDocument document, int mcid) { + int amountOfPages = document.GetNumberOfPages(); + for (int i = 1; i <= amountOfPages; ++i) { + PdfPage page = document.GetPage(i); + PdfMcr mcr = document.GetStructTreeRoot().FindMcrByMcid(page.GetPdfObject(), mcid); + if (mcr != null) { + return mcr; + } + } + return null; + } + private void CheckCatalog(PdfCatalog catalog) { PdfDictionary catalogDict = catalog.GetPdfObject(); if (!catalogDict.ContainsKey(PdfName.Metadata)) { diff --git a/itext/itext.pdfua/itext/pdfua/checkers/utils/AnnotationCheckUtil.cs b/itext/itext.pdfua/itext/pdfua/checkers/utils/AnnotationCheckUtil.cs index 3e176dc582..e08f5f3084 100644 --- a/itext/itext.pdfua/itext/pdfua/checkers/utils/AnnotationCheckUtil.cs +++ b/itext/itext.pdfua/itext/pdfua/checkers/utils/AnnotationCheckUtil.cs @@ -84,8 +84,11 @@ public AnnotationHandler(PdfUAValidationContext context) : base(context) { } - /// - public override void NextElement(IStructureNode elem) { + public override bool Accept(IStructureNode node) { + return node != null; + } + + public override void ProcessElement(IStructureNode elem) { if (!(elem is PdfObjRef)) { return; } diff --git a/itext/itext.pdfua/itext/pdfua/checkers/utils/ContextAwareTagTreeIteratorHandler.cs b/itext/itext.pdfua/itext/pdfua/checkers/utils/ContextAwareTagTreeIteratorHandler.cs index bd45faf6d0..314b2d9b63 100644 --- a/itext/itext.pdfua/itext/pdfua/checkers/utils/ContextAwareTagTreeIteratorHandler.cs +++ b/itext/itext.pdfua/itext/pdfua/checkers/utils/ContextAwareTagTreeIteratorHandler.cs @@ -37,6 +37,8 @@ protected internal ContextAwareTagTreeIteratorHandler(PdfUAValidationContext con this.context = context; } - public abstract void NextElement(IStructureNode arg1); + public abstract bool Accept(IStructureNode arg1); + + public abstract void ProcessElement(IStructureNode arg1); } } diff --git a/itext/itext.pdfua/itext/pdfua/checkers/utils/FormCheckUtil.cs b/itext/itext.pdfua/itext/pdfua/checkers/utils/FormCheckUtil.cs index 9e53e32269..59bb7b552d 100644 --- a/itext/itext.pdfua/itext/pdfua/checkers/utils/FormCheckUtil.cs +++ b/itext/itext.pdfua/itext/pdfua/checkers/utils/FormCheckUtil.cs @@ -48,8 +48,11 @@ public FormTagHandler(PdfUAValidationContext context) : base(context) { } - /// - public override void NextElement(IStructureNode elem) { + public override bool Accept(IStructureNode node) { + return node != null; + } + + public override void ProcessElement(IStructureNode elem) { PdfStructElem form = context.GetElementIfRoleMatches(PdfName.Form, elem); if (form == null) { return; diff --git a/itext/itext.pdfua/itext/pdfua/checkers/utils/FormulaCheckUtil.cs b/itext/itext.pdfua/itext/pdfua/checkers/utils/FormulaCheckUtil.cs index 90796c31ac..e8f563d27c 100644 --- a/itext/itext.pdfua/itext/pdfua/checkers/utils/FormulaCheckUtil.cs +++ b/itext/itext.pdfua/itext/pdfua/checkers/utils/FormulaCheckUtil.cs @@ -61,8 +61,11 @@ public FormulaTagHandler(PdfUAValidationContext context) : base(context) { } - /// - public override void NextElement(IStructureNode elem) { + public override bool Accept(IStructureNode node) { + return node != null; + } + + public override void ProcessElement(IStructureNode elem) { PdfStructElem structElem = context.GetElementIfRoleMatches(PdfName.Formula, elem); if (structElem == null) { return; diff --git a/itext/itext.pdfua/itext/pdfua/checkers/utils/GraphicsCheckUtil.cs b/itext/itext.pdfua/itext/pdfua/checkers/utils/GraphicsCheckUtil.cs index 95e3a40680..49d4cd853a 100644 --- a/itext/itext.pdfua/itext/pdfua/checkers/utils/GraphicsCheckUtil.cs +++ b/itext/itext.pdfua/itext/pdfua/checkers/utils/GraphicsCheckUtil.cs @@ -42,32 +42,6 @@ public GraphicsCheckUtil(PdfUAValidationContext context) { this.context = context; } - /// WARNING! This method is an artifact and currently does nothing. - /// - /// WARNING! This method is an artifact and currently does nothing. - /// It is kept to ensure backward binary compatibility - /// - /// image to check - [System.ObsoleteAttribute(@"This method is an artifact and will be removed.")] - public static void CheckLayoutImage(Image image) { - } - - //No impl - /// WARNING! This method is an artifact and currently does nothing. - /// - /// WARNING! This method is an artifact and currently does nothing. - /// It is kept to ensure backward binary compatibility - /// - /// - /// - /// - /// always null - /// - [System.ObsoleteAttribute(@"This method is an artifact and will be removed.")] - public static ITagTreeIteratorHandler CreateFigureTagHandler() { - return null; - } - /// Checks if image has alternative description or actual text. /// The image to check public void CheckLayoutElement(Image image) { @@ -117,8 +91,11 @@ public GraphicsHandler(PdfUAValidationContext context) : base(context) { } - /// - public override void NextElement(IStructureNode elem) { + public override bool Accept(IStructureNode node) { + return node != null; + } + + public override void ProcessElement(IStructureNode elem) { PdfStructElem structElem = context.GetElementIfRoleMatches(PdfName.Figure, elem); if (structElem == null) { return; diff --git a/itext/itext.pdfua/itext/pdfua/checkers/utils/LayoutCheckUtil.cs b/itext/itext.pdfua/itext/pdfua/checkers/utils/LayoutCheckUtil.cs index 2a0e92b317..a2263bb593 100644 --- a/itext/itext.pdfua/itext/pdfua/checkers/utils/LayoutCheckUtil.cs +++ b/itext/itext.pdfua/itext/pdfua/checkers/utils/LayoutCheckUtil.cs @@ -20,7 +20,6 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ -using System; using iText.Layout; using iText.Layout.Element; using iText.Layout.Renderer; @@ -41,23 +40,13 @@ public LayoutCheckUtil(PdfUAValidationContext context) { this.context = context; } - /// WARNING! This method is an artifact and currently does nothing. - /// - /// WARNING! This method is an artifact and currently does nothing. - /// It is kept to ensure backward binary compatibility - /// - /// layout element to check - [Obsolete] - public static void CheckLayoutElements(Object rendererObj) { - } - /// Checks renderer for PDF UA compliance. - /// The renderer to check. - public void CheckRenderer(Object rendererObj) { - if (rendererObj == null) { + /// The renderer to check. + public void CheckRenderer(IRenderer renderer) { + if (renderer == null) { return; } - IPropertyContainer layoutElement = ((IRenderer)rendererObj).GetModelElement(); + IPropertyContainer layoutElement = renderer.GetModelElement(); if (layoutElement is Image) { new GraphicsCheckUtil(context).CheckLayoutElement((Image)layoutElement); } diff --git a/itext/itext.pdfua/itext/pdfua/checkers/utils/NoteCheckUtil.cs b/itext/itext.pdfua/itext/pdfua/checkers/utils/NoteCheckUtil.cs index b81c2ca3e9..6c99a25843 100644 --- a/itext/itext.pdfua/itext/pdfua/checkers/utils/NoteCheckUtil.cs +++ b/itext/itext.pdfua/itext/pdfua/checkers/utils/NoteCheckUtil.cs @@ -39,8 +39,11 @@ public NoteTagHandler(PdfUAValidationContext context) : base(context) { } - /// - public override void NextElement(IStructureNode elem) { + public override bool Accept(IStructureNode node) { + return node != null; + } + + public override void ProcessElement(IStructureNode elem) { PdfStructElem structElem = context.GetElementIfRoleMatches(PdfName.Note, elem); if (structElem == null) { return; diff --git a/itext/itext.pdfua/itext/pdfua/checkers/utils/headings/HeadingsChecker.cs b/itext/itext.pdfua/itext/pdfua/checkers/utils/headings/HeadingsChecker.cs index ee52ffad4e..17931fb119 100644 --- a/itext/itext.pdfua/itext/pdfua/checkers/utils/headings/HeadingsChecker.cs +++ b/itext/itext.pdfua/itext/pdfua/checkers/utils/headings/HeadingsChecker.cs @@ -57,9 +57,8 @@ public HeadingsChecker(PdfUAValidationContext context) { } /// Checks if layout element has correct heading. - /// layout element to check - public void CheckLayoutElement(Object rendererObj) { - IRenderer renderer = (IRenderer)rendererObj; + /// layout element to check + public void CheckLayoutElement(IRenderer renderer) { IPropertyContainer element = renderer.GetModelElement(); if (element is IAccessibleElement) { IAccessibleElement accessibleElement = (IAccessibleElement)element; @@ -171,8 +170,11 @@ public HeadingHandler(PdfUAValidationContext context) checker = new HeadingsChecker(context); } - /// - public override void NextElement(IStructureNode elem) { + public override bool Accept(IStructureNode node) { + return node != null; + } + + public override void ProcessElement(IStructureNode elem) { checker.CheckStructElement(elem); } } diff --git a/itext/itext.pdfua/itext/pdfua/checkers/utils/tables/TableCheckUtil.cs b/itext/itext.pdfua/itext/pdfua/checkers/utils/tables/TableCheckUtil.cs index c08a51b767..5987abde9f 100644 --- a/itext/itext.pdfua/itext/pdfua/checkers/utils/tables/TableCheckUtil.cs +++ b/itext/itext.pdfua/itext/pdfua/checkers/utils/tables/TableCheckUtil.cs @@ -20,7 +20,6 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ -using System; using iText.Kernel.Pdf; using iText.Kernel.Pdf.Tagging; using iText.Layout.Element; @@ -41,17 +40,6 @@ public TableCheckUtil(PdfUAValidationContext context) { this.context = context; } - /// WARNING! This method is an artifact and currently does nothing. - /// - /// WARNING! This method is an artifact and currently does nothing. - /// It is kept to ensure backward binary compatibility - /// - /// the table to check. - [System.ObsoleteAttribute(@"This method is an artifact and will be removed.")] - public static void CheckLayoutTable(Table table) { - } - - //No impl /// Checks if the table is pdf/ua compliant. /// the table to check. public void CheckTable(Table table) { @@ -69,8 +57,11 @@ public TableHandler(PdfUAValidationContext context) : base(context) { } - /// - public override void NextElement(IStructureNode elem) { + public override bool Accept(IStructureNode node) { + return node != null; + } + + public override void ProcessElement(IStructureNode elem) { PdfStructElem table = context.GetElementIfRoleMatches(PdfName.Table, elem); if (table == null) { return; diff --git a/itext/itext.pdfua/itext/pdfua/exceptions/PdfUALogMessageConstants.cs b/itext/itext.pdfua/itext/pdfua/logs/PdfUALogMessageConstants.cs similarity index 79% rename from itext/itext.pdfua/itext/pdfua/exceptions/PdfUALogMessageConstants.cs rename to itext/itext.pdfua/itext/pdfua/logs/PdfUALogMessageConstants.cs index f2fa5476b0..18689ade4c 100644 --- a/itext/itext.pdfua/itext/pdfua/exceptions/PdfUALogMessageConstants.cs +++ b/itext/itext.pdfua/itext/pdfua/logs/PdfUALogMessageConstants.cs @@ -22,12 +22,16 @@ You should have received a copy of the GNU Affero General Public License */ using System; -namespace iText.Pdfua.Exceptions { +namespace iText.Pdfua.Logs { /// Class containing the log message constants. public sealed class PdfUALogMessageConstants { public const String PAGE_FLUSHING_DISABLED = "Page flushing is disabled in PDF/UA mode to allow UA checks " + "to be applied. Page will only be flushed on closing."; + public const String PDF_TO_PDF_UA_CONVERSION_IS_NOT_SUPPORTED = "PDF to PDF/UA conversion is not supported."; + + public const String WRITER_PROPERTIES_PDF_VERSION_WAS_OVERRIDDEN = "Pdf version from writer properties isn't compatible with specified PDF/UA conformance, it was overridden to {0} version."; + private PdfUALogMessageConstants() { } // empty constructor diff --git a/itext/itext.sign/Properties/AssemblyInfo.cs b/itext/itext.sign/Properties/AssemblyInfo.cs index 8dd96a3d2c..1087469b4e 100644 --- a/itext/itext.sign/Properties/AssemblyInfo.cs +++ b/itext/itext.sign/Properties/AssemblyInfo.cs @@ -21,6 +21,6 @@ [assembly: Guid("5092244a-a2ed-49d2-97fb-f513d965a8f7")] -[assembly: AssemblyVersion("8.0.5.0")] -[assembly: AssemblyFileVersion("8.0.5.0")] -[assembly: AssemblyInformationalVersion("8.0.5")] +[assembly: AssemblyVersion("9.0.0.0")] +[assembly: AssemblyFileVersion("9.0.0.0")] +[assembly: AssemblyInformationalVersion("9.0.0")] diff --git a/itext/itext.sign/itext.sign.csproj b/itext/itext.sign/itext.sign.csproj index ff6678b37a..b1f45cc7a4 100644 --- a/itext/itext.sign/itext.sign.csproj +++ b/itext/itext.sign/itext.sign.csproj @@ -25,6 +25,7 @@ + diff --git a/itext/itext.sign/itext/signatures/AsymmetricAlgorithmSignature.cs b/itext/itext.sign/itext/signatures/AsymmetricAlgorithmSignature.cs index f115966621..c912fd6154 100644 --- a/itext/itext.sign/itext/signatures/AsymmetricAlgorithmSignature.cs +++ b/itext/itext.sign/itext/signatures/AsymmetricAlgorithmSignature.cs @@ -22,6 +22,7 @@ You should have received a copy of the GNU Affero General Public License */ using System; using System.Security.Cryptography; +using iText.Kernel.Crypto; namespace iText.Signatures { /// diff --git a/itext/itext.sign/itext/signatures/CRLVerifier.cs b/itext/itext.sign/itext/signatures/CRLVerifier.cs index 0db6cb5759..79a2ff6010 100644 --- a/itext/itext.sign/itext/signatures/CRLVerifier.cs +++ b/itext/itext.sign/itext/signatures/CRLVerifier.cs @@ -33,7 +33,7 @@ namespace iText.Signatures { /// Class that allows you to verify a certificate against /// one or more Certificate Revocation Lists. /// - [System.ObsoleteAttribute(@"starting from 8.0.5.iText.Signatures.Validation.V1.CRLValidator should be used instead." + [System.ObsoleteAttribute(@"starting from 8.0.5.iText.Signatures.Validation.CRLValidator should be used instead." )] public class CRLVerifier : RootStoreVerifier { /// The Logger instance @@ -129,12 +129,12 @@ public virtual bool Verify(IX509Crl crl, IX509Certificate signCert, IX509Certifi public virtual IX509Crl GetCRL(IX509Certificate signCert, IX509Certificate issuerCert) { try { // gets the URL from the certificate - String crlurl = CertificateUtil.GetCRLURL(signCert); - if (crlurl == null) { + IList crlurl = CertificateUtil.GetCRLURLs(signCert); + if (crlurl.IsEmpty()) { return null; } - LOGGER.LogInformation("Getting CRL from " + crlurl); - return (IX509Crl)SignUtils.ParseCrlFromStream(UrlUtil.OpenStream(new Uri(crlurl))); + LOGGER.LogInformation("Getting CRL from " + crlurl[0]); + return (IX509Crl)SignUtils.ParseCrlFromStream(UrlUtil.OpenStream(new Uri(crlurl[0]))); } catch (System.IO.IOException) { return null; diff --git a/itext/itext.sign/itext/signatures/CertificateInfo.cs b/itext/itext.sign/itext/signatures/CertificateInfo.cs index 5ba382d26f..a3ef2db9f9 100644 --- a/itext/itext.sign/itext/signatures/CertificateInfo.cs +++ b/itext/itext.sign/itext/signatures/CertificateInfo.cs @@ -138,7 +138,7 @@ static X500Name() { } /// A Map with values. - public IDictionary> values = new Dictionary>(); + private readonly IDictionary> values = new Dictionary>(); /// Constructs an X509 name. /// an ASN1 Sequence diff --git a/itext/itext.sign/itext/signatures/CertificateUtil.cs b/itext/itext.sign/itext/signatures/CertificateUtil.cs index 4a38d4e2a6..098dc39770 100644 --- a/itext/itext.sign/itext/signatures/CertificateUtil.cs +++ b/itext/itext.sign/itext/signatures/CertificateUtil.cs @@ -36,6 +36,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Security; using iText.Commons.Utils; using iText.IO.Util; +using iText.Kernel.Crypto; using iText.Signatures.Logs; namespace iText.Signatures { @@ -49,14 +50,6 @@ public class CertificateUtil { private static readonly ILogger LOGGER = ITextLogManager.GetLogger(typeof(CertificateUtil)); // Certificate Revocation Lists - /// Gets a CRL from an X509 certificate. - /// the X509Certificate to extract the CRL from - /// CRL or null if there's no CRL available - [System.ObsoleteAttribute(@"use GetCRLs(iText.Commons.Bouncycastle.Cert.IX509Certificate) .")] - public static IX509Crl GetCRL(IX509Certificate certificate) { - return CertificateUtil.GetCRL(CertificateUtil.GetCRLURL(certificate)); - } - /// Gets a CRLs from the X509 certificate. /// the X509Certificate to extract the CRLs from /// CRL list or null if there's no CRL available @@ -68,15 +61,6 @@ public static IList GetCRLs(IX509Certificate certificate) { return crls; } - /// Gets the URL of the Certificate Revocation List for a Certificate - /// the Certificate - /// the String where you can check if the certificate was revoked. - [System.ObsoleteAttribute(@"use GetCRLURLs(iText.Commons.Bouncycastle.Cert.IX509Certificate) .")] - public static String GetCRLURL(IX509Certificate certificate) { - IList urls = GetCRLURLs(certificate); - return urls.IsEmpty() ? null : urls[0]; - } - /// Gets the list of the Certificate Revocation List URLs for a Certificate. /// the Certificate to get CRL URLs for /// the list of URL strings where you can check if the certificate is revoked. @@ -161,7 +145,7 @@ public static String GetIssuerCertURL(IX509Crl crl) { IAsn1Object obj; try { obj = GetExtensionValue(crl, FACTORY.CreateExtensions().GetAuthorityInfoAccess().GetId()); - return GetValueFromAIAExtension(obj, SecurityIDs.ID_CA_ISSUERS); + return GetValueFromAIAExtension(obj, OID.CA_ISSUERS); } catch (System.IO.IOException) { return null; @@ -176,7 +160,7 @@ public static String GetOCSPURL(IX509Certificate certificate) { IAsn1Object obj; try { obj = GetExtensionValue(certificate, FACTORY.CreateExtensions().GetAuthorityInfoAccess().GetId()); - return GetValueFromAIAExtension(obj, SecurityIDs.ID_OCSP); + return GetValueFromAIAExtension(obj, OID.OCSP); } catch (System.IO.IOException) { return null; @@ -191,7 +175,7 @@ public static String GetIssuerCertURL(IX509Certificate certificate) { IAsn1Object obj; try { obj = GetExtensionValue(certificate, FACTORY.CreateExtensions().GetAuthorityInfoAccess().GetId()); - return GetValueFromAIAExtension(obj, SecurityIDs.ID_CA_ISSUERS); + return GetValueFromAIAExtension(obj, OID.CA_ISSUERS); } catch (System.IO.IOException) { return null; @@ -203,7 +187,7 @@ public static String GetIssuerCertURL(IX509Certificate certificate) { /// a certificate /// a TSA URL public static String GetTSAURL(IX509Certificate certificate) { - byte[] der = SignUtils.GetExtensionValueByOid(certificate, SecurityIDs.ID_TSA); + byte[] der = SignUtils.GetExtensionValueByOid(certificate, OID.TSA); if (der == null) { return null; } @@ -251,7 +235,7 @@ public static void RetrieveRevocationInfoFromSignedData(IAsn1TaggedObject tagged while (revInfo.MoveNext()) { IAsn1Sequence s = FACTORY.CreateASN1Sequence(revInfo.Current); IDerObjectIdentifier o = FACTORY.CreateASN1ObjectIdentifier(s.GetObjectAt(0)); - if (o != null && SecurityIDs.ID_RI_OCSP_RESPONSE.Equals(o.GetId())) { + if (o != null && OID.RI_OCSP_RESPONSE.Equals(o.GetId())) { IAsn1Sequence ocspResp = FACTORY.CreateASN1Sequence(s.GetObjectAt(1)); IDerEnumerated respStatus = FACTORY.CreateASN1Enumerated(ocspResp.GetObjectAt(0)); if (respStatus.IntValueExact() == FACTORY.CreateOCSPResponseStatus().GetSuccessful()) { @@ -303,7 +287,7 @@ public static void RetrieveRevocationInfoFromSignedData(IAsn1TaggedObject tagged /// public static IDerSet CreateRevocationInfoChoices(ICollection crls, ICollection ocsps, ICollection otherRevocationInfoFormats) { - if (crls.Count == 0 && ocsps.Count == 0) { + if (crls.IsEmpty() && ocsps.IsEmpty()) { return null; } IAsn1EncodableVector revocationInfoChoices = FACTORY.CreateASN1EncodableVector(); @@ -316,7 +300,7 @@ public static IDerSet CreateRevocationInfoChoices(ICollection crls, IC foreach (IBasicOcspResponse element in ocsps) { IAsn1EncodableVector ocspResponseRevInfo = FACTORY.CreateASN1EncodableVector(); // Add otherRevInfoFormat (ID_RI_OCSP_RESPONSE) - ocspResponseRevInfo.Add(FACTORY.CreateASN1ObjectIdentifier(SecurityIDs.ID_RI_OCSP_RESPONSE)); + ocspResponseRevInfo.Add(FACTORY.CreateASN1ObjectIdentifier(OID.RI_OCSP_RESPONSE)); IAsn1EncodableVector ocspResponse = FACTORY.CreateASN1EncodableVector(); ocspResponse.Add(FACTORY.CreateOCSPResponseStatus(FACTORY.CreateOCSPResponseStatus().GetSuccessful()).ToASN1Primitive ()); diff --git a/itext/itext.sign/itext/signatures/CertificateVerification.cs b/itext/itext.sign/itext/signatures/CertificateVerification.cs index 5d6ac365b8..ad9c99d81a 100644 --- a/itext/itext.sign/itext/signatures/CertificateVerification.cs +++ b/itext/itext.sign/itext/signatures/CertificateVerification.cs @@ -28,11 +28,14 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Cert; using iText.Commons.Bouncycastle.Tsp; using iText.Commons.Utils; +using iText.Kernel.Crypto; using iText.Signatures.Exceptions; using iText.Signatures.Logs; namespace iText.Signatures { /// This class consists of some methods that allow you to verify certificates. + [System.ObsoleteAttribute(@"starting from 9.0.0.iText.Signatures.Validation.CertificateChainValidator should be used instead." + )] public class CertificateVerification { public const String HAS_UNSUPPORTED_EXTENSIONS = "Has unsupported critical extension"; @@ -62,7 +65,7 @@ public static String VerifyCertificate(IX509Certificate cert, ICollection public static String VerifyCertificate(IX509Certificate cert, ICollection crls, DateTime calendar ) { - if (SignUtils.HasUnsupportedCriticalExtension(cert)) { + if (HasUnsupportedCriticalExtension(cert)) { return CertificateVerification.HAS_UNSUPPORTED_EXTENSIONS; } try { @@ -238,6 +241,29 @@ public static bool VerifyTimestampCertificates(ITimeStampToken ts, ListCheck if the provided certificate has a critical extension that iText doesn't support. + /// X509Certificate instance to check + /// + /// + /// + /// if there are unsupported critical extensions, false if there are none + /// + protected internal static bool HasUnsupportedCriticalExtension(IX509Certificate cert) { + if (cert == null) { + throw new ArgumentException("X509Certificate can't be null."); + } + ICollection criticalExtensionsSet = cert.GetCriticalExtensionOids(); + if (criticalExtensionsSet != null) { + foreach (String oid in criticalExtensionsSet) { + if (OID.X509Extensions.SUPPORTED_CRITICAL_EXTENSIONS.Contains(oid)) { + continue; + } + return true; + } + } + return false; + } + private static void LogExceptionMessages(IList exceptionsThrown) { foreach (Exception ex in exceptionsThrown) { LOGGER.LogError(ex, ex.Message == null ? SignLogMessageConstant.EXCEPTION_WITHOUT_MESSAGE : ex.Message); diff --git a/itext/itext.sign/itext/signatures/CertificateVerifier.cs b/itext/itext.sign/itext/signatures/CertificateVerifier.cs index 297a03b6fc..bd51a95ff1 100644 --- a/itext/itext.sign/itext/signatures/CertificateVerifier.cs +++ b/itext/itext.sign/itext/signatures/CertificateVerifier.cs @@ -35,7 +35,7 @@ namespace iText.Signatures { /// that is the next element in the chain of which the verify() /// method will be called. /// - [System.ObsoleteAttribute(@"starting from 8.0.5.iText.Signatures.Validation.V1.CertificateChainValidator should be used instead." + [System.ObsoleteAttribute(@"starting from 8.0.5.iText.Signatures.Validation.CertificateChainValidator should be used instead." )] public class CertificateVerifier { /// The previous CertificateVerifier in the chain of verifiers. diff --git a/itext/itext.sign/itext/signatures/DefaultIssuingCertificateRetriever.cs b/itext/itext.sign/itext/signatures/DefaultIssuingCertificateRetriever.cs index 4afd4f6920..9e152d182c 100644 --- a/itext/itext.sign/itext/signatures/DefaultIssuingCertificateRetriever.cs +++ b/itext/itext.sign/itext/signatures/DefaultIssuingCertificateRetriever.cs @@ -66,6 +66,10 @@ public virtual IX509Certificate[] GetCrlIssuerCertificates(IX509Crl crl) { return new IX509Certificate[0]; } + public virtual IX509Certificate[][] GetCrlIssuerCertificatesByName(IX509Crl crl) { + return new IX509Certificate[0][]; + } + /// /// /// diff --git a/itext/itext.sign/itext/signatures/IIssuingCertificateRetriever.cs b/itext/itext.sign/itext/signatures/IIssuingCertificateRetriever.cs index 403414c66a..ba3005e74e 100644 --- a/itext/itext.sign/itext/signatures/IIssuingCertificateRetriever.cs +++ b/itext/itext.sign/itext/signatures/IIssuingCertificateRetriever.cs @@ -39,14 +39,23 @@ public interface IIssuingCertificateRetriever { IX509Certificate[] RetrieveMissingCertificates(IX509Certificate[] chain); /// - /// Retrieves certificates that can be used to verify the signature on the CRL response using CRL - /// Authority Information Access (AIA) Extension. + /// Retrieves the certificate chain for the certificate that should be used to verify the signature on the + /// CRL response using CRL Authority Information Access (AIA) Extension and known certificates. /// /// CRL response to retrieve issuer for. /// certificates retrieved from CRL AIA extension or an empty list in case certificates cannot be retrieved. /// IX509Certificate[] GetCrlIssuerCertificates(IX509Crl crl); + /// + /// Retrieves the certificate chaind for the certificates that could be used to verify the signature on the + /// CRL response using CRL Authority Information Access (AIA) Extension and known certificates. + /// + /// CRL response to retrieve issuer for. + /// certificates retrieved from CRL AIA extension or an empty list in case certificates cannot be retrieved. + /// + IX509Certificate[][] GetCrlIssuerCertificatesByName(IX509Crl crl); + /// Sets trusted certificate list to be used for the missing certificates retrieving by the issuer name. /// /// diff --git a/itext/itext.sign/itext/signatures/ITSAClient.cs b/itext/itext.sign/itext/signatures/ITSAClient.cs index 017a9eff5e..512e125cd0 100644 --- a/itext/itext.sign/itext/signatures/ITSAClient.cs +++ b/itext/itext.sign/itext/signatures/ITSAClient.cs @@ -20,7 +20,7 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ -using iText.Commons.Bouncycastle.Crypto; +using iText.Commons.Digest; namespace iText.Signatures { /// Time Stamp Authority client (caller) interface. @@ -47,15 +47,15 @@ public interface ITSAClient { /// /// Returns the - /// + /// /// to digest the data imprint /// /// /// The - /// + /// /// object. /// - IDigest GetMessageDigest(); + IMessageDigest GetMessageDigest(); /// Returns RFC 3161 timeStampToken. /// byte[] - data imprint to be time-stamped diff --git a/itext/itext.sign/itext/signatures/IssuingCertificateRetriever.cs b/itext/itext.sign/itext/signatures/IssuingCertificateRetriever.cs index e81155031d..cc21beb6de 100644 --- a/itext/itext.sign/itext/signatures/IssuingCertificateRetriever.cs +++ b/itext/itext.sign/itext/signatures/IssuingCertificateRetriever.cs @@ -24,11 +24,15 @@ You should have received a copy of the GNU Affero General Public License using System.Collections.Generic; using System.IO; using Microsoft.Extensions.Logging; +using iText.Bouncycastleconnector; using iText.Commons; +using iText.Commons.Bouncycastle; using iText.Commons.Bouncycastle.Asn1.Ocsp; using iText.Commons.Bouncycastle.Cert; +using iText.Commons.Utils; +using iText.Commons.Utils.Collections; using iText.Signatures.Logs; -using iText.Signatures.Validation.V1; +using iText.Signatures.Validation; namespace iText.Signatures { /// @@ -36,13 +40,15 @@ namespace iText.Signatures { /// default implementation. /// public class IssuingCertificateRetriever : IIssuingCertificateRetriever { + private static readonly IBouncyCastleFactory FACTORY = BouncyCastleFactoryCreator.GetFactory(); + private static readonly ILogger LOGGER = ITextLogManager.GetLogger(typeof(iText.Signatures.IssuingCertificateRetriever )); private readonly TrustedCertificatesStore trustedCertificatesStore = new TrustedCertificatesStore(); - private readonly IDictionary knownCertificates = new Dictionary(); + private readonly IDictionary> knownCertificates = new Dictionary>(); /// /// Creates @@ -80,10 +86,11 @@ public virtual IX509Certificate[] RetrieveMissingCertificates(IX509Certificate[] ICollection certificatesFromAIA = ProcessCertificatesFromAIA(url); if (certificatesFromAIA == null || certificatesFromAIA.IsEmpty()) { // Retrieve Issuer from the certificate store - IX509Certificate issuer = trustedCertificatesStore.GetKnownCertificate(lastAddedCert.GetIssuerDN().ToString - ()); - if (issuer == null) { - issuer = knownCertificates.Get(lastAddedCert.GetIssuerDN().ToString()); + IX509Certificate issuer = GetIssuerFromCertificateSet(lastAddedCert, trustedCertificatesStore.GetKnownCertificates + (lastAddedCert.GetIssuerDN().ToString())); + if (issuer == null || !IsSignedBy(lastAddedCert, issuer)) { + issuer = GetIssuerFromCertificateSet(lastAddedCert, knownCertificates.Get(lastAddedCert.GetIssuerDN().ToString + ())); if (issuer == null) { // Unable to retrieve missing certificates while (i < chain.Length) { @@ -104,6 +111,97 @@ public virtual IX509Certificate[] RetrieveMissingCertificates(IX509Certificate[] return fullChain.ToArray(new IX509Certificate[0]); } + /// This method tries to rebuild certificate issuer chain. + /// + /// This method tries to rebuild certificate issuer chain. The result contains all possible chains + /// starting with the given certificate based on issuer names and public keys. + /// + /// + /// + /// + /// for which issuer chains shall be built + /// + /// all possible issuer chains + public virtual IList BuildCertificateChains(IX509Certificate certificate) { + return BuildCertificateChains(new IX509Certificate[] { certificate }); + } + + /// This method tries to rebuild certificate issuer chain. + /// + /// This method tries to rebuild certificate issuer chain. The result contains all possible chains + /// starting with the given certificate array based on issuer names and public keys. + /// + /// + /// + /// + /// array for which issuer chains shall be built + /// + /// all possible issuer chains + public virtual IList BuildCertificateChains(IX509Certificate[] certificate) { + IList> allCertificateChains = BuildCertificateChainsList(certificate); + IList result = new List(allCertificateChains.Count * 5); + foreach (IList chain in allCertificateChains) { + JavaCollectionsUtil.Reverse(chain); + result.Add(chain.ToArray(new IX509Certificate[0])); + } + return result; + } + + private IList> BuildCertificateChainsList(IX509Certificate[] certificates) { + IList> allChains = new List>(BuildCertificateChainsList(certificates + [certificates.Length - 1])); + foreach (IList issuerChain in allChains) { + for (int i = certificates.Length - 2; i >= 0; --i) { + issuerChain.Add(certificates[i]); + } + } + return allChains; + } + + private IList> BuildCertificateChainsList(IX509Certificate certificate) { + if (CertificateUtil.IsSelfSigned(certificate)) { + IList> singleChain = new List>(); + IList chain = new List(); + chain.Add(certificate); + singleChain.Add(chain); + return singleChain; + } + IList> allChains = new List>(); + // Get missing certificates using AIA Extensions + String url = CertificateUtil.GetIssuerCertURL(certificate); + ICollection certificatesFromAIA = ProcessCertificatesFromAIA(url); + if (certificatesFromAIA != null && !certificatesFromAIA.IsEmpty()) { + IList> issuerChains = BuildCertificateChainsList(certificatesFromAIA.ToArray(new IX509Certificate + [0])); + foreach (IList issuerChain in issuerChains) { + issuerChain.Add(certificate); + allChains.Add(issuerChain); + } + } + else { + ICollection possibleIssuers = trustedCertificatesStore.GetKnownCertificates(certificate. + GetIssuerDN().ToString()); + if (knownCertificates.Get(certificate.GetIssuerDN().ToString()) != null) { + possibleIssuers.AddAll(knownCertificates.Get(certificate.GetIssuerDN().ToString())); + } + if (possibleIssuers.IsEmpty()) { + IList> singleChain = new List>(); + IList chain = new List(); + chain.Add(certificate); + singleChain.Add(chain); + return singleChain; + } + foreach (IX509Certificate possibleIssuer in possibleIssuers) { + IList> issuerChains = BuildCertificateChainsList((IX509Certificate)possibleIssuer); + foreach (IList issuerChain in issuerChains) { + issuerChain.Add(certificate); + allChains.Add(issuerChain); + } + } + } + return allChains; + } + /// Retrieve issuer certificate for the provided certificate. /// /// @@ -115,51 +213,41 @@ public virtual IX509Certificate[] RetrieveMissingCertificates(IX509Certificate[] /// /// if there is no issuer certificate, or it cannot be retrieved. /// - public virtual IX509Certificate RetrieveIssuerCertificate(IX509Certificate certificate) { - IX509Certificate[] certificateChain = RetrieveMissingCertificates(new IX509Certificate[] { certificate }); - if (certificateChain.Length > 1) { - return certificateChain[1]; + public virtual IList RetrieveIssuerCertificate(IX509Certificate certificate) { + IList result = new List(); + foreach (IX509Certificate[] certificateChain in BuildCertificateChains((IX509Certificate)certificate)) { + if (certificateChain.Length > 1) { + result.Add(certificateChain[1]); + } } - return null; + return result; } /// - /// Retrieves OCSP responder certificate either from the response certs or + /// Retrieves OCSP responder certificate candidates either from the response certs or /// trusted store in case responder certificate isn't found in /Certs. /// /// basic OCSP response to get responder certificate for - /// retrieved OCSP responder certificate or null in case it wasn't found. - public virtual IX509Certificate RetrieveOCSPResponderCertificate(IBasicOcspResponse ocspResp) { + /// retrieved OCSP responder candidates or an empty set in case none were found. + public virtual ICollection RetrieveOCSPResponderByNameCertificate(IBasicOcspResponse ocspResp + ) { + String name = null; + name = FACTORY.CreateX500Name(FACTORY.CreateASN1Sequence(ocspResp.GetResponderId().ToASN1Primitive().GetName + ().ToASN1Primitive())).GetName(); // Look for the existence of an Authorized OCSP responder inside the cert chain in the ocsp response. IEnumerable certs = SignUtils.GetCertsFromOcspResponse(ocspResp); foreach (IX509Certificate cert in certs) { try { - if (CertificateUtil.IsSignatureValid(ocspResp, cert)) { - return cert; + if (name.Equals(cert.GetSubjectDN().ToString())) { + return JavaCollectionsUtil.Singleton(cert); } } catch (Exception) { } } // Ignore. - // Certificate chain is not present in the response. - // Try to verify using trusted store according to RFC 6960 2.2. Response: - // "The key used to sign the response MUST belong to one of the following: - // - ... - // - a Trusted Responder whose public key is trusted by the requester; - // - ..." - try { - foreach (IX509Certificate anchor in trustedCertificatesStore.GetAllTrustedCertificates()) { - if (CertificateUtil.IsSignatureValid(ocspResp, anchor)) { - // Certificate from the root store is considered trusted and valid by this method. - return anchor; - } - } - } - catch (Exception) { - } - // Ignore. - return null; + // Certificate chain is not present in the response, or is does not contain the responder. + return trustedCertificatesStore.GetKnownCertificates(name); } /// @@ -172,27 +260,59 @@ public virtual IX509Certificate RetrieveOCSPResponderCertificate(IBasicOcspRespo /// /// public virtual IX509Certificate[] GetCrlIssuerCertificates(IX509Crl crl) { + IX509Certificate[][] result = GetCrlIssuerCertificatesGeneric(crl, true); + if (result.Length == 0) { + return new IX509Certificate[0]; + } + return result[0]; + } + + /// + /// + /// + /// + /// + /// + /// + /// + /// + public virtual IX509Certificate[][] GetCrlIssuerCertificatesByName(IX509Crl crl) { + return GetCrlIssuerCertificatesGeneric(crl, false); + } + + private IX509Certificate[][] GetCrlIssuerCertificatesGeneric(IX509Crl crl, bool verify) { // Usually CRLs are signed using CA certificate, so we don’t need to do anything extra and the revocation data // is already collected. However, it is possible to sign it with any other certificate. // IssuingDistributionPoint extension: https://datatracker.ietf.org/doc/html/rfc5280#section-5.2.5 // Nothing special for the indirect CRLs. // AIA Extension + List matches = new List(); String url = CertificateUtil.GetIssuerCertURL(crl); IList certificatesFromAIA = (IList)ProcessCertificatesFromAIA(url); if (certificatesFromAIA == null) { // Retrieve Issuer from the certificate store - IX509Certificate issuer = trustedCertificatesStore.GetKnownCertificate(((IX509Crl)crl).GetIssuerDN().ToString - ()); - if (issuer == null) { - issuer = knownCertificates.Get(((IX509Crl)crl).GetIssuerDN().ToString()); - if (issuer == null) { - // Unable to retrieve CRL issuer - return new IX509Certificate[0]; + ICollection issuers = trustedCertificatesStore.GetKnownCertificates(((IX509Crl)crl).GetIssuerDN + ().ToString()); + if (issuers == null) { + issuers = new HashSet(); + } + IList localIssuers = GetCrlIssuersFromKnownCertificates((IX509Crl)crl); + if (localIssuers != null) { + issuers.AddAll(localIssuers); + } + if (issuers.IsEmpty()) { + // Unable to retrieve CRL issuer + return new IX509Certificate[0][]; + } + foreach (IX509Certificate i in issuers) { + if (!verify || IsSignedBy((IX509Crl)crl, i)) { + matches.AddAll(BuildCertificateChains((IX509Certificate)i)); } } - return RetrieveMissingCertificates(new IX509Certificate[] { issuer }); + return matches.ToArray(new IX509Certificate[][] { }); } - return RetrieveMissingCertificates(certificatesFromAIA.ToArray(new IX509Certificate[0])); + return BuildCertificateChains(certificatesFromAIA.ToArray(new IX509Certificate[0])).ToArray(new IX509Certificate + [][] { }); } /// Sets trusted certificate list to be used as certificates trusted for any possible usage. @@ -226,18 +346,21 @@ public virtual void AddTrustedCertificates(ICollection certifi /// public virtual void AddKnownCertificates(ICollection certificates) { foreach (IX509Certificate certificate in certificates) { - knownCertificates.Put(((IX509Certificate)certificate).GetSubjectDN().ToString(), certificate); + String name = ((IX509Certificate)certificate).GetSubjectDN().ToString(); + IList certs = knownCertificates.ComputeIfAbsent(name, (k) => new List( + )); + certs.Add(certificate); } } /// /// Gets - /// + /// /// to be used to provide more complex trusted certificates configuration. /// /// /// - /// + /// /// storage /// public virtual TrustedCertificatesStore GetTrustedCertificatesStore() { @@ -301,5 +424,41 @@ private ICollection ProcessCertificatesFromAIA(String url) { return null; } } + + private static bool IsSignedBy(IX509Certificate certificate, IX509Certificate issuer) { + try { + certificate.Verify(issuer.GetPublicKey()); + return true; + } + catch (Exception) { + return false; + } + } + + private static bool IsSignedBy(IX509Crl crl, IX509Certificate issuer) { + try { + crl.Verify(issuer.GetPublicKey()); + return true; + } + catch (Exception) { + return false; + } + } + + private static IX509Certificate GetIssuerFromCertificateSet(IX509Certificate lastAddedCert, ICollection certs) { + if (certs != null) { + foreach (IX509Certificate cert in certs) { + if (IsSignedBy(lastAddedCert, cert)) { + return cert; + } + } + } + return null; + } + + private IList GetCrlIssuersFromKnownCertificates(IX509Crl crl) { + return knownCertificates.Get(crl.GetIssuerDN().ToString()); + } } } diff --git a/itext/itext.sign/itext/signatures/LtvVerification.cs b/itext/itext.sign/itext/signatures/LtvVerification.cs index e7e9a151fe..18b852fb2d 100644 --- a/itext/itext.sign/itext/signatures/LtvVerification.cs +++ b/itext/itext.sign/itext/signatures/LtvVerification.cs @@ -36,6 +36,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Utils; using iText.IO.Font; using iText.IO.Source; +using iText.Kernel.Crypto; using iText.Kernel.Exceptions; using iText.Kernel.Pdf; using iText.Signatures.Exceptions; @@ -211,10 +212,12 @@ public virtual bool AddVerification(String signatureName, IOcspClient ocsp, ICrl } if (certInclude == LtvVerification.CertificateInclusion.YES) { foreach (IX509Certificate processedCert in processedCerts) { - validationData.certs.Add(processedCert.GetEncoded()); + IList certs = validationData.GetCerts(); + certs.Add(processedCert.GetEncoded()); + validationData.SetCerts(certs); } } - if (validationData.crls.Count == 0 && validationData.ocsps.Count == 0) { + if (validationData.GetCrls().IsEmpty() && validationData.GetOcsps().IsEmpty()) { return false; } validated.Put(GetSignatureHashKey(signatureName), validationData); @@ -235,14 +238,20 @@ public virtual bool AddVerification(String signatureName, ICollection oc LtvVerification.ValidationData vd = new LtvVerification.ValidationData(); if (ocsps != null) { foreach (byte[] ocsp in ocsps) { - vd.ocsps.Add(LtvVerification.BuildOCSPResponse(ocsp)); + IList ocspsArr = vd.GetOcsps(); + ocspsArr.Add(LtvVerification.BuildOCSPResponse(ocsp)); + vd.SetOcsps(ocspsArr); } } if (crls != null) { - vd.crls.AddAll(crls); + IList crlsArr = vd.GetCrls(); + crlsArr.AddAll(crls); + vd.SetCrls(crlsArr); } if (certs != null) { - vd.certs.AddAll(certs); + IList certsArr = vd.GetCerts(); + certsArr.AddAll(certs); + vd.SetCerts(certsArr); } validated.Put(GetSignatureHashKey(signatureName), vd); return true; @@ -250,7 +259,7 @@ public virtual bool AddVerification(String signatureName, ICollection oc /// Merges the validation with any validation already in the document or creates a new one. public virtual void Merge() { - if (used || validated.Count == 0) { + if (used || validated.IsEmpty()) { return; } used = true; @@ -336,7 +345,9 @@ private void AddRevocationDataForCertificate(IX509Certificate signingCert, IX509 ocspEnc = ocsp.GetEncoded(cert, GetParent(cert, certificateChain), null); if (ocspEnc != null && BOUNCY_CASTLE_FACTORY.CreateCertificateStatus().GetGood().Equals(OcspClientBouncyCastle .GetCertificateStatus(ocspEnc))) { - validationData.ocsps.Add(LtvVerification.BuildOCSPResponse(ocspEnc)); + IList ocsps = validationData.GetOcsps(); + ocsps.Add(LtvVerification.BuildOCSPResponse(ocspEnc)); + validationData.SetOcsps(ocsps); revocationDataAdded = true; LOGGER.LogInformation("OCSP added"); if (certOption == LtvVerification.CertificateOption.ALL_CERTIFICATES) { @@ -353,16 +364,18 @@ private void AddRevocationDataForCertificate(IX509Certificate signingCert, IX509 ICollection cims = crl.GetEncoded(cert, null); if (cims != null) { foreach (byte[] cim in cims) { + revocationDataAdded = true; bool dup = false; - foreach (byte[] b in validationData.crls) { + foreach (byte[] b in validationData.GetCrls()) { if (JavaUtil.ArraysEquals(b, cim)) { dup = true; break; } } if (!dup) { - validationData.crls.Add(cim); - revocationDataAdded = true; + IList crls = validationData.GetCrls(); + crls.Add(cim); + validationData.SetCrls(crls); LOGGER.LogInformation("CRL added"); if (certOption == LtvVerification.CertificateOption.ALL_CERTIFICATES) { IX509Certificate[] certsList = issuingCertificateRetriever.GetCrlIssuerCertificates(SignUtils.ParseCrlFromStream @@ -513,7 +526,7 @@ private void OutputDss(PdfDictionary dss, PdfDictionary vrim, PdfArray ocsps, Pd PdfArray crl = new PdfArray(); PdfArray cert = new PdfArray(); PdfDictionary vri = new PdfDictionary(); - foreach (byte[] b in validated.Get(vkey).crls) { + foreach (byte[] b in validated.Get(vkey).GetCrls()) { PdfStream ps = new PdfStream(b); ps.SetCompressionLevel(CompressionConstants.DEFAULT_COMPRESSION); ps.MakeIndirect(document); @@ -521,14 +534,14 @@ private void OutputDss(PdfDictionary dss, PdfDictionary vrim, PdfArray ocsps, Pd crls.Add(ps); crls.SetModified(); } - foreach (byte[] b in validated.Get(vkey).ocsps) { + foreach (byte[] b in validated.Get(vkey).GetOcsps()) { PdfStream ps = new PdfStream(b); ps.SetCompressionLevel(CompressionConstants.DEFAULT_COMPRESSION); ocsp.Add(ps); ocsps.Add(ps); ocsps.SetModified(); } - foreach (byte[] b in validated.Get(vkey).certs) { + foreach (byte[] b in validated.Get(vkey).GetCerts()) { PdfStream ps = new PdfStream(b); ps.SetCompressionLevel(CompressionConstants.DEFAULT_COMPRESSION); ps.MakeIndirect(document); @@ -536,15 +549,15 @@ private void OutputDss(PdfDictionary dss, PdfDictionary vrim, PdfArray ocsps, Pd certs.Add(ps); certs.SetModified(); } - if (ocsp.Size() > 0) { + if (!ocsp.IsEmpty()) { ocsp.MakeIndirect(document); vri.Put(PdfName.OCSP, ocsp); } - if (crl.Size() > 0) { + if (!crl.IsEmpty()) { crl.MakeIndirect(document); vri.Put(PdfName.CRL, crl); } - if (cert.Size() > 0) { + if (!cert.IsEmpty()) { cert.MakeIndirect(document); vri.Put(PdfName.Cert, cert); } @@ -554,15 +567,15 @@ private void OutputDss(PdfDictionary dss, PdfDictionary vrim, PdfArray ocsps, Pd vrim.MakeIndirect(document); vrim.SetModified(); dss.Put(PdfName.VRI, vrim); - if (ocsps.Size() > 0) { + if (!ocsps.IsEmpty()) { ocsps.MakeIndirect(document); dss.Put(PdfName.OCSPs, ocsps); } - if (crls.Size() > 0) { + if (!crls.IsEmpty()) { crls.MakeIndirect(document); dss.Put(PdfName.CRLs, crls); } - if (certs.Size() > 0) { + if (!certs.IsEmpty()) { certs.MakeIndirect(document); dss.Put(PdfName.Certs, certs); } @@ -572,11 +585,47 @@ private void OutputDss(PdfDictionary dss, PdfDictionary vrim, PdfArray ocsps, Pd } private class ValidationData { - public IList crls = new List(); + private IList crls = new List(); - public IList ocsps = new List(); + private IList ocsps = new List(); - public IList certs = new List(); + private IList certs = new List(); + + /// Sets the crls byte array. + /// crls + public virtual void SetCrls(IList crls) { + this.crls = crls; + } + + /// Retrieves Crls byte array. + /// crls + public virtual IList GetCrls() { + return crls; + } + + /// Sets the ocsps array. + /// ocsps + public virtual void SetOcsps(IList ocsps) { + this.ocsps = ocsps; + } + + /// Retrieves ocsps byte array. + /// ocsps + public virtual IList GetOcsps() { + return ocsps; + } + + /// Sets the certs byte array. + /// certs + public virtual void SetCerts(IList certs) { + this.certs = certs; + } + + /// Retrieves cert byte array. + /// cert + public virtual IList GetCerts() { + return certs; + } } private IX509Certificate[] RetrieveMissingCertificates(IX509Certificate[] certChain) { diff --git a/itext/itext.sign/itext/signatures/LtvVerifier.cs b/itext/itext.sign/itext/signatures/LtvVerifier.cs index b0458a7496..2410304471 100644 --- a/itext/itext.sign/itext/signatures/LtvVerifier.cs +++ b/itext/itext.sign/itext/signatures/LtvVerifier.cs @@ -39,7 +39,7 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Signatures { /// Verifies the signatures in an LTV document. - [System.ObsoleteAttribute(@"starting from 8.0.5.iText.Signatures.Validation.V1.SignatureValidator should be used instead." + [System.ObsoleteAttribute(@"starting from 8.0.5.iText.Signatures.Validation.SignatureValidator should be used instead." )] public class LtvVerifier : RootStoreVerifier { private static readonly IBouncyCastleFactory BOUNCY_CASTLE_FACTORY = BouncyCastleFactoryCreator.GetFactory diff --git a/itext/itext.sign/itext/signatures/OCSPVerifier.cs b/itext/itext.sign/itext/signatures/OCSPVerifier.cs index c928a4c47a..5aa8dcb200 100644 --- a/itext/itext.sign/itext/signatures/OCSPVerifier.cs +++ b/itext/itext.sign/itext/signatures/OCSPVerifier.cs @@ -41,7 +41,7 @@ namespace iText.Signatures { /// Class that allows you to verify a certificate against /// one or more OCSP responses. /// - [System.ObsoleteAttribute(@"starting from 8.0.5.iText.Signatures.Validation.V1.OCSPValidator should be used instead." + [System.ObsoleteAttribute(@"starting from 8.0.5.iText.Signatures.Validation.OCSPValidator should be used instead." )] public class OCSPVerifier : RootStoreVerifier { private static readonly IBouncyCastleFactory BOUNCY_CASTLE_FACTORY = BouncyCastleFactoryCreator.GetFactory diff --git a/itext/itext.sign/itext/signatures/OcspClientBouncyCastle.cs b/itext/itext.sign/itext/signatures/OcspClientBouncyCastle.cs index e72ea6ff92..d488045608 100644 --- a/itext/itext.sign/itext/signatures/OcspClientBouncyCastle.cs +++ b/itext/itext.sign/itext/signatures/OcspClientBouncyCastle.cs @@ -30,7 +30,6 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Cert; using iText.Commons.Bouncycastle.Cert.Ocsp; using iText.Commons.Bouncycastle.Math; -using iText.Commons.Utils; using iText.IO.Util; namespace iText.Signatures { @@ -43,33 +42,24 @@ public class OcspClientBouncyCastle : IOcspClient { private static readonly ILogger LOGGER = ITextLogManager.GetLogger(typeof(iText.Signatures.OcspClientBouncyCastle )); - private readonly OCSPVerifier verifier; - - /// - /// Creates - /// OcspClient. - /// - /// will be used for response verification. - [System.ObsoleteAttribute(@"starting from 8.0.5. OcspClientBouncyCastle() should be used instead. If required, iText.Commons.Bouncycastle.Asn1.Ocsp.IBasicOcspResponse can be checked using iText.Signatures.Validation.V1.OCSPValidator class." - )] - public OcspClientBouncyCastle(OCSPVerifier verifier) { - this.verifier = verifier; - } - /// /// Creates new /// /// instance. /// public OcspClientBouncyCastle() { - this.verifier = null; } + // Empty constructor in order for default one to not be removed if another one is added. /// Gets OCSP response. /// - /// Gets OCSP response. If - /// - /// was set, the response will be checked. + /// Gets OCSP response. + /// + /// If required, + /// + /// can be checked using + /// + /// class. /// /// the certificate to check /// parent certificate @@ -89,12 +79,7 @@ public virtual IBasicOcspResponse GetBasicOCSPResp(IX509Certificate checkCert, I if (ocspResponse.GetStatus() != BOUNCY_CASTLE_FACTORY.CreateOCSPResponseStatus().GetSuccessful()) { return null; } - IBasicOcspResponse basicResponse = BOUNCY_CASTLE_FACTORY.CreateBasicOCSPResponse(ocspResponse.GetResponseObject - ()); - if (verifier != null) { - verifier.IsValidResponse(basicResponse, rootCert, DateTimeUtil.GetCurrentUtcTime()); - } - return basicResponse; + return BOUNCY_CASTLE_FACTORY.CreateBasicOCSPResponse(ocspResponse.GetResponseObject()); } catch (Exception ex) { LOGGER.LogError(ex.Message); @@ -139,7 +124,6 @@ public virtual byte[] GetEncoded(IX509Certificate checkCert, IX509Certificate ro /// protected internal static IOcspRequest GenerateOCSPRequest(IX509Certificate issuerCert, IBigInteger serialNumber ) { - //Add provider BC // Generate the id for the certificate we are looking for ICertID id = SignUtils.GenerateCertificateId(issuerCert, serialNumber, BOUNCY_CASTLE_FACTORY.CreateCertificateID ().GetHashSha1()); diff --git a/itext/itext.sign/itext/signatures/PKCS7ExternalSignatureContainer.cs b/itext/itext.sign/itext/signatures/PKCS7ExternalSignatureContainer.cs index 720427a826..68e068891f 100644 --- a/itext/itext.sign/itext/signatures/PKCS7ExternalSignatureContainer.cs +++ b/itext/itext.sign/itext/signatures/PKCS7ExternalSignatureContainer.cs @@ -26,6 +26,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Bouncycastleconnector; using iText.Commons.Bouncycastle.Cert; using iText.Commons.Bouncycastle.Crypto; +using iText.Kernel.Crypto; using iText.Kernel.Exceptions; using iText.Kernel.Pdf; diff --git a/itext/itext.sign/itext/signatures/PadesTwoPhaseSigningHelper.cs b/itext/itext.sign/itext/signatures/PadesTwoPhaseSigningHelper.cs index 436198e9ae..c7078208ea 100644 --- a/itext/itext.sign/itext/signatures/PadesTwoPhaseSigningHelper.cs +++ b/itext/itext.sign/itext/signatures/PadesTwoPhaseSigningHelper.cs @@ -29,6 +29,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Cert; using iText.Commons.Digest; using iText.Commons.Utils; +using iText.Kernel.Crypto; using iText.Kernel.Exceptions; using iText.Kernel.Pdf; using iText.Signatures.Cms; @@ -396,8 +397,7 @@ public virtual void SignCMSContainerWithBaselineTProfile(IExternalSignature exte byte[] timestamp = tsaClient.GetTimeStampToken(signatureDigest); using (IAsn1InputStream tempStream = FACTORY.CreateASN1InputStream(new MemoryStream(timestamp))) { IAsn1Sequence seq = FACTORY.CreateASN1Sequence(tempStream.ReadObject()); - CmsAttribute timestampAttribute = new CmsAttribute(SecurityIDs.ID_AA_TIME_STAMP_TOKEN, FACTORY.CreateDERSet - (seq)); + CmsAttribute timestampAttribute = new CmsAttribute(OID.AA_TIME_STAMP_TOKEN, FACTORY.CreateDERSet(seq)); cmsContainer.GetSignerInfo().AddUnSignedAttribute(timestampAttribute); } try { diff --git a/itext/itext.sign/itext/signatures/PdfPKCS7.cs b/itext/itext.sign/itext/signatures/PdfPKCS7.cs index 71c0bc548c..8137d9383c 100644 --- a/itext/itext.sign/itext/signatures/PdfPKCS7.cs +++ b/itext/itext.sign/itext/signatures/PdfPKCS7.cs @@ -41,6 +41,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Math; using iText.Commons.Digest; using iText.Commons.Utils; +using iText.Kernel.Crypto; using iText.Kernel.Exceptions; using iText.Kernel.Pdf; using iText.Signatures.Exceptions; @@ -74,6 +75,9 @@ public class PdfPKCS7 { /// private readonly ICollection signedDataRevocationInfo = new List(); + private readonly IAsn1EncodableVector unsignedAttributes = BOUNCY_CASTLE_FACTORY.CreateASN1EncodableVector + (); + // Constructors for creating new signatures /// Assembles all the elements needed to create a signature, except for the data. /// the private key @@ -181,7 +185,7 @@ public PdfPKCS7(byte[] contentsKey, PdfName filterSubtype) { throw new ArgumentException(SignExceptionMessageConstant.NOT_A_VALID_PKCS7_OBJECT_NOT_A_SEQUENCE); } IDerObjectIdentifier objId = BOUNCY_CASTLE_FACTORY.CreateASN1ObjectIdentifier(signedData.GetObjectAt(0)); - if (!objId.GetId().Equals(SecurityIDs.ID_PKCS7_SIGNED_DATA)) { + if (!objId.GetId().Equals(OID.PKCS7_SIGNED_DATA)) { throw new ArgumentException(SignExceptionMessageConstant.NOT_A_VALID_PKCS7_OBJECT_NOT_SIGNED_DATA); } IAsn1Sequence content = BOUNCY_CASTLE_FACTORY.CreateASN1Sequence(BOUNCY_CASTLE_FACTORY.CreateASN1TaggedObject @@ -266,12 +270,12 @@ public PdfPKCS7(byte[] contentsKey, PdfName filterSubtype) { for (int k = 0; k < sseq.Size(); ++k) { IAsn1Sequence seq2 = BOUNCY_CASTLE_FACTORY.CreateASN1Sequence(sseq.GetObjectAt(k)); String idSeq2 = BOUNCY_CASTLE_FACTORY.CreateASN1ObjectIdentifier(seq2.GetObjectAt(0)).GetId(); - if (idSeq2.Equals(SecurityIDs.ID_MESSAGE_DIGEST)) { + if (idSeq2.Equals(OID.MESSAGE_DIGEST)) { IAsn1Set set = BOUNCY_CASTLE_FACTORY.CreateASN1Set(seq2.GetObjectAt(1)); digestAttr = BOUNCY_CASTLE_FACTORY.CreateASN1OctetString(set.GetObjectAt(0)).GetOctets(); } else { - if (idSeq2.Equals(SecurityIDs.ID_ADBE_REVOCATION)) { + if (idSeq2.Equals(OID.ADBE_REVOCATION)) { IAsn1Set setout = BOUNCY_CASTLE_FACTORY.CreateASN1Set(seq2.GetObjectAt(1)); IAsn1Sequence seqout = BOUNCY_CASTLE_FACTORY.CreateASN1Sequence(setout.GetObjectAt(0)); for (int j = 0; j < seqout.Size(); ++j) { @@ -287,7 +291,7 @@ public PdfPKCS7(byte[] contentsKey, PdfName filterSubtype) { } } else { - if (isCades && idSeq2.Equals(SecurityIDs.ID_AA_SIGNING_CERTIFICATE_V1)) { + if (isCades && idSeq2.Equals(OID.AA_SIGNING_CERTIFICATE_V1)) { IAsn1Set setout = BOUNCY_CASTLE_FACTORY.CreateASN1Set(seq2.GetObjectAt(1)); IAsn1Sequence seqout = BOUNCY_CASTLE_FACTORY.CreateASN1Sequence(setout.GetObjectAt(0)); ISigningCertificate sv2 = BOUNCY_CASTLE_FACTORY.CreateSigningCertificate(seqout); @@ -303,7 +307,7 @@ public PdfPKCS7(byte[] contentsKey, PdfName filterSubtype) { foundCades = true; } else { - if (isCades && idSeq2.Equals(SecurityIDs.ID_AA_SIGNING_CERTIFICATE_V2)) { + if (isCades && idSeq2.Equals(OID.AA_SIGNING_CERTIFICATE_V2)) { IAsn1Set setout = BOUNCY_CASTLE_FACTORY.CreateASN1Set(seq2.GetObjectAt(1)); IAsn1Sequence seqout = BOUNCY_CASTLE_FACTORY.CreateASN1Sequence(setout.GetObjectAt(0)); ISigningCertificateV2 sv2 = BOUNCY_CASTLE_FACTORY.CreateSigningCertificateV2(seqout); @@ -388,6 +392,15 @@ public PdfPKCS7(byte[] contentsKey, PdfName filterSubtype) { } } + /// Get unsigned attributes associated with this PKCS7 signature container. + /// + /// unsigned attributes as + /// + /// + public virtual IAsn1EncodableVector GetUnsignedAttributes() { + return unsignedAttributes; + } + /// Set signature policy identifier to be used during signature creation. /// /// @@ -518,15 +531,13 @@ public virtual String GetDigestAlgorithmName() { // Ed25519 and Ed448 do not allow a choice of hashing algorithm, // and ISO 32002 requires using a fixed hashing algorithm to // digest the document content - if (SecurityIDs.ID_ED25519.Equals(this.signatureMechanismOid) && !SecurityIDs.ID_SHA512.Equals(digestAlgorithmOid - )) { + if (OID.ED25519.Equals(this.signatureMechanismOid) && !OID.SHA_512.Equals(digestAlgorithmOid)) { // We compare based on OID to ensure that there are no name normalisation issues. throw new PdfException(SignExceptionMessageConstant.ALGO_REQUIRES_SPECIFIC_HASH).SetMessageParams("Ed25519" , "SHA-512", hashAlgoName); } else { - if (SecurityIDs.ID_ED448.Equals(this.signatureMechanismOid) && !SecurityIDs.ID_SHAKE256.Equals(digestAlgorithmOid - )) { + if (OID.ED448.Equals(this.signatureMechanismOid) && !OID.SHAKE_256.Equals(digestAlgorithmOid)) { throw new PdfException(SignExceptionMessageConstant.ALGO_REQUIRES_SPECIFIC_HASH).SetMessageParams("Ed448", "512-bit SHAKE256", hashAlgoName); } @@ -556,16 +567,16 @@ public virtual String GetSignatureMechanismOid() { /// the algorithm used to calculate the signature public virtual String GetSignatureMechanismName() { switch (this.signatureMechanismOid) { - case SecurityIDs.ID_ED25519: { + case OID.ED25519: { // Ed25519 and Ed448 do not involve a choice of hashing algorithm return "Ed25519"; } - case SecurityIDs.ID_ED448: { + case OID.ED448: { return "Ed448"; } - case SecurityIDs.ID_RSASSA_PSS: { + case OID.RSASSA_PSS: { // For RSASSA-PSS, the algorithm parameters dictate everything, so // there's no need to duplicate that information in the algorithm name. return "RSASSA-PSS"; @@ -674,11 +685,11 @@ private ISigner InitSignature(IPublicKey key) { } private void ConfigureSignatureMechanismParameters(ISigner signature) { - if (SecurityIDs.ID_RSASSA_PSS.Equals(this.signatureMechanismOid)) { + if (OID.RSASSA_PSS.Equals(this.signatureMechanismOid)) { IRsassaPssParameters @params = BOUNCY_CASTLE_FACTORY.CreateRSASSAPSSParams(this.signatureMechanismParameters ); String mgfOid = @params.GetMaskGenAlgorithm().GetAlgorithm().GetId(); - if (!SecurityIDs.ID_MGF1.Equals(mgfOid)) { + if (!OID.MGF1.Equals(mgfOid)) { throw new ArgumentException(SignExceptionMessageConstant.ONLY_MGF1_SUPPORTED_IN_RSASSA_PSS); } // Even though having separate digests at all "layers" is mathematically fine, @@ -824,7 +835,7 @@ public virtual byte[] GetEncodedPKCS7(byte[] secondDigest, PdfSigner.CryptoStand } // Create the contentInfo. IAsn1EncodableVector v = BOUNCY_CASTLE_FACTORY.CreateASN1EncodableVector(); - v.Add(BOUNCY_CASTLE_FACTORY.CreateASN1ObjectIdentifier(SecurityIDs.ID_PKCS7_DATA)); + v.Add(BOUNCY_CASTLE_FACTORY.CreateASN1ObjectIdentifier(OID.PKCS7_DATA)); if (encapMessageContent != null) { v.Add(BOUNCY_CASTLE_FACTORY.CreateDERTaggedObject(0, BOUNCY_CASTLE_FACTORY.CreateDEROctetString(encapMessageContent ))); @@ -878,13 +889,11 @@ public virtual byte[] GetEncodedPKCS7(byte[] secondDigest, PdfSigner.CryptoStand if (tsaClient != null) { byte[] tsImprint = tsaClient.GetMessageDigest().Digest(signatureValue); byte[] tsToken = tsaClient.GetTimeStampToken(tsImprint); - if (tsToken != null) { - IAsn1EncodableVector unauthAttributes = BuildUnauthenticatedAttributes(tsToken); - if (unauthAttributes != null) { - signerInfo.Add(BOUNCY_CASTLE_FACTORY.CreateDERTaggedObject(false, 1, BOUNCY_CASTLE_FACTORY.CreateDERSet(unauthAttributes - ))); - } - } + AddTimestampTokenToUnsignedAttributes(tsToken); + } + if (unsignedAttributes.Size() > 0) { + signerInfo.Add(BOUNCY_CASTLE_FACTORY.CreateDERTaggedObject(false, 1, BOUNCY_CASTLE_FACTORY.CreateDERSet(unsignedAttributes + ))); } // Finally build the body out of all the components above IAsn1EncodableVector body = BOUNCY_CASTLE_FACTORY.CreateASN1EncodableVector(); @@ -901,7 +910,7 @@ public virtual byte[] GetEncodedPKCS7(byte[] secondDigest, PdfSigner.CryptoStand // and return it // IAsn1EncodableVector whole = BOUNCY_CASTLE_FACTORY.CreateASN1EncodableVector(); - whole.Add(BOUNCY_CASTLE_FACTORY.CreateASN1ObjectIdentifier(SecurityIDs.ID_PKCS7_SIGNED_DATA)); + whole.Add(BOUNCY_CASTLE_FACTORY.CreateASN1ObjectIdentifier(OID.PKCS7_SIGNED_DATA)); whole.Add(BOUNCY_CASTLE_FACTORY.CreateDERTaggedObject(0, BOUNCY_CASTLE_FACTORY.CreateDERSequence(body))); MemoryStream bOut = new MemoryStream(); IDerOutputStream dout = BOUNCY_CASTLE_FACTORY.CreateASN1OutputStream(bOut); @@ -925,24 +934,18 @@ public virtual byte[] GetEncodedPKCS7(byte[] secondDigest, PdfSigner.CryptoStand /// handled by the (vendor supplied) TSA request/response interface). /// /// byte[] - time stamp token, DER encoded signedData - /// - /// - /// - /// - private IAsn1EncodableVector BuildUnauthenticatedAttributes(byte[] timeStampToken) { + private void AddTimestampTokenToUnsignedAttributes(byte[] timeStampToken) { if (timeStampToken == null) { - return null; + return; } - IAsn1EncodableVector unauthAttributes = BOUNCY_CASTLE_FACTORY.CreateASN1EncodableVector(); IAsn1EncodableVector v = BOUNCY_CASTLE_FACTORY.CreateASN1EncodableVector(); - v.Add(BOUNCY_CASTLE_FACTORY.CreateASN1ObjectIdentifier(SecurityIDs.ID_AA_TIME_STAMP_TOKEN)); + v.Add(BOUNCY_CASTLE_FACTORY.CreateASN1ObjectIdentifier(OID.AA_TIME_STAMP_TOKEN)); using (IAsn1InputStream tempstream = BOUNCY_CASTLE_FACTORY.CreateASN1InputStream(new MemoryStream(timeStampToken ))) { IAsn1Sequence seq = BOUNCY_CASTLE_FACTORY.CreateASN1Sequence(tempstream.ReadObject()); v.Add(BOUNCY_CASTLE_FACTORY.CreateDERSet(seq)); } - unauthAttributes.Add(BOUNCY_CASTLE_FACTORY.CreateDERSequence(v)); - return unauthAttributes; + unsignedAttributes.Add(BOUNCY_CASTLE_FACTORY.CreateDERSequence(v)); } // Authenticated attributes @@ -1013,12 +1016,12 @@ private IDerSet GetAuthenticatedAttributeSet(byte[] secondDigest, ICollectionSet certification level which specifies DocMDP level which is expected to be set. - /// - /// - /// - /// certification level - /// - /// - /// same instance of - /// - /// - public virtual iText.Signatures.PdfPadesSigner SetCertificationLevel(AccessPermissions accessPermissions) { - this.accessPermissions = accessPermissions; - return this; - } - - /// Set FieldMDP rules to be applied for this signature. - /// - /// - /// - /// field lock dictionary. - /// - /// - /// same instance of - /// - /// - public virtual iText.Signatures.PdfPadesSigner SetSignatureFieldLock(PdfSigFieldLock fieldLock) { - this.fieldLock = fieldLock; - return this; - } - /// Set the name to be used for timestamp signature creation. /// /// Set the name to be used for timestamp signature creation. @@ -690,8 +656,6 @@ private void PerformSignDetached(SignerProperties signerProperties, bool isFinal , IX509Certificate[] chain, ITSAClient tsaClient) { IX509Certificate[] fullChain = issuingCertificateRetriever.RetrieveMissingCertificates(chain); PdfSigner signer = CreatePdfSigner(signerProperties, isFinal); - signer.SetCertificationLevel(accessPermissions); - signer.SetFieldLockDict(fieldLock); try { signer.SignDetached(externalDigest, externalSignature, fullChain, null, null, tsaClient, estimatedSize, PdfSigner.CryptoStandard .CADES); diff --git a/itext/itext.sign/itext/signatures/PdfSignatureAppearance.cs b/itext/itext.sign/itext/signatures/PdfSignatureAppearance.cs deleted file mode 100644 index e851548178..0000000000 --- a/itext/itext.sign/itext/signatures/PdfSignatureAppearance.cs +++ /dev/null @@ -1,813 +0,0 @@ -/* -This file is part of the iText (R) project. -Copyright (c) 1998-2024 Apryse Group NV -Authors: Apryse Software. - -This program is offered under a commercial and under the AGPL license. -For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. - -AGPL licensing: -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . -*/ -using System; -using iText.Commons.Bouncycastle.Cert; -using iText.Forms.Fields; -using iText.Forms.Fields.Properties; -using iText.Forms.Form.Element; -using iText.IO.Image; -using iText.Kernel.Colors; -using iText.Kernel.Font; -using iText.Kernel.Geom; -using iText.Kernel.Pdf; -using iText.Kernel.Pdf.Xobject; -using iText.Layout.Font; -using iText.Layout.Properties; - -namespace iText.Signatures { - /// Provides convenient methods to make a signature appearance. - /// - /// Provides convenient methods to make a signature appearance. Use it in conjunction with - /// . - /// - public class PdfSignatureAppearance { - /// The document to be signed. - private readonly PdfDocument document; - - /// Signature model element. - private SignatureFieldAppearance modelElement; - - /// The page where the signature will appear. - private int page = 1; - - /// - /// The coordinates of the rectangle for a visible signature, - /// or a zero-width, zero-height rectangle for an invisible signature. - /// - private Rectangle rect; - - /// Rectangle that represent the position and dimension of the signature in the page. - private Rectangle pageRect; - - /// The rendering mode chosen for visible signatures. - private PdfSignatureAppearance.RenderingMode renderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION; - - /// The reason for signing. - private String reason = ""; - - /// The caption for the reason for signing. - private String reasonCaption = "Reason: "; - - /// Holds value of property location. - private String location = ""; - - /// The caption for the location of signing. - private String locationCaption = "Location: "; - - /// Holds value of the application that creates the signature. - private String signatureCreator = ""; - - /// The contact name of the signer. - private String contact = ""; - - /// Holds value of property signDate. - private DateTime signDate; - - /// The signing certificate. - private IX509Certificate signCertificate; - - /// The image that needs to be used for a visible signature. - private ImageData signatureGraphic = null; - - /// A background image for the text in layer 2. - private ImageData image; - - /// The scaling to be applied to the background image. - private float imageScale; - - /// The text that goes in Layer 2 of the signature appearance. - private String description; - - /// Font for the text in Layer 2. - private PdfFont font; - - /// Font provider for the text. - private FontProvider fontProvider; - - /// Font family for the text. - private String[] fontFamilyNames; - - /// Font size for the font of Layer 2. - private float fontSize = 0; - - /// Font color for the font of Layer 2. - private Color fontColor; - - /// Zero level of the signature appearance. - private PdfFormXObject n0; - - /// Second level of the signature appearance. - private PdfFormXObject n2; - - /// Indicates the field to be signed. - private String fieldName = ""; - - /// Indicates if we need to reuse the existing appearance as layer 0. - private bool reuseAppearance = false; - - // Option for backward compatibility. - private bool reuseAppearanceSet = false; - - /// Creates a PdfSignatureAppearance. - /// PdfDocument - /// Rectangle of the appearance - /// Number of the page the appearance should be on - protected internal PdfSignatureAppearance(PdfDocument document, Rectangle pageRect, int pageNumber) { - this.document = document; - this.pageRect = new Rectangle(pageRect); - this.rect = new Rectangle(pageRect.GetWidth(), pageRect.GetHeight()); - this.page = pageNumber; - } - - /// - /// Provides the page number of the signature field which this signature - /// appearance is associated with. - /// - /// - /// The page number of the signature field which this signature - /// appearance is associated with. - /// - [System.ObsoleteAttribute(@"won't be public in the next major release. Use PdfSigner.GetPageNumber() instead." - )] - public virtual int GetPageNumber() { - return page; - } - - /// - /// Sets the page number of the signature field which this signature - /// appearance is associated with. - /// - /// - /// Sets the page number of the signature field which this signature - /// appearance is associated with. Implicitly calls - /// - /// which considers page number to process the rectangle correctly. - /// - /// - /// The page number of the signature field which - /// this signature appearance is associated with. - /// - /// this instance to support fluent interface. - [System.ObsoleteAttribute(@"won't be public in the next major release. Use PdfSigner.SetPageNumber(int) instead." - )] - public virtual iText.Signatures.PdfSignatureAppearance SetPageNumber(int pageNumber) { - this.page = pageNumber; - SetPageRect(pageRect); - return this; - } - - /// - /// Provides the rectangle that represent the position and dimension - /// of the signature field in the page. - /// - /// - /// the rectangle that represent the position and dimension - /// of the signature field in the page. - /// - [System.ObsoleteAttribute(@"won't be public in the next major release. Use PdfSigner.GetPageRect() instead." - )] - public virtual Rectangle GetPageRect() { - return pageRect; - } - - /// - /// Sets the rectangle that represent the position and dimension of - /// the signature field in the page. - /// - /// - /// The rectangle that represents the position and - /// dimension of the signature field in the page. - /// - /// this instance to support fluent interface. - [System.ObsoleteAttribute(@"won't be public in the next major release. Use PdfSigner.SetPageRect(iText.Kernel.Geom.Rectangle) instead." - )] - public virtual iText.Signatures.PdfSignatureAppearance SetPageRect(Rectangle pageRect) { - this.pageRect = new Rectangle(pageRect); - this.rect = new Rectangle(pageRect.GetWidth(), pageRect.GetHeight()); - return this; - } - - /// Get Layer 0 of the appearance. - /// - /// Get Layer 0 of the appearance. - /// - /// The size of the layer is determined by the rectangle set via - /// - /// - /// layer 0. - [System.ObsoleteAttribute(@"will be deleted in the next major release. See iText.Forms.Fields.PdfSignatureFormField.SetBackgroundLayer(iText.Kernel.Pdf.Xobject.PdfFormXObject) . Note that it should be called for the field retrieved with PdfSigner.GetSignatureField() method." - )] - public virtual PdfFormXObject GetLayer0() { - if (n0 == null) { - n0 = new PdfFormXObject(rect); - n0.MakeIndirect(document); - } - return n0; - } - - /// Get Layer 2 of the appearance. - /// - /// Get Layer 2 of the appearance. - /// - /// The size of the layer is determined by the rectangle set via - /// - /// - /// layer 2. - [System.ObsoleteAttribute(@"will be deleted in the next major release. See iText.Forms.Fields.PdfSignatureFormField.SetSignatureAppearanceLayer(iText.Kernel.Pdf.Xobject.PdfFormXObject) . Note that it should be called for the field retrieved with PdfSigner.GetSignatureField() method." - )] - public virtual PdfFormXObject GetLayer2() { - if (n2 == null) { - n2 = new PdfFormXObject(rect); - n2.MakeIndirect(document); - } - return n2; - } - - /// Gets the rendering mode for this signature. - /// the rendering mode for this signature. - [System.ObsoleteAttribute(@"in favour of iText.Forms.Form.Element.SignatureFieldAppearance , rendering mode will be detected depending on specifiedsetContent method parameters." - )] - public virtual PdfSignatureAppearance.RenderingMode GetRenderingMode() { - return renderingMode; - } - - /// Sets the rendering mode for this signature. - /// the rendering mode. - /// this instance to support fluent interface. - [System.ObsoleteAttribute(@"in favour of iText.Forms.Form.Element.SignatureFieldAppearance , rendering mode will be detected depending on specifiedsetContent method parameters." - )] - public virtual iText.Signatures.PdfSignatureAppearance SetRenderingMode(PdfSignatureAppearance.RenderingMode - renderingMode) { - this.renderingMode = renderingMode; - return this; - } - - /// Returns the signing reason. - /// reason for signing. - [System.ObsoleteAttribute(@"won't be public in the next major release. Use PdfSigner.GetReason() instead." - )] - public virtual String GetReason() { - return reason; - } - - /// Sets the signing reason. - /// signing reason. - /// this instance to support fluent interface. - [System.ObsoleteAttribute(@"won't be public in the next major release. Use PdfSigner.SetReason(System.String) instead." - )] - public virtual iText.Signatures.PdfSignatureAppearance SetReason(String reason) { - this.reason = reason; - return this; - } - - /// Sets the caption for the signing reason. - /// A new signing reason caption. - /// this instance to support fluent interface. - [System.ObsoleteAttribute(@"in favour of iText.Forms.Fields.Properties.SignedAppearanceText that should be used for iText.Forms.Form.Element.SignatureFieldAppearance ." - )] - public virtual iText.Signatures.PdfSignatureAppearance SetReasonCaption(String reasonCaption) { - this.reasonCaption = reasonCaption; - return this; - } - - /// Returns the signing location. - /// signing location. - [System.ObsoleteAttribute(@"won't be public in the next major release. Use PdfSigner.GetLocation() instead." - )] - public virtual String GetLocation() { - return location; - } - - /// Sets the signing location. - /// A new signing location. - /// this instance to support fluent interface. - [System.ObsoleteAttribute(@"won't be public in the next major release. Use PdfSigner.SetLocation(System.String) instead." - )] - public virtual iText.Signatures.PdfSignatureAppearance SetLocation(String location) { - this.location = location; - return this; - } - - /// Sets the caption for the signing location. - /// A new signing location caption. - /// this instance to support fluent interface. - [System.ObsoleteAttribute(@"in favour of iText.Forms.Fields.Properties.SignedAppearanceText that should be used for iText.Forms.Form.Element.SignatureFieldAppearance ." - )] - public virtual iText.Signatures.PdfSignatureAppearance SetLocationCaption(String locationCaption) { - this.locationCaption = locationCaption; - return this; - } - - /// Returns the signature creator. - /// The signature creator. - [System.ObsoleteAttribute(@"Use PdfSigner.GetSignatureCreator() instead.")] - public virtual String GetSignatureCreator() { - return signatureCreator; - } - - /// Sets the name of the application used to create the signature. - /// A new name of the application signing a document. - /// this instance to support fluent interface. - [System.ObsoleteAttribute(@"Use PdfSigner.SetSignatureCreator(System.String) instead.")] - public virtual iText.Signatures.PdfSignatureAppearance SetSignatureCreator(String signatureCreator) { - this.signatureCreator = signatureCreator; - return this; - } - - /// Returns the signing contact. - /// The signing contact. - [System.ObsoleteAttribute(@"Use PdfSigner.GetContact() instead.")] - public virtual String GetContact() { - return contact; - } - - /// Sets the signing contact. - /// A new signing contact. - /// this instance to support fluent interface. - [System.ObsoleteAttribute(@"Use PdfSigner.SetContact(System.String) instead.")] - public virtual iText.Signatures.PdfSignatureAppearance SetContact(String contact) { - this.contact = contact; - return this; - } - - /// Sets the certificate used to provide the text in the appearance. - /// - /// Sets the certificate used to provide the text in the appearance. - /// This certificate doesn't take part in the actual signing process. - /// - /// the certificate. - /// this instance to support fluent interface. - [System.ObsoleteAttribute(@"in favour of iText.Forms.Fields.Properties.SignedAppearanceText that should be used for iText.Forms.Form.Element.SignatureFieldAppearance . Specified certificate provides signer name." - )] - public virtual iText.Signatures.PdfSignatureAppearance SetCertificate(IX509Certificate signCertificate) { - this.signCertificate = signCertificate; - return this; - } - - /// Get the signing certificate. - /// the signing certificate. - [System.ObsoleteAttribute(@"in favour of iText.Forms.Fields.Properties.SignedAppearanceText that should be used for iText.Forms.Form.Element.SignatureFieldAppearance ." - )] - public virtual IX509Certificate GetCertificate() { - return signCertificate; - } - - /// Gets the Image object to render. - /// the image. - [System.ObsoleteAttribute(@"in favour of iText.Forms.Form.Element.SignatureFieldAppearance .")] - public virtual ImageData GetSignatureGraphic() { - return signatureGraphic; - } - - /// Sets the Image object to render when Render is set to RenderingMode.GRAPHIC or RenderingMode.GRAPHIC_AND_DESCRIPTION. - /// - /// image rendered. If null the mode is defaulted to RenderingMode.DESCRIPTION - /// this instance to support fluent interface. - [System.ObsoleteAttribute(@"in favour of iText.Forms.Form.Element.SignatureFieldAppearance.SetContent(iText.IO.Image.ImageData) oriText.Forms.Form.Element.SignatureFieldAppearance.SetContent(System.String, iText.IO.Image.ImageData) ." - )] - public virtual iText.Signatures.PdfSignatureAppearance SetSignatureGraphic(ImageData signatureGraphic) { - this.signatureGraphic = signatureGraphic; - return this; - } - - /// Indicates that the existing appearances needs to be reused as a background layer. - /// is an appearances reusing flag value to set. - /// this instance to support fluent interface. - [System.ObsoleteAttribute(@"in favour of iText.Forms.Fields.PdfSignatureFormField.SetReuseAppearance(bool) . Note that it should be called for the field retrieved with PdfSigner.GetSignatureField() method." - )] - public virtual iText.Signatures.PdfSignatureAppearance SetReuseAppearance(bool reuseAppearance) { - this.reuseAppearance = reuseAppearance; - this.reuseAppearanceSet = true; - return this; - } - - /// Gets the background image for the layer 2. - /// the background image for the layer 2. - [System.ObsoleteAttribute(@"in favour of iText.Layout.ElementPropertyContainer{T}.SetBackgroundImage(iText.Layout.Properties.BackgroundImage) ." - )] - public virtual ImageData GetImage() { - return image; - } - - /// Sets the background image for the text in the layer 2. - /// the background image for the layer 2. - /// this instance to support fluent interface. - [System.ObsoleteAttribute(@"in favour of iText.Layout.ElementPropertyContainer{T}.SetBackgroundImage(iText.Layout.Properties.BackgroundImage) ." - )] - public virtual iText.Signatures.PdfSignatureAppearance SetImage(ImageData image) { - this.image = image; - return this; - } - - /// Gets the scaling to be applied to the background image. - /// the scaling to be applied to the background image. - [System.ObsoleteAttribute(@"in favour of iText.Layout.ElementPropertyContainer{T}.SetBackgroundImage(iText.Layout.Properties.BackgroundImage) ." - )] - public virtual float GetImageScale() { - return imageScale; - } - - /// Sets the scaling to be applied to the background image. - /// - /// Sets the scaling to be applied to the background image. If it's zero the image - /// will fully fill the rectangle. If it's less than zero the image will fill the rectangle but - /// will keep the proportions. If it's greater than zero that scaling will be applied. - /// In any of the cases the image will always be centered. It's zero by default. - /// - /// the scaling to be applied to the background image. - /// this instance to support fluent interface. - [System.ObsoleteAttribute(@"in favour of iText.Layout.ElementPropertyContainer{T}.SetBackgroundImage(iText.Layout.Properties.BackgroundImage) ." - )] - public virtual iText.Signatures.PdfSignatureAppearance SetImageScale(float imageScale) { - this.imageScale = imageScale; - return this; - } - - /// Sets the signature text identifying the signer. - /// - /// the signature text identifying the signer. If null or not set - /// a standard description will be used. - /// - /// this instance to support fluent interface. - [System.ObsoleteAttribute(@"in favour of iText.Forms.Form.Element.SignatureFieldAppearance .")] - public virtual iText.Signatures.PdfSignatureAppearance SetLayer2Text(String text) { - this.description = text; - return this; - } - - /// Gets the signature text identifying the signer if set by setLayer2Text(). - /// the signature text identifying the signer. - [System.ObsoleteAttribute(@"in favour of iText.Forms.Form.Element.SignatureFieldAppearance .")] - public virtual String GetLayer2Text() { - return description; - } - - /// Gets the n2 and n4 layer font. - /// the n2 and n4 layer font. - [System.ObsoleteAttribute(@"in favour of iText.Forms.Form.Element.SignatureFieldAppearance .")] - public virtual PdfFont GetLayer2Font() { - return this.font; - } - - /// Sets the n2 layer font. - /// Sets the n2 layer font. If the font size is zero, auto-fit will be used. - /// the n2 font. - /// this instance to support fluent interface. - [System.ObsoleteAttribute(@"in favour of iText.Layout.ElementPropertyContainer{T}.SetFont(iText.Kernel.Font.PdfFont) ." - )] - public virtual iText.Signatures.PdfSignatureAppearance SetLayer2Font(PdfFont font) { - this.font = font; - return this; - } - - /// Sets the n2 and n4 layer font size. - /// font size. - /// this instance to support fluent interface. - [System.ObsoleteAttribute(@"in favour of iText.Layout.ElementPropertyContainer{T}.SetFontSize(float) .")] - public virtual iText.Signatures.PdfSignatureAppearance SetLayer2FontSize(float fontSize) { - this.fontSize = fontSize; - return this; - } - - /// Gets the n2 and n4 layer font size. - /// the n2 and n4 layer font size. - [System.ObsoleteAttribute(@"in favour of iText.Forms.Form.Element.SignatureFieldAppearance .")] - public virtual float GetLayer2FontSize() { - return fontSize; - } - - /// Sets the n2 and n4 layer font color. - /// font color. - /// this instance to support fluent interface. - [System.ObsoleteAttribute(@"in favour of iText.Layout.ElementPropertyContainer{T}.SetFontColor(iText.Kernel.Colors.Color) ." - )] - public virtual iText.Signatures.PdfSignatureAppearance SetLayer2FontColor(Color color) { - this.fontColor = color; - return this; - } - - /// Gets the n2 layer font color. - /// the n2 layer font color. - [System.ObsoleteAttribute(@"in favour of iText.Forms.Form.Element.SignatureFieldAppearance .")] - public virtual Color GetLayer2FontColor() { - return fontColor; - } - - /// Gets the signature layout element. - /// the signature layout element. - public virtual SignatureFieldAppearance GetSignatureAppearance() { - if (modelElement == null) { - modelElement = new SignatureFieldAppearance(fieldName); - SetContent(); - SetFontRelatedProperties(); - ApplyBackgroundImage(); - } - else { - PopulateExistingModelElement(); - } - return modelElement; - } - - /// Sets the signature layout element. - /// the signature layout element. - /// this instance to support fluent interface. - [System.ObsoleteAttribute(@"Use PdfSigner.SetSignatureAppearance(iText.Forms.Form.Element.SignatureFieldAppearance) instead." - )] - public virtual iText.Signatures.PdfSignatureAppearance SetSignatureAppearance(SignatureFieldAppearance modelElement - ) { - this.modelElement = modelElement; - return this; - } - - /// - /// Sets - /// . - /// - /// - /// Sets - /// - /// . Note, font provider is inherited property. - /// - /// - /// the instance of - /// . - /// - /// this instance to support fluent interface. - [System.ObsoleteAttribute(@"in favour of iText.Layout.ElementPropertyContainer{T}.SetProperty(int, System.Object) ." - )] - public virtual iText.Signatures.PdfSignatureAppearance SetFontProvider(FontProvider fontProvider) { - this.fontProvider = fontProvider; - return this; - } - - /// Sets the preferable font families for the signature content. - /// - /// Sets the preferable font families for the signature content. - /// Note that - /// - /// shall be set as well. - /// - /// defines an ordered list of preferable font families for the signature element. - /// - /// this instance to support fluent interface. - [System.ObsoleteAttribute(@"in favour of iText.Layout.ElementPropertyContainer{T}.SetFontFamily(System.String[]) ." - )] - public virtual iText.Signatures.PdfSignatureAppearance SetFontFamily(params String[] fontFamilyNames) { - this.fontFamilyNames = fontFamilyNames; - return this; - } - - /// Gets the visibility status of the signature. - /// the visibility status of the signature. - [System.ObsoleteAttribute(@"won't be public in the next major release.")] - public virtual bool IsInvisible() { - return rect == null || rect.GetWidth() == 0 || rect.GetHeight() == 0; - } - - /// Constructs appearance (top-level) for a signature. - /// a top-level signature appearance. - /// Adobe Pdf Digital - /// * Signature Appearances - [System.ObsoleteAttribute(@"in favour of iText.Forms.Form.Element.SignatureFieldAppearance . Shouldn't be used." - )] - protected internal virtual PdfFormXObject GetAppearance() { - SignatureUtil signatureUtil = new SignatureUtil(document); - bool fieldExist = signatureUtil.DoesSignatureFieldExist(fieldName); - PdfSignatureFormField sigField; - if (fieldExist) { - sigField = (PdfSignatureFormField)PdfFormCreator.GetAcroForm(document, true).GetField(fieldName); - } - else { - sigField = new SignatureFormFieldBuilder(document, fieldName).SetWidgetRectangle(rect).CreateSignature(); - } - sigField.GetFirstFormAnnotation().SetFormFieldElement(GetSignatureAppearance()); - return new PdfFormXObject(sigField.GetFirstFormAnnotation().GetPdfObject().GetAsDictionary(PdfName.AP).GetAsStream - (PdfName.N)); - } - - /// Returns the signature date. - /// the signature date. - [System.ObsoleteAttribute(@"use PdfSigner.GetSignDate() instead.")] - protected internal virtual DateTime GetSignDate() { - return signDate; - } - - /// Sets the signature date. - /// A new signature date. - /// this instance to support fluent interface. - [System.ObsoleteAttribute(@"use PdfSigner.SetSignDate(System.DateTime) instead.")] - protected internal virtual iText.Signatures.PdfSignatureAppearance SetSignDate(DateTime signDate) { - this.signDate = signDate; - return this; - } - - /// Set the field name of the appearance. - /// - /// Set the field name of the appearance. Field name indicates the field to be signed if it is already presented - /// in the document (signing existing field). Required for reuseAppearance option. - /// - /// name of the field - /// this instance to support fluent interface - protected internal virtual iText.Signatures.PdfSignatureAppearance SetFieldName(String fieldName) { - this.fieldName = fieldName; - return this; - } - -//\cond DO_NOT_DOCUMENT - /// - /// Returns reuseAppearance value which indicates that the existing appearances needs to be reused - /// as a background layer. - /// - /// an appearances reusing flag value. - internal virtual bool IsReuseAppearance() { - return reuseAppearance; - } -//\endcond - -//\cond DO_NOT_DOCUMENT - /// - /// Checks if reuseAppearance value was set using - /// this#setReuseAppearance(boolean). - /// - /// - /// Checks if reuseAppearance value was set using - /// this#setReuseAppearance(boolean). - /// Used for backward compatibility. - /// - /// boolean value. - internal virtual bool IsReuseAppearanceSet() { - return reuseAppearanceSet; - } -//\endcond - -//\cond DO_NOT_DOCUMENT - /// Gets the background layer that is present when creating the signature field if it was set. - /// n0 layer xObject. - internal virtual PdfFormXObject GetBackgroundLayer() { - return n0; - } -//\endcond - -//\cond DO_NOT_DOCUMENT - /// Gets the signature appearance layer that contains information about the signature if it was set. - /// n2 layer xObject. - internal virtual PdfFormXObject GetSignatureAppearanceLayer() { - return n2; - } -//\endcond - -//\cond DO_NOT_DOCUMENT - internal virtual void ApplyBackgroundImage() { - if (image != null) { - BackgroundRepeat repeat = new BackgroundRepeat(BackgroundRepeat.BackgroundRepeatValue.NO_REPEAT); - BackgroundPosition position = new BackgroundPosition().SetPositionX(BackgroundPosition.PositionX.CENTER).SetPositionY - (BackgroundPosition.PositionY.CENTER); - BackgroundSize size = new BackgroundSize(); - float EPS = 1e-5f; - if (Math.Abs(imageScale) < EPS) { - size.SetBackgroundSizeToValues(UnitValue.CreatePercentValue(100), UnitValue.CreatePercentValue(100)); - } - else { - if (imageScale < 0) { - size.SetBackgroundSizeToContain(); - } - else { - size.SetBackgroundSizeToValues(UnitValue.CreatePointValue(imageScale * image.GetWidth()), UnitValue.CreatePointValue - (imageScale * image.GetHeight())); - } - } - modelElement.SetBackgroundImage(new BackgroundImage.Builder().SetImage(new PdfImageXObject(image)).SetBackgroundSize - (size).SetBackgroundRepeat(repeat).SetBackgroundPosition(position).Build()); - } - } -//\endcond - -//\cond DO_NOT_DOCUMENT - internal virtual SignedAppearanceText GenerateSignatureText() { - return new SignedAppearanceText().SetSignedBy(GetSignerName()).SetSignDate(signDate).SetReasonLine(reasonCaption - + reason).SetLocationLine(locationCaption + location); - } -//\endcond - - private void SetFontRelatedProperties() { - if (fontProvider != null) { - modelElement.SetProperty(Property.FONT_PROVIDER, fontProvider); - modelElement.SetFontFamily(fontFamilyNames); - } - else { - modelElement.SetFont(font); - } - modelElement.SetFontSize(fontSize); - modelElement.SetFontColor(fontColor); - } - - private void SetContent() { - if (IsInvisible()) { - return; - } - switch (renderingMode) { - case PdfSignatureAppearance.RenderingMode.GRAPHIC: { - if (signatureGraphic == null) { - throw new InvalidOperationException("A signature image must be present when rendering mode is " + "graphic and description. Use setSignatureGraphic()" - ); - } - modelElement.SetContent(signatureGraphic); - break; - } - - case PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION: { - if (signatureGraphic == null) { - throw new InvalidOperationException("A signature image must be present when rendering mode is " + "graphic and description. Use setSignatureGraphic()" - ); - } - if (description != null) { - modelElement.SetContent(description, signatureGraphic); - } - else { - modelElement.SetContent(GenerateSignatureText(), signatureGraphic); - } - break; - } - - case PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION: { - if (description != null) { - modelElement.SetContent(GetSignerName(), description); - } - else { - modelElement.SetContent(GetSignerName(), GenerateSignatureText()); - } - break; - } - - default: { - if (description != null) { - modelElement.SetContent(description); - } - else { - modelElement.SetContent(GenerateSignatureText()); - } - break; - } - } - } - - private void PopulateExistingModelElement() { - modelElement.SetSignerName(GetSignerName()); - SignedAppearanceText signedAppearanceText = modelElement.GetSignedAppearanceText(); - if (signedAppearanceText != null) { - signedAppearanceText.SetSignedBy(GetSignerName()).SetSignDate(signDate); - if (String.IsNullOrEmpty(signedAppearanceText.GetReasonLine())) { - signedAppearanceText.SetReasonLine(reasonCaption + reason); - } - if (String.IsNullOrEmpty(signedAppearanceText.GetLocationLine())) { - signedAppearanceText.SetLocationLine(locationCaption + location); - } - } - } - - private String GetSignerName() { - String name = null; - CertificateInfo.X500Name x500name = CertificateInfo.GetSubjectFields((IX509Certificate)signCertificate); - if (x500name != null) { - name = x500name.GetField("CN"); - if (name == null) { - name = x500name.GetField("E"); - } - } - return name == null ? "" : name; - } - - /// Signature rendering modes. - [Obsolete] - public enum RenderingMode { - /// The rendering mode is just the description. - DESCRIPTION, - /// The rendering mode is the name of the signer and the description. - NAME_AND_DESCRIPTION, - /// The rendering mode is an image and the description. - GRAPHIC_AND_DESCRIPTION, - /// The rendering mode is just an image. - GRAPHIC - } - } -} diff --git a/itext/itext.sign/itext/signatures/PdfSigner.cs b/itext/itext.sign/itext/signatures/PdfSigner.cs index 6b5c2f6adc..b593ff6125 100644 --- a/itext/itext.sign/itext/signatures/PdfSigner.cs +++ b/itext/itext.sign/itext/signatures/PdfSigner.cs @@ -24,6 +24,8 @@ You should have received a copy of the GNU Affero General Public License using System.Collections.Generic; using System.IO; using iText.Bouncycastleconnector; +using iText.Commons.Bouncycastle; +using iText.Commons.Bouncycastle.Asn1; using iText.Commons.Bouncycastle.Asn1.Esf; using iText.Commons.Bouncycastle.Cert; using iText.Commons.Bouncycastle.Crypto; @@ -31,22 +33,40 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Utils; using iText.Forms; using iText.Forms.Fields; +using iText.Forms.Fields.Properties; using iText.Forms.Form.Element; using iText.Forms.Util; using iText.IO.Source; using iText.IO.Util; +using iText.Kernel.Crypto; using iText.Kernel.Exceptions; using iText.Kernel.Font; using iText.Kernel.Geom; +using iText.Kernel.Mac; using iText.Kernel.Pdf; using iText.Kernel.Pdf.Annot; +using iText.Kernel.Pdf.Tagutils; +using iText.Kernel.Validation; +using iText.Kernel.Validation.Context; using iText.Layout.Properties; +using iText.Layout.Tagging; using iText.Pdfa; +using iText.Pdfa.Checker; +using iText.Signatures.Cms; using iText.Signatures.Exceptions; +using iText.Signatures.Mac; namespace iText.Signatures { /// Takes care of the cryptographic options and appearances that form a signature. public class PdfSigner { +//\cond DO_NOT_DOCUMENT + internal const int MAXIMUM_MAC_SIZE = 788; +//\endcond + + private static readonly IBouncyCastleFactory FACTORY = BouncyCastleFactoryCreator.GetFactory(); + + private const String ID_ATTR_PDF_MAC_DATA = "1.0.32004.1.2"; + /// Enum containing the Cryptographic Standards. /// Enum containing the Cryptographic Standards. Possible values are "CMS" and "CADES". public enum CryptoStandard { @@ -56,24 +76,6 @@ public enum CryptoStandard { CADES } - /// Approval signature. - public const int NOT_CERTIFIED = 0; - - /// Author signature, no changes allowed. - public const int CERTIFIED_NO_CHANGES_ALLOWED = 1; - - /// Author signature, form filling allowed. - public const int CERTIFIED_FORM_FILLING = 2; - - /// Author signature, form filling and annotations allowed. - public const int CERTIFIED_FORM_FILLING_AND_ANNOTATIONS = 3; - - /// The certification level. - protected internal int certificationLevel = NOT_CERTIFIED; - - /// The name of the field. - protected internal String fieldName; - /// The file right before the signature is added (can be null). protected internal FileStream raf; @@ -107,21 +109,18 @@ public enum CryptoStandard { /// Indicates if the pdf document has already been pre-closed. protected internal bool preClosed = false; - /// Signature field lock dictionary. - protected internal PdfSigFieldLock fieldLock; - - /// The signature appearance. - protected internal PdfSignatureAppearance appearance; - - /// Holds value of property signDate. - protected internal DateTime signDate = DateTimeUtil.GetCurrentTime(); - /// Boolean to check if this PdfSigner instance has been closed already or not. protected internal bool closed = false; /// AcroForm for the PdfDocument. private readonly PdfAcroForm acroForm; + /// The name of the signer extracted from the signing certificate. + private String signerName = ""; + + /// Properties to be used in signing operations. + private SignerProperties signerProperties = new SignerProperties(); + /// Creates a PdfSigner instance. /// /// Creates a PdfSigner instance. Uses a @@ -163,19 +162,8 @@ public PdfSigner(PdfReader reader, Stream outputStream, StampingProperties prope public PdfSigner(PdfReader reader, Stream outputStream, String path, StampingProperties stampingProperties , SignerProperties signerProperties) : this(reader, outputStream, path, stampingProperties) { - this.fieldLock = signerProperties.GetFieldLockDict(); - UpdateFieldName(signerProperties.GetFieldName()); - // We need to update field name because the setter could change it and the user can rely on this field - signerProperties.SetFieldName(fieldName); - certificationLevel = signerProperties.GetCertificationLevel(); - appearance.SetPageRect(signerProperties.GetPageRect()); - appearance.SetPageNumber(signerProperties.GetPageNumber()); - appearance.SetSignDate(signerProperties.GetSignDate()); - appearance.SetSignatureCreator(signerProperties.GetSignatureCreator()); - appearance.SetContact(signerProperties.GetContact()); - appearance.SetReason(signerProperties.GetReason()); - appearance.SetLocation(signerProperties.GetLocation()); - this.appearance.SetSignatureAppearance(signerProperties.GetSignatureAppearance()); + this.signerProperties = signerProperties; + UpdateFieldName(); } /// Creates a PdfSigner instance. @@ -195,19 +183,18 @@ public PdfSigner(PdfReader reader, Stream outputStream, String path, StampingPro /// public PdfSigner(PdfReader reader, Stream outputStream, String path, StampingProperties properties) { StampingProperties localProps = new StampingProperties(properties).PreserveEncryption(); + localProps.RegisterDependency(typeof(IMacContainerLocator), new SignatureMacContainerLocator()); if (path == null) { - temporaryOS = new MemoryStream(); - document = InitDocument(reader, new PdfWriter(temporaryOS), localProps); + this.temporaryOS = new MemoryStream(); + this.document = InitDocument(reader, new PdfWriter(temporaryOS), localProps); } else { this.tempFile = FileUtil.CreateTempFile(path); - document = InitDocument(reader, new PdfWriter(FileUtil.GetFileOutputStream(tempFile)), localProps); + this.document = InitDocument(reader, new PdfWriter(FileUtil.GetFileOutputStream(tempFile)), localProps); } - acroForm = PdfFormCreator.GetAcroForm(document, true); - originalOS = outputStream; - fieldName = GetNewSigFieldName(); - appearance = new PdfSignatureAppearance(document, new Rectangle(0, 0), 1); - appearance.SetSignDate(signDate); + this.acroForm = PdfFormCreator.GetAcroForm(document, true); + this.originalOS = outputStream; + this.signerProperties.SetFieldName(GetNewSigFieldName()); } //\cond DO_NOT_DOCUMENT @@ -221,9 +208,7 @@ internal PdfSigner(PdfDocument document, Stream outputStream, MemoryStream tempo this.document = document; this.acroForm = PdfFormCreator.GetAcroForm(document, true); this.originalOS = outputStream; - this.fieldName = GetNewSigFieldName(); - this.appearance = new PdfSignatureAppearance(document, new Rectangle(0, 0), 1); - this.appearance.SetSignDate(this.signDate); + this.signerProperties.SetFieldName(GetNewSigFieldName()); } //\endcond @@ -254,126 +239,24 @@ internal PdfSigner(PdfDocument document, Stream outputStream, MemoryStream tempo /// protected internal virtual PdfDocument InitDocument(PdfReader reader, PdfWriter writer, StampingProperties properties) { - return new PdfAAgnosticPdfDocument(reader, writer, properties); - } - - /// Gets the signature date. - /// Calendar set to the signature date - public virtual DateTime GetSignDate() { - return signDate; - } - - /// Sets the signature date. - /// the signature date - public virtual void SetSignDate(DateTime signDate) { - this.signDate = signDate; - this.appearance.SetSignDate(signDate); - } - - /// Provides access to a signature appearance object. - /// - /// Provides access to a signature appearance object. Use it to - /// customize the appearance of the signature. - /// - /// Be aware: - /// - /// If you create new signature field (either use - /// - /// with - /// the name that doesn't exist in the document or don't specify it at all) then - /// the signature is invisible by default. - /// - /// If you sign already existing field, then the signature appearance object - /// is modified to have all the properties (page num., rect etc.) consistent with - /// the state of the field (if you customized the appearance object - /// before the - /// - /// call you'll have to do it again) - /// - /// - /// - /// - /// - /// - /// - /// object. - /// - [Obsolete] - public virtual PdfSignatureAppearance GetSignatureAppearance() { - return appearance; - } - - /// Sets the signature field layout element to customize the appearance of the signature. - /// - /// Sets the signature field layout element to customize the appearance of the signature. Signer's sign date will - /// be set. - /// - /// - /// the - /// - /// layout element. - /// - public virtual void SetSignatureAppearance(SignatureFieldAppearance appearance) { - this.appearance.SetSignatureAppearance(appearance); + // TODO DEVSIX-8676 Enable keeping A and UA conformance in PdfSigner + // TODO DEVSIX-8677 let users preserve document's conformance without knowing upfront their conformance + return new PdfSigner.PdfSignerDocument(reader, writer, properties); } - /// Returns the document's certification level. - /// - /// Returns the document's certification level. - /// For possible values see - /// . - /// - /// The certified status. - public virtual int GetCertificationLevel() { - return this.certificationLevel; - } - - /// Sets the document's certification level. - /// - /// Sets the document's certification level. - /// This method overrides the value set by - /// . - /// - /// - /// a new certification level for a document. - /// Possible values are: - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public virtual void SetCertificationLevel(int certificationLevel) { - this.certificationLevel = certificationLevel; - } - - /// Sets the document's certification level. - /// - /// Sets the document's certification level. - /// This method overrides the value set by - /// . - /// - /// - /// - /// - /// enum which specifies which certification level shall be used - /// - public virtual void SetCertificationLevel(AccessPermissions accessPermissions) { - this.certificationLevel = (int)(accessPermissions); + /// Sets the properties to be used in signing operations. + /// the signer properties + /// this instance to support fluent interface + public virtual PdfSigner SetSignerProperties(SignerProperties properties) { + this.signerProperties = properties; + UpdateFieldName(); + return this; } - /// Gets the field name. - /// the field name - public virtual String GetFieldName() { - return fieldName; + /// Gets the properties to be used in signing operations. + /// the signer properties + public virtual SignerProperties GetSignerProperties() { + return this.signerProperties; } /// Returns the user made signature dictionary. @@ -381,13 +264,13 @@ public virtual String GetFieldName() { /// Returns the user made signature dictionary. This is the dictionary at the /V key /// of the signature field. /// - /// The user made signature dictionary. + /// the user made signature dictionary public virtual PdfSignature GetSignatureDictionary() { return cryptoDictionary; } /// Getter for property signatureEvent. - /// Value of property signatureEvent. + /// value of property signatureEvent public virtual PdfSigner.ISignatureEvent GetSignatureEvent() { return this.signatureEvent; } @@ -409,16 +292,6 @@ public virtual String GetNewSigFieldName() { return name + step; } - /// Sets the name indicating the field to be signed. - /// - /// Sets the name indicating the field to be signed. The field can already be presented in the - /// document but shall not be signed. If the field is not presented in the document, it will be created. - /// - /// The name indicating the field to be signed. - public virtual void SetFieldName(String fieldName) { - UpdateFieldName(fieldName); - } - /// Gets the PdfDocument associated with this instance. /// the PdfDocument associated with this instance public virtual PdfDocument GetDocument() { @@ -434,144 +307,12 @@ protected internal virtual void SetDocument(PdfDocument document) { this.document = document; } - /// - /// Provides the page number of the signature field which this signature - /// appearance is associated with. - /// - /// - /// The page number of the signature field which this signature - /// appearance is associated with. - /// - public virtual int GetPageNumber() { - return appearance.GetPageNumber(); - } - - /// - /// Sets the page number of the signature field which this signature - /// appearance is associated with. - /// - /// - /// Sets the page number of the signature field which this signature - /// appearance is associated with. Implicitly calls - /// - /// which considers page number to process the rectangle correctly. - /// - /// - /// The page number of the signature field which - /// this signature appearance is associated with. - /// - /// this instance to support fluent interface. - public virtual PdfSigner SetPageNumber(int pageNumber) { - appearance.SetPageNumber(pageNumber); - return this; - } - - /// - /// Provides the rectangle that represent the position and dimension - /// of the signature field in the page. - /// - /// - /// the rectangle that represent the position and dimension - /// of the signature field in the page - /// - public virtual Rectangle GetPageRect() { - return appearance.GetPageRect(); - } - - /// - /// Sets the rectangle that represent the position and dimension of - /// the signature field in the page. - /// - /// - /// The rectangle that represents the position and - /// dimension of the signature field in the page. - /// - /// this instance to support fluent interface. - public virtual PdfSigner SetPageRect(Rectangle pageRect) { - appearance.SetPageRect(pageRect); - return this; - } - /// Setter for the OutputStream. /// OutputStream for the bytes of the document public virtual void SetOriginalOutputStream(Stream originalOS) { this.originalOS = originalOS; } - /// Getter for the field lock dictionary. - /// Field lock dictionary. - public virtual PdfSigFieldLock GetFieldLockDict() { - return fieldLock; - } - - /// Setter for the field lock dictionary. - /// - /// Setter for the field lock dictionary. - /// - /// Be aware: if a signature is created on an existing signature field, - /// then its /Lock dictionary takes the precedence (if it exists). - /// - /// Field lock dictionary - public virtual void SetFieldLockDict(PdfSigFieldLock fieldLock) { - this.fieldLock = fieldLock; - } - - /// Returns the signature creator. - /// The signature creator. - public virtual String GetSignatureCreator() { - return appearance.GetSignatureCreator(); - } - - /// Sets the name of the application used to create the signature. - /// A new name of the application signing a document. - /// this instance to support fluent interface. - public virtual PdfSigner SetSignatureCreator(String signatureCreator) { - appearance.SetSignatureCreator(signatureCreator); - return this; - } - - /// Returns the signing contact. - /// The signing contact. - public virtual String GetContact() { - return appearance.GetContact(); - } - - /// Sets the signing contact. - /// A new signing contact. - /// this instance to support fluent interface. - public virtual PdfSigner SetContact(String contact) { - appearance.SetContact(contact); - return this; - } - - /// Returns the signing reason. - /// The signing reason. - public virtual String GetReason() { - return appearance.GetReason(); - } - - /// Sets the signing reason. - /// A new signing reason. - /// this instance to support fluent interface. - public virtual PdfSigner SetReason(String reason) { - appearance.SetReason(reason); - return this; - } - - /// Returns the signing location. - /// The signing location. - public virtual String GetLocation() { - return appearance.GetLocation(); - } - - /// Sets the signing location. - /// A new signing location. - /// this instance to support fluent interface. - public virtual PdfSigner SetLocation(String location) { - appearance.SetLocation(location); - return this; - } - /// Gets the signature field to be signed. /// /// Gets the signature field to be signed. The field can already be presented in the document. If the field is @@ -585,18 +326,33 @@ public virtual PdfSigner SetLocation(String location) { /// and /// . + /// + /// Note that for the new signature field + /// + /// and + /// + /// should be called before this method. /// /// /// the /// - /// instance. + /// instance /// public virtual PdfSignatureFormField GetSignatureField() { - PdfFormField field = acroForm.GetField(fieldName); + PdfFormField field = acroForm.GetField(GetFieldName()); if (field == null) { - PdfSignatureFormField sigField = new SignatureFormFieldBuilder(document, fieldName).SetWidgetRectangle(GetPageRect + PdfSignatureFormField sigField = new SignatureFormFieldBuilder(document, this.signerProperties.GetFieldName + ()).SetWidgetRectangle(this.signerProperties.GetPageRect()).SetPage(this.signerProperties.GetPageNumber ()).CreateSignature(); acroForm.AddField(sigField); + if (acroForm.GetPdfObject().IsIndirect()) { + acroForm.SetModified(); + } + else { + // Acroform dictionary is a Direct dictionary, + // for proper flushing, catalog needs to be marked as modified + document.GetCatalog().SetModified(); + } return sigField; } if (field is PdfSignatureFormField) { @@ -737,13 +493,13 @@ public virtual void SignDetached(IExternalDigest externalDigest, IExternalSignat if (closed) { throw new PdfException(SignExceptionMessageConstant.THIS_INSTANCE_OF_PDF_SIGNER_ALREADY_CLOSED); } - if (certificationLevel > 0 && IsDocumentPdf2()) { + if ((int)(this.signerProperties.GetCertificationLevel()) > 0 && IsDocumentPdf2()) { if (DocumentContainsCertificationOrApprovalSignatures()) { throw new PdfException(SignExceptionMessageConstant.CERTIFICATION_SIGNATURE_CREATION_FAILED_DOC_SHALL_NOT_CONTAIN_SIGS ); } } - document.CheckIsoConformance(sigtype == PdfSigner.CryptoStandard.CADES, IsoKey.SIGNATURE_TYPE); + document.CheckIsoConformance(new SignTypeValidationContext(sigtype == PdfSigner.CryptoStandard.CADES)); ICollection crlBytes = null; int i = 0; while (crlBytes == null && i < chain.Length) { @@ -762,8 +518,12 @@ public virtual void SignDetached(IExternalDigest externalDigest, IExternalSignat if (tsaClient != null) { estimatedSize += tsaClient.GetTokenSizeEstimate() + 96; } + if (document.GetDiContainer().GetInstance().IsMacContainerLocated()) { + // If MAC container was located, we presume MAC will be embedded and allocate additional space. + estimatedSize += MAXIMUM_MAC_SIZE; + } } - appearance.SetCertificate(chain[0]); + this.signerName = PdfSigner.GetSignerName((IX509Certificate)chain[0]); if (sigtype == PdfSigner.CryptoStandard.CADES && !IsDocumentPdf2()) { AddDeveloperExtension(PdfDeveloperExtension.ESIC_1_7_EXTENSIONLEVEL2); } @@ -779,11 +539,14 @@ public virtual void SignDetached(IExternalDigest externalDigest, IExternalSignat } PdfSignature dic = new PdfSignature(PdfName.Adobe_PPKLite, sigtype == PdfSigner.CryptoStandard.CADES ? PdfName .ETSI_CAdES_DETACHED : PdfName.Adbe_pkcs7_detached); - dic.SetReason(GetReason()); - dic.SetLocation(GetLocation()); - dic.SetSignatureCreator(GetSignatureCreator()); - dic.SetContact(GetContact()); - dic.SetDate(new PdfDate(GetSignDate())); + dic.SetReason(this.signerProperties.GetReason()); + dic.SetLocation(this.signerProperties.GetLocation()); + dic.SetSignatureCreator(this.signerProperties.GetSignatureCreator()); + dic.SetContact(this.signerProperties.GetContact()); + DateTime claimedSignDate = this.signerProperties.GetClaimedSignDate(); + if (claimedSignDate != TimestampConstants.UNDEFINED_TIMESTAMP_DATE) { + dic.SetDate(new PdfDate(claimedSignDate)); + } // time-stamp will over-rule this cryptoDictionary = dic; IDictionary exc = new Dictionary(); @@ -794,7 +557,7 @@ public virtual void SignDetached(IExternalDigest externalDigest, IExternalSignat sgn.SetSignaturePolicy(signaturePolicy); } Stream data = GetRangeStream(); - byte[] hash = DigestAlgorithms.Digest(data, hashAlgorithm, externalDigest); + byte[] hash = DigestAlgorithms.Digest(data, SignUtils.GetMessageDigest(hashAlgorithm, externalDigest)); IList ocspList = new List(); if (chain.Length > 1 && ocspClient != null) { for (int j = 0; j < chain.Length - 1; ++j) { @@ -809,6 +572,8 @@ public virtual void SignDetached(IExternalDigest externalDigest, IExternalSignat byte[] extSignature = externalSignature.Sign(sh); sgn.SetExternalSignatureValue(extSignature, null, externalSignature.GetSignatureAlgorithmName(), externalSignature .GetSignatureMechanismParameters()); + document.DispatchEvent(new SignatureContainerGenerationEvent(sgn.GetUnsignedAttributes(), extSignature, GetRangeStream + ())); byte[] encodedSig = sgn.GetEncodedPKCS7(hash, sigtype, tsaClient, ocspList, crlBytes); if (estimatedSize < encodedSig.Length) { throw new System.IO.IOException("Not enough space"); @@ -839,11 +604,16 @@ public virtual void SignExternalContainer(IExternalSignatureContainer externalSi PdfSignature dic = CreateSignatureDictionary(true); externalSignatureContainer.ModifySigningDictionary(dic.GetPdfObject()); cryptoDictionary = dic; + if (document.GetDiContainer().GetInstance().IsMacContainerLocated()) { + // If MAC container was located, we presume MAC will be embedded and allocate additional space. + estimatedSize += MAXIMUM_MAC_SIZE; + } IDictionary exc = new Dictionary(); exc.Put(PdfName.Contents, estimatedSize * 2 + 2); PreClose(exc); Stream data = GetRangeStream(); byte[] encodedSig = externalSignatureContainer.Sign(data); + encodedSig = EmbedMacTokenIntoSignatureContainer(encodedSig); if (estimatedSize < encodedSig.Length) { throw new System.IO.IOException(SignExceptionMessageConstant.NOT_ENOUGH_SPACE); } @@ -875,10 +645,14 @@ public virtual void Timestamp(ITSAClient tsa, String signatureName) { throw new PdfException(SignExceptionMessageConstant.PROVIDED_TSA_CLIENT_IS_NULL); } int contentEstimated = tsa.GetTokenSizeEstimate(); + if (document.GetDiContainer().GetInstance().IsMacContainerLocated()) { + // If MAC container was located, we presume MAC will be embedded and allocate additional space. + contentEstimated += MAXIMUM_MAC_SIZE; + } if (!IsDocumentPdf2()) { AddDeveloperExtension(PdfDeveloperExtension.ESIC_1_7_EXTENSIONLEVEL5); } - SetFieldName(signatureName); + this.signerProperties.SetFieldName(signatureName); PdfSignature dic = new PdfSignature(PdfName.Adobe_PPKLite, PdfName.ETSI_RFC3161); dic.Put(PdfName.Type, PdfName.DocTimeStamp); cryptoDictionary = dic; @@ -901,6 +675,7 @@ public virtual void Timestamp(ITSAClient tsa, String signatureName) { throw iText.Bouncycastleconnector.BouncyCastleFactoryCreator.GetFactory().CreateGeneralSecurityException(e .Message, e); } + tsToken = EmbedMacTokenIntoSignatureContainer(tsToken); if (contentEstimated + 2 < tsToken.Length) { throw new System.IO.IOException(MessageFormatUtil.Format(SignExceptionMessageConstant.TOKEN_ESTIMATION_SIZE_IS_NOT_LARGE_ENOUGH , contentEstimated, tsToken.Length)); @@ -948,7 +723,7 @@ protected internal virtual ICollection ProcessCrl(IX509Certificate cert, } crlBytes.AddAll(b); } - return crlBytes.Count == 0 ? null : crlBytes; + return crlBytes.IsEmpty() ? null : crlBytes; } /// @@ -998,6 +773,8 @@ protected internal virtual void PreClose(IDictionary exclusionSiz throw new PdfException(SignExceptionMessageConstant.NO_CRYPTO_DICTIONARY_DEFINED); } cryptoDictionary.GetPdfObject().MakeIndirect(document); + document.DispatchEvent(new SignatureDocumentClosingEvent(cryptoDictionary.GetPdfObject().GetIndirectReference + ())); if (fieldExist) { fieldLock = PopulateExistingSignatureFormField(acroForm); } @@ -1014,7 +791,7 @@ protected internal virtual void PreClose(IDictionary exclusionSiz exclusionLocations.Put(key, lit); cryptoDictionary.Put(key, lit); } - if (certificationLevel > 0) { + if ((int)(this.signerProperties.GetCertificationLevel()) > 0) { AddDocMDP(cryptoDictionary); } if (fieldLock != null) { @@ -1023,14 +800,14 @@ protected internal virtual void PreClose(IDictionary exclusionSiz if (signatureEvent != null) { signatureEvent.GetSignatureDictionary(cryptoDictionary); } - if (certificationLevel > 0) { + if ((int)(this.signerProperties.GetCertificationLevel()) > 0) { // add DocMDP entry to root PdfDictionary docmdp = new PdfDictionary(); docmdp.Put(PdfName.DocMDP, cryptoDictionary.GetPdfObject()); document.GetCatalog().Put(PdfName.Perms, docmdp); document.GetCatalog().SetModified(); } - document.CheckIsoConformance(cryptoDictionary.GetPdfObject(), IsoKey.SIGNATURE); + document.CheckIsoConformance(new SignatureValidationContext(cryptoDictionary.GetPdfObject())); cryptoDictionary.GetPdfObject().Flush(false); document.Close(); range = new long[exclusionLocations.Count * 2]; @@ -1052,8 +829,8 @@ protected internal virtual void PreClose(IDictionary exclusionSiz MemoryStream bos = new MemoryStream(); PdfOutputStream os = new PdfOutputStream(bos); os.Write('['); - for (int k = 0; k < range.Length; ++k) { - os.WriteLong(range[k]).Write(' '); + foreach (long l in range) { + os.WriteLong(l).Write(' '); } os.Write(']'); Array.Copy(bos.ToArray(), 0, bout, (int)byteRangePosition, (int)bos.Length); @@ -1066,8 +843,8 @@ protected internal virtual void PreClose(IDictionary exclusionSiz MemoryStream bos = new MemoryStream(); PdfOutputStream os = new PdfOutputStream(bos); os.Write('['); - for (int k = 0; k < range.Length; ++k) { - os.WriteLong(range[k]).Write(' '); + foreach (long l in range) { + os.WriteLong(l).Write(' '); } os.Write(']'); raf.Seek(byteRangePosition); @@ -1089,6 +866,64 @@ protected internal virtual void PreClose(IDictionary exclusionSiz } } + /// + /// Returns final signature appearance object set by + /// + /// and + /// customized using + /// + /// properties such as signing date, reason, location and signer name + /// in case they weren't specified by the user, or, if none was set, returns a new one with default appearance. + /// + /// + /// Returns final signature appearance object set by + /// + /// and + /// customized using + /// + /// properties such as signing date, reason, location and signer name + /// in case they weren't specified by the user, or, if none was set, returns a new one with default appearance. + /// + /// To customize the appearance of the signature, create new + /// + /// object and set it + /// using + /// . + /// + /// Note that in case you create new signature field (either use + /// + /// with the name + /// that doesn't exist in the document or don't specify it at all) then the signature is invisible by default. + /// + /// It is possible to set other appearance related properties such as + /// + /// , + /// + /// (n0 layer) and + /// + /// (n2 layer) for the signature field using + /// + /// . Page, rectangle and other properties could be set up via + /// . + /// + /// + /// + /// + /// object representing signature appearance + /// + protected internal virtual SignatureFieldAppearance GetSignatureAppearance() { + if (this.signerProperties.GetSignatureAppearance() == null) { + this.signerProperties.SetSignatureAppearance(new SignatureFieldAppearance(SignerProperties.IGNORED_ID)); + SetContent(); + } + else { + PopulateExistingModelElement(); + } + return this.signerProperties.GetSignatureAppearance(); + } + /// Populates already existing signature form field in the acroForm object. /// /// Populates already existing signature form field in the acroForm object. @@ -1103,14 +938,15 @@ protected internal virtual void PreClose(IDictionary exclusionSiz /// /// signature field lock dictionary protected internal virtual PdfSigFieldLock PopulateExistingSignatureFormField(PdfAcroForm acroForm) { - PdfSignatureFormField sigField = (PdfSignatureFormField)acroForm.GetField(fieldName); + PdfSignatureFormField sigField = (PdfSignatureFormField)acroForm.GetField(this.signerProperties.GetFieldName + ()); PdfSigFieldLock sigFieldLock = sigField.GetSigFieldLockDictionary(); - if (sigFieldLock == null && this.fieldLock != null) { - this.fieldLock.GetPdfObject().MakeIndirect(document); - sigField.Put(PdfName.Lock, this.fieldLock.GetPdfObject()); - sigFieldLock = this.fieldLock; + if (sigFieldLock == null && this.signerProperties.GetFieldLockDict() != null) { + this.signerProperties.GetFieldLockDict().GetPdfObject().MakeIndirect(document); + sigField.Put(PdfName.Lock, this.signerProperties.GetFieldLockDict().GetPdfObject()); + sigFieldLock = this.signerProperties.GetFieldLockDict(); } - sigField.Put(PdfName.P, document.GetPage(GetPageNumber()).GetPdfObject()); + sigField.Put(PdfName.P, document.GetPage(this.signerProperties.GetPageNumber()).GetPdfObject()); sigField.Put(PdfName.V, cryptoDictionary.GetPdfObject()); PdfObject obj = sigField.GetPdfObject().Get(PdfName.F); int flags = 0; @@ -1119,18 +955,8 @@ protected internal virtual PdfSigFieldLock PopulateExistingSignatureFormField(Pd } flags |= PdfAnnotation.LOCKED; sigField.Put(PdfName.F, new PdfNumber(flags)); - sigField.DisableFieldRegeneration(); - if (appearance.IsReuseAppearanceSet()) { - sigField.SetReuseAppearance(appearance.IsReuseAppearance()); - } - if (appearance.GetSignatureAppearanceLayer() != null) { - sigField.SetSignatureAppearanceLayer(appearance.GetSignatureAppearanceLayer()); - } - if (appearance.GetBackgroundLayer() != null) { - sigField.SetBackgroundLayer(appearance.GetBackgroundLayer()); - } - sigField.GetFirstFormAnnotation().SetFormFieldElement(appearance.GetSignatureAppearance()); - sigField.EnableFieldRegeneration(); + sigField.GetFirstFormAnnotation().SetFormFieldElement(GetSignatureAppearance()); + sigField.RegenerateField(); sigField.SetModified(); return sigFieldLock; } @@ -1150,22 +976,20 @@ protected internal virtual PdfSigFieldLock PopulateExistingSignatureFormField(Pd /// the name of the field /// signature field lock dictionary protected internal virtual PdfSigFieldLock CreateNewSignatureFormField(PdfAcroForm acroForm, String name) { - PdfWidgetAnnotation widget = new PdfWidgetAnnotation(GetPageRect()); + PdfWidgetAnnotation widget = new PdfWidgetAnnotation(this.signerProperties.GetPageRect()); widget.SetFlags(PdfAnnotation.PRINT | PdfAnnotation.LOCKED); PdfSignatureFormField sigField = new SignatureFormFieldBuilder(document, name).CreateSignature(); sigField.Put(PdfName.V, cryptoDictionary.GetPdfObject()); sigField.AddKid(widget); PdfSigFieldLock sigFieldLock = sigField.GetSigFieldLockDictionary(); - if (this.fieldLock != null) { - this.fieldLock.GetPdfObject().MakeIndirect(document); - sigField.Put(PdfName.Lock, this.fieldLock.GetPdfObject()); - sigFieldLock = this.fieldLock; + if (this.signerProperties.GetFieldLockDict() != null) { + this.signerProperties.GetFieldLockDict().GetPdfObject().MakeIndirect(document); + sigField.Put(PdfName.Lock, this.signerProperties.GetFieldLockDict().GetPdfObject()); + sigFieldLock = this.signerProperties.GetFieldLockDict(); } - int pagen = GetPageNumber(); + int pagen = this.signerProperties.GetPageNumber(); widget.SetPage(document.GetPage(pagen)); sigField.DisableFieldRegeneration(); - sigField.SetReuseAppearance(appearance.IsReuseAppearance()).SetSignatureAppearanceLayer(appearance.GetSignatureAppearanceLayer - ()).SetBackgroundLayer(appearance.GetBackgroundLayer()); ApplyDefaultPropertiesForTheNewField(sigField); sigField.EnableFieldRegeneration(); acroForm.AddField(sigField, document.GetPage(pagen)); @@ -1191,9 +1015,9 @@ protected internal virtual PdfSigFieldLock CreateNewSignatureFormField(PdfAcroFo /// . /// /// - /// The + /// the /// - /// of bytes to be signed. + /// of bytes to be signed /// protected internal virtual Stream GetRangeStream() { RandomAccessSourceFactory fac = new RandomAccessSourceFactory(); @@ -1296,7 +1120,7 @@ protected internal virtual IRandomAccessSource GetUnderlyingSource() { protected internal virtual void AddDocMDP(PdfSignature crypto) { PdfDictionary reference = new PdfDictionary(); PdfDictionary transformParams = new PdfDictionary(); - transformParams.Put(PdfName.P, new PdfNumber(certificationLevel)); + transformParams.Put(PdfName.P, new PdfNumber((int)(this.signerProperties.GetCertificationLevel()))); transformParams.Put(PdfName.V, new PdfName("1.2")); transformParams.Put(PdfName.Type, PdfName.TransformParams); reference.Put(PdfName.TransformMethod, PdfName.DocMDP); @@ -1403,9 +1227,37 @@ protected internal virtual int GetWidgetPageNumber(PdfWidgetAnnotation widget) { return pageNumber; } - private void UpdateFieldName(String fieldName) { - if (fieldName != null) { - PdfFormField field = acroForm.GetField(fieldName); +//\cond DO_NOT_DOCUMENT + internal virtual PdfSignature CreateSignatureDictionary(bool includeDate) { + PdfSignature dic = new PdfSignature(); + dic.SetReason(this.signerProperties.GetReason()); + dic.SetLocation(this.signerProperties.GetLocation()); + dic.SetSignatureCreator(this.signerProperties.GetSignatureCreator()); + dic.SetContact(this.signerProperties.GetContact()); + DateTime claimedSignDate = this.signerProperties.GetClaimedSignDate(); + if (includeDate && claimedSignDate != TimestampConstants.UNDEFINED_TIMESTAMP_DATE) { + dic.SetDate(new PdfDate(claimedSignDate)); + } + // time-stamp will over-rule this + return dic; + } +//\endcond + + private static String GetSignerName(IX509Certificate certificate) { + String name = null; + CertificateInfo.X500Name x500name = CertificateInfo.GetSubjectFields(certificate); + if (x500name != null) { + name = x500name.GetField("CN"); + if (name == null) { + name = x500name.GetField("E"); + } + } + return name == null ? "" : name; + } + + private void UpdateFieldName() { + if (signerProperties.GetFieldName() != null) { + PdfFormField field = acroForm.GetField(signerProperties.GetFieldName()); if (field != null) { if (!PdfName.Sig.Equals(field.GetFormType())) { throw new ArgumentException(SignExceptionMessageConstant.FIELD_TYPE_IS_NOT_A_SIGNATURE_FIELD_TYPE); @@ -1416,19 +1268,20 @@ private void UpdateFieldName(String fieldName) { IList widgets = field.GetWidgets(); if (!widgets.IsEmpty()) { PdfWidgetAnnotation widget = widgets[0]; - SetPageRect(GetWidgetRectangle(widget)); - SetPageNumber(GetWidgetPageNumber(widget)); + this.signerProperties.SetPageRect(GetWidgetRectangle(widget)); + this.signerProperties.SetPageNumber(GetWidgetPageNumber(widget)); } } else { // Do not allow dots for new fields // For existing fields dots are allowed because there it might be fully qualified name - if (fieldName.IndexOf('.') >= 0) { + if (signerProperties.GetFieldName().IndexOf('.') >= 0) { throw new ArgumentException(SignExceptionMessageConstant.FIELD_NAMES_CANNOT_CONTAIN_A_DOT); } } - this.appearance.SetFieldName(fieldName); - this.fieldName = fieldName; + } + else { + this.signerProperties.SetFieldName(GetNewSigFieldName()); } } @@ -1436,23 +1289,44 @@ private bool IsDocumentPdf2() { return document.GetPdfVersion().CompareTo(PdfVersion.PDF_2_0) >= 0; } -//\cond DO_NOT_DOCUMENT - internal virtual PdfSignature CreateSignatureDictionary(bool includeDate) { - PdfSignature dic = new PdfSignature(); - dic.SetReason(GetReason()); - dic.SetLocation(GetLocation()); - dic.SetSignatureCreator(GetSignatureCreator()); - dic.SetContact(GetContact()); - if (includeDate) { - dic.SetDate(new PdfDate(GetSignDate())); + protected internal virtual void ApplyAccessibilityProperties(PdfFormField formField, IAccessibleElement modelElement + , PdfDocument pdfDocument) { + if (!pdfDocument.IsTagged()) { + return; + } + AccessibilityProperties properties = modelElement.GetAccessibilityProperties(); + String alternativeDescription = properties.GetAlternateDescription(); + if (alternativeDescription != null && !String.IsNullOrEmpty(alternativeDescription)) { + formField.SetAlternativeName(alternativeDescription); } - // time-stamp will over-rule this - return dic; } -//\endcond + + private byte[] EmbedMacTokenIntoSignatureContainer(byte[] signatureContainer) { + if (document.GetDiContainer().GetInstance().IsMacContainerLocated()) { + try { + CMSContainer cmsContainer = new CMSContainer(signatureContainer); + // If MAC is in the signature already, we regenerate it anyway. + cmsContainer.GetSignerInfo().RemoveUnSignedAttribute(ID_ATTR_PDF_MAC_DATA); + IAsn1EncodableVector unsignedVector = FACTORY.CreateASN1EncodableVector(); + document.DispatchEvent(new SignatureContainerGenerationEvent(unsignedVector, cmsContainer.GetSignerInfo(). + GetSignatureData(), GetRangeStream())); + if (FACTORY.CreateDERSequence(unsignedVector).Size() != 0) { + IAsn1Sequence sequence = FACTORY.CreateASN1Sequence(FACTORY.CreateDERSequence(unsignedVector).GetObjectAt( + 0)); + cmsContainer.GetSignerInfo().AddUnSignedAttribute(new CmsAttribute(FACTORY.CreateASN1ObjectIdentifier(sequence + .GetObjectAt(0)).GetId(), sequence.GetObjectAt(1).ToASN1Primitive())); + return cmsContainer.Serialize(); + } + } + catch (Exception exception) { + throw new PdfException(SignExceptionMessageConstant.NOT_POSSIBLE_TO_EMBED_MAC_TO_SIGNATURE, exception); + } + } + return signatureContainer; + } private void ApplyDefaultPropertiesForTheNewField(PdfSignatureFormField sigField) { - SignatureFieldAppearance formFieldElement = appearance.GetSignatureAppearance(); + SignatureFieldAppearance formFieldElement = GetSignatureAppearance(); PdfFormAnnotation annotation = sigField.GetFirstFormAnnotation(); annotation.SetFormFieldElement(formFieldElement); // Apply default field properties: @@ -1472,11 +1346,60 @@ private void ApplyDefaultPropertiesForTheNewField(PdfSignatureFormField sigField } BorderStyleUtil.ApplyBorderProperty(formFieldElement, annotation); Background background = formFieldElement.GetProperty(Property.BACKGROUND); + ApplyAccessibilityProperties(sigField, formFieldElement, document); if (background != null) { sigField.GetFirstFormAnnotation().SetBackgroundColor(background.GetColor()); } } + private void SetContent() { + if (this.signerProperties.GetPageRect() == null || this.signerProperties.GetPageRect().GetWidth() == 0 || + this.signerProperties.GetPageRect().GetHeight() == 0) { + return; + } + this.signerProperties.GetSignatureAppearance().SetContent(GenerateSignatureText()); + } + + private SignedAppearanceText GenerateSignatureText() { + SignedAppearanceText signedAppearanceText = new SignedAppearanceText(); + FillInAppearanceText(signedAppearanceText); + return signedAppearanceText; + } + + private void PopulateExistingModelElement() { + this.signerProperties.GetSignatureAppearance().SetSignerName(signerName); + SignedAppearanceText appearanceText = this.signerProperties.GetSignatureAppearance().GetSignedAppearanceText + (); + if (appearanceText != null) { + FillInAppearanceText(appearanceText); + } + } + + private void FillInAppearanceText(SignedAppearanceText appearanceText) { + appearanceText.SetSignedBy(signerName); + DateTime claimedSignDate = this.signerProperties.GetClaimedSignDate(); + if (claimedSignDate != TimestampConstants.UNDEFINED_TIMESTAMP_DATE) { + appearanceText.SetSignDate(claimedSignDate); + } + String reason = signerProperties.GetReason(); + bool setReason = appearanceText.GetReasonLine() != null && String.IsNullOrEmpty(appearanceText.GetReasonLine + ()); + if (setReason && reason != null && !String.IsNullOrEmpty(reason)) { + appearanceText.SetReasonLine("Reason: " + reason); + } + String location = signerProperties.GetLocation(); + bool setLocation = appearanceText.GetLocationLine() != null && String.IsNullOrEmpty(appearanceText.GetLocationLine + ()); + if (setLocation && location != null && !String.IsNullOrEmpty(location)) { + appearanceText.SetLocationLine("Location: " + location); + } + } + + private String GetFieldName() { + UpdateFieldName(); + return signerProperties.GetFieldName(); + } + /// An interface to retrieve the signature dictionary for modification. public interface ISignatureEvent { /// Allows modification of the signature dictionary. @@ -1547,5 +1470,21 @@ public virtual Stream GetDataToSign() { //\endcond internal delegate byte[] ISignatureDataProvider(PdfSigner.SignatureApplier applier); + + private class PdfSignerDocument : PdfDocument { + public PdfSignerDocument(PdfReader reader, PdfWriter writer, StampingProperties properties) + : base(reader, writer, properties) { + if (GetConformance().IsPdfA()) { + PdfAChecker checker = PdfADocument.GetCorrectCheckerFromConformance(GetConformance().GetAConformance()); + ValidationContainer validationContainer = new ValidationContainer(); + validationContainer.AddChecker(checker); + GetDiContainer().Register(typeof(ValidationContainer), validationContainer); + this.pdfPageFactory = new PdfAPageFactory(checker); + this.documentInfoHelper = new PdfADocumentInfoHelper(this); + this.defaultFontStrategy = new PdfADefaultFontStrategy(this); + SetFlushUnusedObjects(true); + } + } + } } } diff --git a/itext/itext.sign/itext/signatures/PdfTwoPhaseSigner.cs b/itext/itext.sign/itext/signatures/PdfTwoPhaseSigner.cs index 0e160ecbd2..723e3e46e0 100644 --- a/itext/itext.sign/itext/signatures/PdfTwoPhaseSigner.cs +++ b/itext/itext.sign/itext/signatures/PdfTwoPhaseSigner.cs @@ -23,7 +23,10 @@ You should have received a copy of the GNU Affero General Public License using System; using System.Collections.Generic; using System.IO; +using iText.Commons.Digest; +using iText.Kernel.Crypto; using iText.Kernel.Exceptions; +using iText.Kernel.Mac; using iText.Kernel.Pdf; using iText.Signatures.Cms; using iText.Signatures.Exceptions; @@ -92,38 +95,15 @@ public PdfTwoPhaseSigner(PdfReader reader, Stream outputStream) { /// the message digest of the prepared document. public virtual byte[] PrepareDocumentForSignature(SignerProperties signerProperties, String digestAlgorithm , PdfName filter, PdfName subFilter, int estimatedSize, bool includeDate) { - if (closed) { - throw new PdfException(SignExceptionMessageConstant.THIS_INSTANCE_OF_PDF_SIGNER_ALREADY_CLOSED); - } - PdfSigner pdfSigner = CreatePdfSigner(signerProperties); - PdfDocument document = pdfSigner.GetDocument(); - if (document.GetPdfVersion().CompareTo(PdfVersion.PDF_2_0) < 0) { - document.GetCatalog().AddDeveloperExtension(PdfDeveloperExtension.ESIC_1_7_EXTENSIONLEVEL2); - } - document.GetCatalog().AddDeveloperExtension(PdfDeveloperExtension.ISO_32002); - document.GetCatalog().AddDeveloperExtension(PdfDeveloperExtension.ISO_32001); - PdfSignature cryptoDictionary = pdfSigner.CreateSignatureDictionary(includeDate); - cryptoDictionary.Put(PdfName.Filter, filter); - cryptoDictionary.Put(PdfName.SubFilter, subFilter); - pdfSigner.cryptoDictionary = cryptoDictionary; - IDictionary exc = new Dictionary(); - exc.Put(PdfName.Contents, estimatedSize * 2 + 2); - pdfSigner.PreClose(exc); - Stream data = pdfSigner.GetRangeStream(); - byte[] digest; + IMessageDigest digest; if (externalDigest != null) { - digest = DigestAlgorithms.Digest(data, digestAlgorithm, externalDigest); + digest = externalDigest.GetMessageDigest(digestAlgorithm); } else { - digest = DigestAlgorithms.Digest(data, SignUtils.GetMessageDigest(digestAlgorithm)); + digest = SignUtils.GetMessageDigest(digestAlgorithm); } - byte[] paddedSig = new byte[estimatedSize]; - PdfDictionary dic2 = new PdfDictionary(); - dic2.Put(PdfName.Contents, new PdfString(paddedSig).SetHexWriting(true)); - pdfSigner.Close(dic2); - pdfSigner.closed = true; - closed = true; - return digest; + return PrepareDocumentForSignature(signerProperties, digest, filter, subFilter, estimatedSize, includeDate + ); } /// Adds an existing signature to a PDF where space was already reserved. @@ -185,5 +165,38 @@ internal virtual PdfSigner CreatePdfSigner(SignerProperties signerProperties) { return new PdfSigner(reader, outputStream, null, stampingProperties, signerProperties); } //\endcond + + private byte[] PrepareDocumentForSignature(SignerProperties signerProperties, IMessageDigest messageDigest + , PdfName filter, PdfName subFilter, int estimatedSize, bool includeDate) { + if (closed) { + throw new PdfException(SignExceptionMessageConstant.THIS_INSTANCE_OF_PDF_SIGNER_ALREADY_CLOSED); + } + PdfSigner pdfSigner = CreatePdfSigner(signerProperties); + PdfDocument document = pdfSigner.GetDocument(); + if (document.GetDiContainer().GetInstance().IsMacContainerLocated()) { + throw new PdfException(SignExceptionMessageConstant.NOT_POSSIBLE_TO_EMBED_MAC_TO_SIGNATURE); + } + if (document.GetPdfVersion().CompareTo(PdfVersion.PDF_2_0) < 0) { + document.GetCatalog().AddDeveloperExtension(PdfDeveloperExtension.ESIC_1_7_EXTENSIONLEVEL2); + } + document.GetCatalog().AddDeveloperExtension(PdfDeveloperExtension.ISO_32002); + document.GetCatalog().AddDeveloperExtension(PdfDeveloperExtension.ISO_32001); + PdfSignature cryptoDictionary = pdfSigner.CreateSignatureDictionary(includeDate); + cryptoDictionary.Put(PdfName.Filter, filter); + cryptoDictionary.Put(PdfName.SubFilter, subFilter); + pdfSigner.cryptoDictionary = cryptoDictionary; + IDictionary exc = new Dictionary(); + exc.Put(PdfName.Contents, estimatedSize * 2 + 2); + pdfSigner.PreClose(exc); + Stream data = pdfSigner.GetRangeStream(); + byte[] digest = DigestAlgorithms.Digest(data, messageDigest); + byte[] paddedSig = new byte[estimatedSize]; + PdfDictionary dic2 = new PdfDictionary(); + dic2.Put(PdfName.Contents, new PdfString(paddedSig).SetHexWriting(true)); + pdfSigner.Close(dic2); + pdfSigner.closed = true; + closed = true; + return digest; + } } } diff --git a/itext/itext.sign/itext/signatures/PrivateKeySignature.cs b/itext/itext.sign/itext/signatures/PrivateKeySignature.cs index 8acc533216..04ec03b156 100644 --- a/itext/itext.sign/itext/signatures/PrivateKeySignature.cs +++ b/itext/itext.sign/itext/signatures/PrivateKeySignature.cs @@ -23,6 +23,7 @@ You should have received a copy of the GNU Affero General Public License using System; using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Utils; +using iText.Kernel.Crypto; using iText.Kernel.Exceptions; using iText.Signatures.Exceptions; @@ -95,7 +96,7 @@ public PrivateKeySignature(IPrivateKey pk, String hashAlgorithm, String signatur } switch (this.signatureAlgorithm) { case "Ed25519": { - if (!SecurityIDs.ID_SHA512.Equals(digestAlgorithmOid)) { + if (!OID.SHA_512.Equals(digestAlgorithmOid)) { throw new PdfException(SignExceptionMessageConstant.ALGO_REQUIRES_SPECIFIC_HASH).SetMessageParams("Ed25519" , "SHA-512", this.hashAlgorithm); } @@ -104,7 +105,7 @@ public PrivateKeySignature(IPrivateKey pk, String hashAlgorithm, String signatur } case "Ed448": { - if (!SecurityIDs.ID_SHAKE256.Equals(digestAlgorithmOid)) { + if (!OID.SHAKE_256.Equals(digestAlgorithmOid)) { throw new PdfException(SignExceptionMessageConstant.ALGO_REQUIRES_SPECIFIC_HASH).SetMessageParams("Ed448", "512-bit SHAKE256", this.hashAlgorithm); } diff --git a/itext/itext.sign/itext/signatures/RSASSAPSSMechanismParams.cs b/itext/itext.sign/itext/signatures/RSASSAPSSMechanismParams.cs index 8c43ff7bd9..e41391c3a9 100644 --- a/itext/itext.sign/itext/signatures/RSASSAPSSMechanismParams.cs +++ b/itext/itext.sign/itext/signatures/RSASSAPSSMechanismParams.cs @@ -25,6 +25,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle; using iText.Commons.Bouncycastle.Asn1; using iText.Commons.Bouncycastle.Crypto; +using iText.Kernel.Crypto; using iText.Kernel.Exceptions; namespace iText.Signatures { diff --git a/itext/itext.sign/itext/signatures/RootStoreVerifier.cs b/itext/itext.sign/itext/signatures/RootStoreVerifier.cs index 30316b0bd1..6f8bc7bd5d 100644 --- a/itext/itext.sign/itext/signatures/RootStoreVerifier.cs +++ b/itext/itext.sign/itext/signatures/RootStoreVerifier.cs @@ -30,7 +30,7 @@ namespace iText.Signatures { /// Verifies a certificate against a KeyStore /// containing trusted anchors. /// - [System.ObsoleteAttribute(@"starting from 8.0.5.iText.Signatures.Validation.V1.CertificateChainValidator should be used instead." + [System.ObsoleteAttribute(@"starting from 8.0.5.iText.Signatures.Validation.CertificateChainValidator should be used instead." )] public class RootStoreVerifier : CertificateVerifier { /// A key store against which certificates can be verified. diff --git a/itext/itext.sign/itext/signatures/SecurityIDs.cs b/itext/itext.sign/itext/signatures/SecurityIDs.cs deleted file mode 100644 index b2cdf9c851..0000000000 --- a/itext/itext.sign/itext/signatures/SecurityIDs.cs +++ /dev/null @@ -1,80 +0,0 @@ -/* -This file is part of the iText (R) project. -Copyright (c) 1998-2024 Apryse Group NV -Authors: Apryse Software. - -This program is offered under a commercial and under the AGPL license. -For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. - -AGPL licensing: -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . -*/ -using System; - -namespace iText.Signatures { - /// A list of IDs that are used by the security classes - public class SecurityIDs { - public const String ID_PKCS7_DATA = "1.2.840.113549.1.7.1"; - - public const String ID_PKCS7_SIGNED_DATA = "1.2.840.113549.1.7.2"; - - public const String ID_RSA = "1.2.840.113549.1.1.1"; - - public const String ID_RSASSA_PSS = "1.2.840.113549.1.1.10"; - - public const String ID_RSA_WITH_SHA256 = "1.2.840.113549.1.1.11"; - - public const String ID_RSA_WITH_SHA3_512 = "2.16.840.1.101.3.4.3.16"; - - public const String ID_DSA = "1.2.840.10040.4.1"; - - public const String ID_ECDSA = "1.2.840.10045.2.1"; - - public const String ID_ED25519 = "1.3.101.112"; - - public const String ID_ED448 = "1.3.101.113"; - - public const String ID_SHA256 = "2.16.840.1.101.3.4.2.1"; - - public const String ID_SHA384 = "2.16.840.1.101.3.4.2.2"; - - public const String ID_SHA512 = "2.16.840.1.101.3.4.2.3"; - - public const String ID_SHAKE256 = "2.16.840.1.101.3.4.2.12"; - - public const String ID_CONTENT_TYPE = "1.2.840.113549.1.9.3"; - - public const String ID_MESSAGE_DIGEST = "1.2.840.113549.1.9.4"; - - public const String ID_SIGNING_TIME = "1.2.840.113549.1.9.5"; - - public const String ID_ADBE_REVOCATION = "1.2.840.113583.1.1.8"; - - public const String ID_TSA = "1.2.840.113583.1.1.9.1"; - - public const String ID_OCSP = "1.3.6.1.5.5.7.48.1"; - - public const String ID_CA_ISSUERS = "1.3.6.1.5.5.7.48.2"; - - public const String ID_AA_SIGNING_CERTIFICATE_V1 = "1.2.840.113549.1.9.16.2.12"; - - public const String ID_AA_SIGNING_CERTIFICATE_V2 = "1.2.840.113549.1.9.16.2.47"; - - public const String ID_MGF1 = "1.2.840.113549.1.1.8"; - - public const String ID_AA_TIME_STAMP_TOKEN = "1.2.840.113549.1.9.16.2.14"; - - public const String ID_RI_OCSP_RESPONSE = "1.3.6.1.5.5.7.16.2"; - } -} diff --git a/itext/itext.sign/itext/signatures/SignExtensions.cs b/itext/itext.sign/itext/signatures/SignExtensions.cs index ecded872e0..e63a98b1a6 100644 --- a/itext/itext.sign/itext/signatures/SignExtensions.cs +++ b/itext/itext.sign/itext/signatures/SignExtensions.cs @@ -88,6 +88,10 @@ public static void AddAll(this IDictionary c, IDicti c[pair.Key] = pair.Value; } } + + public static void Add(this IList list, int index, T elem) { + list.Insert(index, elem); + } public static T JRemoveAt(this IList list, int index) { T value = list[index]; diff --git a/itext/itext.sign/itext/signatures/SignUtils.cs b/itext/itext.sign/itext/signatures/SignUtils.cs index 34242d59f7..c372ca2ad3 100644 --- a/itext/itext.sign/itext/signatures/SignUtils.cs +++ b/itext/itext.sign/itext/signatures/SignUtils.cs @@ -85,8 +85,8 @@ internal static byte[] GetExtensionValueByOid(IX509Crl crl, String oid) { return extensionValue.IsNull() ? null : extensionValue.GetDerEncoded(); } - internal static IDigest GetMessageDigest(String hashAlgorithm) { - return (IDigest)new BouncyCastleDigest().GetMessageDigest(hashAlgorithm); + internal static IMessageDigest GetMessageDigest(String hashAlgorithm) { + return new BouncyCastleDigest().GetMessageDigest(hashAlgorithm); } internal static IMessageDigest GetMessageDigest(String hashAlgorithm, IExternalDigest externalDigest) { @@ -211,37 +211,6 @@ internal static TsaResponse GetTsaResponseForUserRequest(String tsaUrl, byte[] r response.encoding = httpWebResponse.Headers[HttpResponseHeader.ContentEncoding]; return response; } - - /// - /// This behavior is different in Java and .NET, because in Java we use this two-step check: - /// first via #hasUnsupportedCriticalExtension method, and then additionally allowing standard critical extensions; - /// in .NET there's only second step. However, removing first step in Java can be a breaking change for some users - /// and moreover we don't have any means of providing customization for unsupported extensions check as of right now. - /// - /// During major release I'd suggest changing java unsupported extensions check logic to the same as in .NET, - /// but only if it is possible to customize this logic. - /// - /// - /// - /// TODO DEVSIX-2634 - [Obsolete] - internal static bool HasUnsupportedCriticalExtension(IX509Certificate cert) { - if ( cert == null ) { - throw new ArgumentException("X509Certificate can't be null."); - } - - ISet criticalExtensionsSet = cert.GetCriticalExtensionOids(); - if (criticalExtensionsSet != null) { - foreach (String oid in criticalExtensionsSet) { - if (OID.X509Extensions.SUPPORTED_CRITICAL_EXTENSIONS.Contains(oid)) { - continue; - - } - return true; - } - } - return false; - } internal static DateTime GetTimeStampDate(ITstInfo timeStampTokenInfo) { return timeStampTokenInfo.GetGenTime(); diff --git a/itext/itext.sign/itext/signatures/SignatureMechanisms.cs b/itext/itext.sign/itext/signatures/SignatureMechanisms.cs index ab688b4ae6..be6009931d 100644 --- a/itext/itext.sign/itext/signatures/SignatureMechanisms.cs +++ b/itext/itext.sign/itext/signatures/SignatureMechanisms.cs @@ -26,7 +26,8 @@ You should have received a copy of the GNU Affero General Public License using iText.Bouncycastleconnector; using iText.Commons; using iText.Commons.Bouncycastle; -using iText.Signatures.Logs; +using iText.Kernel.Crypto; +using iText.Kernel.Logs; namespace iText.Signatures { /// @@ -110,10 +111,10 @@ static SignatureMechanisms() { * the digest is required to be specified in the algorithm params anyway, * and the OID does not depend on the digest. BouncyCastle accepts both. */ - algorithmNames.Put(SecurityIDs.ID_RSASSA_PSS, "RSASSA-PSS"); + algorithmNames.Put(OID.RSASSA_PSS, "RSASSA-PSS"); // EdDSA - algorithmNames.Put(SecurityIDs.ID_ED25519, "Ed25519"); - algorithmNames.Put(SecurityIDs.ID_ED448, "Ed448"); + algorithmNames.Put(OID.ED25519, "Ed25519"); + algorithmNames.Put(OID.ED448, "Ed448"); rsaOidsByDigest.Put("SHA224", "1.2.840.113549.1.1.14"); rsaOidsByDigest.Put("SHA256", "1.2.840.113549.1.1.11"); rsaOidsByDigest.Put("SHA384", "1.2.840.113549.1.1.12"); @@ -158,7 +159,7 @@ public static String GetSignatureMechanismOid(String signatureAlgorithmName, Str switch (signatureAlgorithmName) { case "RSA": { String oId = rsaOidsByDigest.Get(digestAlgorithmName); - resultingOId = oId == null ? SecurityIDs.ID_RSA : oId; + resultingOId = oId == null ? OID.RSA : oId; break; } @@ -173,18 +174,18 @@ public static String GetSignatureMechanismOid(String signatureAlgorithmName, Str } case "Ed25519": { - resultingOId = SecurityIDs.ID_ED25519; + resultingOId = OID.ED25519; break; } case "Ed448": { - resultingOId = SecurityIDs.ID_ED448; + resultingOId = OID.ED448; break; } case "RSASSA-PSS": case "RSA/PSS": { - resultingOId = SecurityIDs.ID_RSASSA_PSS; + resultingOId = OID.RSASSA_PSS; break; } @@ -196,7 +197,7 @@ public static String GetSignatureMechanismOid(String signatureAlgorithmName, Str if (resultingOId != null) { return resultingOId; } - LOGGER.LogWarning(SignLogMessageConstant.ALGORITHM_NOT_FROM_SPEC); + LOGGER.LogWarning(KernelLogMessageConstant.ALGORITHM_NOT_FROM_SPEC); resultingOId = BOUNCY_CASTLE_FACTORY.GetAlgorithmOid(digestAlgorithmName + "with" + signatureAlgorithmName ); if (resultingOId == null) { @@ -229,7 +230,7 @@ public static String GetMechanism(String oid, String digest) { if (!algorithm.Equals(oid)) { return digest + "with" + algorithm; } - LOGGER.LogWarning(SignLogMessageConstant.ALGORITHM_NOT_FROM_SPEC); + LOGGER.LogWarning(KernelLogMessageConstant.ALGORITHM_NOT_FROM_SPEC); return BOUNCY_CASTLE_FACTORY.GetAlgorithmName(oid); } } diff --git a/itext/itext.sign/itext/signatures/SignaturePolicyInfo.cs b/itext/itext.sign/itext/signatures/SignaturePolicyInfo.cs index 2fcd503fb5..3c0eb04029 100644 --- a/itext/itext.sign/itext/signatures/SignaturePolicyInfo.cs +++ b/itext/itext.sign/itext/signatures/SignaturePolicyInfo.cs @@ -26,6 +26,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Asn1; using iText.Commons.Bouncycastle.Asn1.Esf; using iText.Commons.Utils; +using iText.Kernel.Crypto; namespace iText.Signatures { /// Class that encapsulates the signature policy information diff --git a/itext/itext.sign/itext/signatures/SignatureUtil.cs b/itext/itext.sign/itext/signatures/SignatureUtil.cs index eb328846a5..f688e28e1d 100644 --- a/itext/itext.sign/itext/signatures/SignatureUtil.cs +++ b/itext/itext.sign/itext/signatures/SignatureUtil.cs @@ -408,10 +408,30 @@ public virtual bool CheckWhetherSignatureCoversWholeDocument(PdfFormField signat rangeIsCorrect = false; PdfDictionary signature = (PdfDictionary)signatureField.GetValue(); int[] byteRange = ((PdfArray)signature.Get(PdfName.ByteRange)).ToIntArray(); - if (4 != byteRange.Length || 0 != byteRange[0] || tokens.GetSafeFile().Length() != byteRange[2] + byteRange - [3]) { + if (4 != byteRange.Length || 0 != byteRange[0]) { return false; } + if (tokens.GetSafeFile().Length() < byteRange[2] + byteRange[3]) { + return false; + } + else { + // We allow up to 4 EOL bytes to not be included into byte range. + tokens.Seek(byteRange[2] + byteRange[3]); + try { + String remainingBytes = tokens.ReadString(5); + if (remainingBytes.Length > 4) { + return false; + } + foreach (byte b in remainingBytes.GetBytes(System.Text.Encoding.UTF8)) { + if (b != '\n' && b != '\r') { + return false; + } + } + } + catch (System.IO.IOException) { + return false; + } + } rangeExclusionStart = byteRange[1]; rangeExlusionEnd = byteRange[2]; long signatureOffset; diff --git a/itext/itext.sign/itext/signatures/SignerProperties.cs b/itext/itext.sign/itext/signatures/SignerProperties.cs index c7618d8bf0..adf97890e5 100644 --- a/itext/itext.sign/itext/signatures/SignerProperties.cs +++ b/itext/itext.sign/itext/signatures/SignerProperties.cs @@ -29,13 +29,22 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Signatures { /// Properties to be used in signing operations. public class SignerProperties { + /// + /// This string could be used to create the + /// + /// instance which will be used for signing + /// since its ID will be ignored anyway in that case, and specified ID won't override the field name. + /// + /// + public const String IGNORED_ID = ""; + private PdfSigFieldLock fieldLock; private SignatureFieldAppearance appearance; private DateTime signDate = DateTimeUtil.GetCurrentTime(); - private int certificationLevel = PdfSigner.NOT_CERTIFIED; + private AccessPermissions certificationLevel = AccessPermissions.UNSPECIFIED; private String fieldName; @@ -60,41 +69,89 @@ public SignerProperties() { // Empty constructor. /// Gets the signature date. - /// Calendar set to the signature date. - public virtual DateTime GetSignDate() { + /// calendar set to the signature date + public virtual DateTime GetClaimedSignDate() { return signDate; } /// Sets the signature date. - /// the signature date. - /// this instance to support fluent interface. - public virtual iText.Signatures.SignerProperties SetSignDate(DateTime signDate) { + /// the signature date + /// this instance to support fluent interface + public virtual iText.Signatures.SignerProperties SetClaimedSignDate(DateTime signDate) { this.signDate = signDate; return this; } /// Sets the signature field layout element to customize the appearance of the signature. /// - /// Sets the signature field layout element to customize the appearance of the signature. Signer's sign date will - /// be set. + /// Sets the signature field layout element to customize the appearance of the signature. + /// ID specified for + /// + /// will be ignored and won't override field name, so + /// + /// could be used. To specify signature name use + /// . + /// + /// Note that if + /// + /// was set as the content (or part of the content) + /// for + /// + /// object, + /// + /// properties such as signing date, reason, location + /// and signer name could be set automatically. + /// + /// In case you create new signature field (either using + /// + /// with the name + /// that doesn't exist in the document or do not specifying it at all) then the signature is invisible by default. + /// Use + /// + /// and + /// + /// to provide + /// the rectangle that represent the position and dimension of the signature field in the specified page. + /// + /// It is possible to set other appearance related properties such as + /// + /// , + /// + /// (n0 layer) and + /// + /// (n2 layer) for the signature field using + /// + /// . Page, rectangle and other properties could be also set up via + /// . /// /// /// the /// - /// layout element. + /// layout element representing signature appearance /// - /// this instance to support fluent interface. + /// this instance to support fluent interface public virtual iText.Signatures.SignerProperties SetSignatureAppearance(SignatureFieldAppearance appearance ) { this.appearance = appearance; return this; } - /// Gets signature field layout element, which customizes the appearance of a signature. + /// Gets signature field appearance object representing the appearance of the signature. + /// + /// Gets signature field appearance object representing the appearance of the signature. + /// + /// To customize the signature appearance, create new + /// + /// object and set it + /// using + /// . + /// /// /// /// - /// layout element. + /// object representing signature appearance /// public virtual SignatureFieldAppearance GetSignatureAppearance() { return this.appearance; @@ -104,39 +161,32 @@ public virtual SignatureFieldAppearance GetSignatureAppearance() { /// /// Returns the document's certification level. /// For possible values see - /// . + /// . /// - /// The certified status. - public virtual int GetCertificationLevel() { + /// + /// + /// + /// enum which specifies which certification level shall be used + /// + public virtual AccessPermissions GetCertificationLevel() { return this.certificationLevel; } /// Sets the document's certification level. - /// - /// a new certification level for a document. - /// Possible values are: - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// + /// + /// + /// + /// enum which specifies which certification level shall be used /// - /// this instance to support fluent interface. - public virtual iText.Signatures.SignerProperties SetCertificationLevel(int certificationLevel) { - this.certificationLevel = certificationLevel; + /// this instance to support fluent interface + public virtual iText.Signatures.SignerProperties SetCertificationLevel(AccessPermissions accessPermissions + ) { + this.certificationLevel = accessPermissions; return this; } /// Gets the field name. - /// the field name. + /// the field name public virtual String GetFieldName() { return fieldName; } @@ -145,74 +195,57 @@ public virtual String GetFieldName() { /// /// Sets the name indicating the field to be signed. The field can already be presented in the /// document but shall not be signed. If the field is not presented in the document, it will be created. + /// + /// Note that ID specified for + /// + /// set by + /// + /// will be + /// ignored and won't override the field name. /// - /// The name indicating the field to be signed. - /// this instance to support fluent interface. + /// the name indicating the field to be signed + /// this instance to support fluent interface public virtual iText.Signatures.SignerProperties SetFieldName(String fieldName) { - this.fieldName = fieldName; + if (fieldName != null) { + this.fieldName = fieldName; + } return this; } - /// - /// Provides the page number of the signature field which this signature - /// appearance is associated with. - /// - /// - /// The page number of the signature field which this signature - /// appearance is associated with. - /// + /// Provides the page number of the signature field which this signature appearance is associated with. + /// + /// the page number of the signature field which this signature appearance is associated with public virtual int GetPageNumber() { return this.pageNumber; } - /// - /// Sets the page number of the signature field which this signature - /// appearance is associated with. - /// - /// - /// Sets the page number of the signature field which this signature - /// appearance is associated with. Implicitly calls - /// - /// which considers page number to process the rectangle correctly. - /// - /// - /// The page number of the signature field which - /// this signature appearance is associated with. - /// - /// this instance to support fluent interface. + /// Sets the page number of the signature field which this signature appearance is associated with. + /// the page number of the signature field which this signature appearance is associated with + /// + /// this instance to support fluent interface public virtual iText.Signatures.SignerProperties SetPageNumber(int pageNumber) { this.pageNumber = pageNumber; return this; } - /// - /// Provides the rectangle that represent the position and dimension - /// of the signature field in the page. - /// - /// - /// the rectangle that represent the position and dimension - /// of the signature field in the page - /// + /// Provides the rectangle that represent the position and dimension of the signature field in the page. + /// + /// the rectangle that represent the position and dimension of the signature field in the page public virtual Rectangle GetPageRect() { return this.pageRect; } - /// - /// Sets the rectangle that represent the position and dimension of - /// the signature field in the page. - /// - /// - /// The rectangle that represents the position and - /// dimension of the signature field in the page. - /// - /// this instance to support fluent interface. + /// Sets the rectangle that represent the position and dimension of the signature field in the page. + /// the rectangle that represents the position and dimension of the signature field in the page + /// + /// this instance to support fluent interface public virtual iText.Signatures.SignerProperties SetPageRect(Rectangle pageRect) { this.pageRect = pageRect; return this; } /// Getter for the field lock dictionary. - /// Field lock dictionary. + /// field lock dictionary public virtual PdfSigFieldLock GetFieldLockDict() { return fieldLock; } @@ -224,15 +257,15 @@ public virtual PdfSigFieldLock GetFieldLockDict() { /// Be aware: if a signature is created on an existing signature field, /// then its /Lock dictionary takes the precedence (if it exists). /// - /// Field lock dictionary. - /// this instance to support fluent interface. + /// field lock dictionary + /// this instance to support fluent interface public virtual iText.Signatures.SignerProperties SetFieldLockDict(PdfSigFieldLock fieldLock) { this.fieldLock = fieldLock; return this; } /// Returns the signature creator. - /// The signature creator. + /// the signature creator public virtual String GetSignatureCreator() { return this.signatureCreator; } @@ -246,42 +279,42 @@ public virtual iText.Signatures.SignerProperties SetSignatureCreator(String sign } /// Returns the signing contact. - /// The signing contact. + /// the signing contact public virtual String GetContact() { return this.contact; } /// Sets the signing contact. - /// A new signing contact. - /// this instance to support fluent interface. + /// a new signing contact + /// this instance to support fluent interface public virtual iText.Signatures.SignerProperties SetContact(String contact) { this.contact = contact; return this; } /// Returns the signing reason. - /// The signing reason. + /// the signing reason public virtual String GetReason() { return this.reason; } /// Sets the signing reason. - /// A new signing reason. - /// this instance to support fluent interface. + /// a new signing reason + /// this instance to support fluent interface public virtual iText.Signatures.SignerProperties SetReason(String reason) { this.reason = reason; return this; } /// Returns the signing location. - /// The signing location. + /// the signing location public virtual String GetLocation() { return this.location; } /// Sets the signing location. - /// A new signing location. - /// this instance to support fluent interface. + /// a new signing location + /// this instance to support fluent interface public virtual iText.Signatures.SignerProperties SetLocation(String location) { this.location = location; return this; diff --git a/itext/itext.sign/itext/signatures/TSAClientBouncyCastle.cs b/itext/itext.sign/itext/signatures/TSAClientBouncyCastle.cs index 708c55b93a..b32ee29305 100644 --- a/itext/itext.sign/itext/signatures/TSAClientBouncyCastle.cs +++ b/itext/itext.sign/itext/signatures/TSAClientBouncyCastle.cs @@ -27,10 +27,11 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons; using iText.Commons.Bouncycastle; using iText.Commons.Bouncycastle.Asn1.Cmp; -using iText.Commons.Bouncycastle.Crypto; using iText.Commons.Bouncycastle.Math; using iText.Commons.Bouncycastle.Tsp; +using iText.Commons.Digest; using iText.Commons.Utils; +using iText.Kernel.Crypto; using iText.Kernel.Exceptions; using iText.Signatures.Exceptions; @@ -152,7 +153,7 @@ public virtual void SetTSAReqPolicy(String tsaReqPolicy) { /// Gets the MessageDigest to digest the data imprint /// the digest algorithm name - public virtual IDigest GetMessageDigest() { + public virtual IMessageDigest GetMessageDigest() { return SignUtils.GetMessageDigest(digestAlgorithm); } diff --git a/itext/itext.sign/itext/signatures/VerificationException.cs b/itext/itext.sign/itext/signatures/VerificationException.cs index 6bdb29a8ce..815de785ef 100644 --- a/itext/itext.sign/itext/signatures/VerificationException.cs +++ b/itext/itext.sign/itext/signatures/VerificationException.cs @@ -30,6 +30,8 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Signatures { /// An exception that is thrown when something is wrong with a certificate. + [System.ObsoleteAttribute(@"starting from 9.0.0 since all the classes that use this one are also deprecated in favour of new signature validation logic in the iText.Signatures.Validation package." + )] public class VerificationException : AbstractGeneralSecurityException { private static readonly IBouncyCastleFactory BOUNCY_CASTLE_FACTORY = BouncyCastleFactoryCreator.GetFactory (); diff --git a/itext/itext.sign/itext/signatures/VerificationOK.cs b/itext/itext.sign/itext/signatures/VerificationOK.cs index 61ea1a6ff0..2d673814c1 100644 --- a/itext/itext.sign/itext/signatures/VerificationOK.cs +++ b/itext/itext.sign/itext/signatures/VerificationOK.cs @@ -30,7 +30,7 @@ namespace iText.Signatures { /// succeeded using a specific CertificateVerifier and for a specific /// reason. /// - [System.ObsoleteAttribute(@"starting from 8.0.5.iText.Signatures.Validation.V1.Report.ReportItem should be used instead." + [System.ObsoleteAttribute(@"starting from 8.0.5.iText.Signatures.Validation.Report.ReportItem should be used instead." )] public class VerificationOK { /// The certificate that was verified successfully. diff --git a/itext/itext.sign/itext/signatures/cms/CMSContainer.cs b/itext/itext.sign/itext/signatures/cms/CMSContainer.cs index f69e80eba7..c953ecb968 100644 --- a/itext/itext.sign/itext/signatures/cms/CMSContainer.cs +++ b/itext/itext.sign/itext/signatures/cms/CMSContainer.cs @@ -29,6 +29,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Asn1.Ocsp; using iText.Commons.Bouncycastle.Cert; using iText.Commons.Utils; +using iText.Kernel.Crypto; using iText.Kernel.Exceptions; using iText.Signatures; using iText.Signatures.Exceptions; @@ -81,6 +82,8 @@ public class CMSContainer { /// This class only supports one signer per signature field. private SignerInfo signerInfo = new SignerInfo(); + private int version = 1; + /// Creates an empty SignedData structure. public CMSContainer() { } @@ -94,6 +97,7 @@ public CMSContainer(byte[] encodedCMSdata) { IAsn1Sequence contentInfo = BC_FACTORY.CreateASN1Sequence(@is.ReadObject()); IAsn1Sequence signedData = BC_FACTORY.CreateASN1Sequence(BC_FACTORY.CreateASN1TaggedObject(contentInfo.GetObjectAt (1)).GetObject()); + version = BC_FACTORY.CreateASN1Integer(signedData.GetObjectAt(0)).GetValue().GetIntValue(); // The digest algorithm is retrieved from SignerInfo later on, here we just validate // that there is exactly 1 digest algorithm. IAsn1Set digestAlgorithms = BC_FACTORY.CreateASN1Set(signedData.GetObjectAt(1)); @@ -149,10 +153,10 @@ public virtual long GetSizeEstimation() { return result.Length; } - /// Only version 1 is supported by this class. - /// 1 as CMSversion + /// The version of the CMS container. + /// version of the CMS container public virtual int GetCmsVersion() { - return 1; + return version; } /// The digest algorithm OID and parameters used by the signer. @@ -291,7 +295,7 @@ other OtherRevocationInfoFormat SEQUENCE signerInfos SignerInfos SET */ IAsn1EncodableVector contentInfoV = BC_FACTORY.CreateASN1EncodableVector(); - contentInfoV.Add(BC_FACTORY.CreateASN1ObjectIdentifier(SecurityIDs.ID_PKCS7_SIGNED_DATA)); + contentInfoV.Add(BC_FACTORY.CreateASN1ObjectIdentifier(OID.PKCS7_SIGNED_DATA)); IAsn1EncodableVector singedDataV = BC_FACTORY.CreateASN1EncodableVector(); singedDataV.Add(BC_FACTORY.CreateASN1Integer(GetCmsVersion())); // version @@ -301,7 +305,7 @@ signerInfos SignerInfos SET IAsn1EncodableVector encapContentInfoV = BC_FACTORY.CreateASN1EncodableVector(); encapContentInfoV.Add(BC_FACTORY.CreateASN1ObjectIdentifier(encapContentInfo.GetContentType())); if (encapContentInfo.GetContent() != null) { - encapContentInfoV.Add(encapContentInfo.GetContent()); + encapContentInfoV.Add(BC_FACTORY.CreateDERTaggedObject(0, encapContentInfo.GetContent())); } singedDataV.Add(BC_FACTORY.CreateDERSequence(encapContentInfoV)); IAsn1EncodableVector certificateSetV = BC_FACTORY.CreateASN1EncodableVector(); diff --git a/itext/itext.sign/itext/signatures/cms/EncapsulatedContentInfo.cs b/itext/itext.sign/itext/signatures/cms/EncapsulatedContentInfo.cs index 05e3cd981a..cc9640ad58 100644 --- a/itext/itext.sign/itext/signatures/cms/EncapsulatedContentInfo.cs +++ b/itext/itext.sign/itext/signatures/cms/EncapsulatedContentInfo.cs @@ -24,6 +24,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Bouncycastleconnector; using iText.Commons.Bouncycastle; using iText.Commons.Bouncycastle.Asn1; +using iText.Kernel.Crypto; namespace iText.Signatures.Cms { /// This class represents the signed content. @@ -31,7 +32,7 @@ public class EncapsulatedContentInfo { private static readonly IBouncyCastleFactory BC_FACTORY = BouncyCastleFactoryCreator.GetFactory(); /// Object identifier of the content field - private String eContentType = "1.2.840.113549.1.7.1"; + private String eContentType = OID.PKCS7_DATA; /// Optional. /// diff --git a/itext/itext.sign/itext/signatures/cms/SignerInfo.cs b/itext/itext.sign/itext/signatures/cms/SignerInfo.cs index f3d0d1e349..71a175dd24 100644 --- a/itext/itext.sign/itext/signatures/cms/SignerInfo.cs +++ b/itext/itext.sign/itext/signatures/cms/SignerInfo.cs @@ -31,6 +31,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Cert; using iText.Commons.Digest; using iText.Commons.Utils; +using iText.Kernel.Crypto; using iText.Kernel.Exceptions; using iText.Signatures; using iText.Signatures.Exceptions; @@ -67,8 +68,8 @@ public class SignerInfo { /// Creates an empty SignerInfo structure. public SignerInfo() { - CmsAttribute contentType = new CmsAttribute(SecurityIDs.ID_CONTENT_TYPE, BC_FACTORY.CreateDERSet(BC_FACTORY - .CreateASN1ObjectIdentifier(SecurityIDs.ID_PKCS7_DATA))); + CmsAttribute contentType = new CmsAttribute(OID.CONTENT_TYPE, BC_FACTORY.CreateDERSet(BC_FACTORY.CreateASN1ObjectIdentifier + (OID.PKCS7_DATA))); signedAttributes.Add(contentType); unSignedAttributes = new List(); } @@ -132,8 +133,8 @@ public virtual void SetMessageDigest(byte[] digest) { if (signedAttributesReadOnly) { throw new InvalidOperationException(SignExceptionMessageConstant.CMS_SIGNERINFO_READONLY); } - CmsAttribute digestAttribute = new CmsAttribute(SecurityIDs.ID_MESSAGE_DIGEST, BC_FACTORY.CreateDERSet(BC_FACTORY - .CreateDEROctetString(digest))); + CmsAttribute digestAttribute = new CmsAttribute(OID.MESSAGE_DIGEST, BC_FACTORY.CreateDERSet(BC_FACTORY.CreateDEROctetString + (digest))); signedAttributes.Add(digestAttribute); } @@ -211,7 +212,7 @@ public virtual void AddSignerCertificateToSignedAttributes(IX509Certificate cert IMessageDigest md = DigestAlgorithms.GetMessageDigestFromOid(digestAlgorithmOid); IAsn1EncodableVector certContents = BC_FACTORY.CreateASN1EncodableVector(); // don't add if it is the default value - if (!SecurityIDs.ID_SHA256.Equals(digestAlgorithmOid)) { + if (!OID.SHA_256.Equals(digestAlgorithmOid)) { IAlgorithmIdentifier algoId = BC_FACTORY.CreateAlgorithmIdentifier(BC_FACTORY.CreateASN1ObjectIdentifier(digestAlgorithmOid )); certContents.Add(algoId); @@ -232,8 +233,7 @@ public virtual void AddSignerCertificateToSignedAttributes(IX509Certificate cert IDerSequence certContentsSeqSeq = BC_FACTORY.CreateDERSequence(certContentsSeq); IDerSequence certContentsSeqSeqSeq = BC_FACTORY.CreateDERSequence(certContentsSeqSeq); IDerSet certContentsSeqSeqSeqSet = BC_FACTORY.CreateDERSet(certContentsSeqSeqSeq); - CmsAttribute attribute = new CmsAttribute(SecurityIDs.ID_AA_SIGNING_CERTIFICATE_V2, certContentsSeqSeqSeqSet - ); + CmsAttribute attribute = new CmsAttribute(OID.AA_SIGNING_CERTIFICATE_V2, certContentsSeqSeqSeqSet); signedAttributes.Add(attribute); } @@ -321,6 +321,16 @@ public virtual void AddUnSignedAttribute(CmsAttribute attribute) { unSignedAttributes.Add(attribute); } + /// Removes unsigned attribute from signer info object based on attribute type. + /// + /// + /// + /// attribute type + /// + public virtual void RemoveUnSignedAttribute(String type) { + unSignedAttributes.RemoveIf((cmsAttribute) => cmsAttribute.GetType().Equals(type)); + } + /// Retrieves the encoded signed attributes of the signer info. /// /// Retrieves the encoded signed attributes of the signer info. @@ -488,13 +498,13 @@ private static ICollection ProcessAttributeSet(IAsn1Encodable asnS } private void SetRevocationInfo() { - signedAttributes.RemoveIf((a) => SecurityIDs.ID_ADBE_REVOCATION.Equals(a.GetType())); + signedAttributes.RemoveIf((a) => OID.ADBE_REVOCATION.Equals(a.GetType())); if (ContainsRevocationData()) { IAsn1EncodableVector revocationV = BC_FACTORY.CreateASN1EncodableVector(); CreateCRLStructure(revocationV); CreateOCPSStructure(revocationV); - CmsAttribute digestAttribute = new CmsAttribute(SecurityIDs.ID_ADBE_REVOCATION, BC_FACTORY.CreateDERSequence - (revocationV)); + CmsAttribute digestAttribute = new CmsAttribute(OID.ADBE_REVOCATION, BC_FACTORY.CreateDERSequence(revocationV + )); signedAttributes.Add(digestAttribute); } } diff --git a/itext/itext.sign/itext/signatures/exceptions/SignExceptionMessageConstant.cs b/itext/itext.sign/itext/signatures/exceptions/SignExceptionMessageConstant.cs index 4bafe8e572..1595678b1d 100644 --- a/itext/itext.sign/itext/signatures/exceptions/SignExceptionMessageConstant.cs +++ b/itext/itext.sign/itext/signatures/exceptions/SignExceptionMessageConstant.cs @@ -92,6 +92,8 @@ public sealed class SignExceptionMessageConstant { public const String NOT_ENOUGH_SPACE = "Not enough space."; + public const String NOT_POSSIBLE_TO_EMBED_MAC_TO_SIGNATURE = "It was not possible to embed MAC token into signature. Most likely signature container is empty."; + public const String PATH_IS_NOT_DIRECTORY = "Provided path: {0} is not a directory. " + "Please provide a directory path to store temporary pdf files which are required for signing."; public const String PROVIDED_TSA_CLIENT_IS_NULL = "Provided TSA client is null. TSA client is required for timestamp signing."; @@ -99,8 +101,6 @@ public sealed class SignExceptionMessageConstant { public const String SIGNATURE_WITH_THIS_NAME_IS_NOT_THE_LAST_IT_DOES_NOT_COVER_WHOLE_DOCUMENT = "Signature " + "with name {0} is not the last. It doesn't cover the whole document."; - public const String THE_NAME_OF_THE_DIGEST_ALGORITHM_IS_NULL = "The name of the digest algorithm is null."; - public const String THERE_IS_NO_FIELD_IN_THE_DOCUMENT_WITH_SUCH_NAME = "There is no field in the document " + "with such name: {0}."; diff --git a/itext/itext.sign/itext/signatures/logs/SignLogMessageConstant.cs b/itext/itext.sign/itext/signatures/logs/SignLogMessageConstant.cs index 60210af3a8..2cc3144c0b 100644 --- a/itext/itext.sign/itext/signatures/logs/SignLogMessageConstant.cs +++ b/itext/itext.sign/itext/signatures/logs/SignLogMessageConstant.cs @@ -25,8 +25,6 @@ You should have received a copy of the GNU Affero General Public License namespace iText.Signatures.Logs { /// Class which contains constants to be used in logging inside sign module. public sealed class SignLogMessageConstant { - public const String ALGORITHM_NOT_FROM_SPEC = "Requested algorithm might not be supported by the pdf specification."; - public const String EXCEPTION_WITHOUT_MESSAGE = "Unexpected exception without message was thrown during keystore processing"; public const String UNABLE_TO_PARSE_AIA_CERT = "Unable to parse certificates coming from authority info " diff --git a/itext/itext.sign/itext/signatures/mac/SignatureContainerGenerationEvent.cs b/itext/itext.sign/itext/signatures/mac/SignatureContainerGenerationEvent.cs new file mode 100644 index 0000000000..9f6256a009 --- /dev/null +++ b/itext/itext.sign/itext/signatures/mac/SignatureContainerGenerationEvent.cs @@ -0,0 +1,105 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using System.IO; +using iText.Commons.Bouncycastle.Asn1; +using iText.Kernel.Pdf.Event; + +namespace iText.Signatures.Mac { + /// Represents an event firing before creating signature container. + public class SignatureContainerGenerationEvent : AbstractPdfDocumentEvent { + public const String START_SIGNATURE_CONTAINER_GENERATION = "StartSignatureContainerGeneration"; + + private readonly IAsn1EncodableVector unsignedAttributes; + + private readonly byte[] signature; + + private readonly Stream documentInputStream; + + /// Creates an event firing before creating the signature container. + /// + /// + /// + /// unsigned signature attributes + /// + /// + /// + /// byte[] + /// signature value + /// + /// + /// + /// + /// containing document bytes considering byte range + /// + public SignatureContainerGenerationEvent(IAsn1EncodableVector unsignedAttributes, byte[] signature, Stream + documentInputStream) + : base(START_SIGNATURE_CONTAINER_GENERATION) { + this.unsignedAttributes = unsignedAttributes; + this.signature = signature; + this.documentInputStream = documentInputStream; + } + + /// + /// Gets + /// + /// unsigned signature attributes. + /// + /// + /// + /// + /// unsigned signature attributes + /// + public virtual IAsn1EncodableVector GetUnsignedAttributes() { + return unsignedAttributes; + } + + /// + /// Gets + /// byte[] + /// signature value. + /// + /// + /// + /// byte[] + /// signature value + /// + public virtual byte[] GetSignature() { + return signature; + } + + /// + /// Gets + /// + /// containing document bytes considering byte range. + /// + /// + /// + /// + /// containing document bytes considering byte range + /// + public virtual Stream GetDocumentInputStream() { + return documentInputStream; + } + } +} diff --git a/itext/itext.sign/itext/signatures/mac/SignatureDocumentClosingEvent.cs b/itext/itext.sign/itext/signatures/mac/SignatureDocumentClosingEvent.cs new file mode 100644 index 0000000000..29148c215b --- /dev/null +++ b/itext/itext.sign/itext/signatures/mac/SignatureDocumentClosingEvent.cs @@ -0,0 +1,63 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Event; + +namespace iText.Signatures.Mac { + /// Represents an event firing before embedding the signature into the document. + public class SignatureDocumentClosingEvent : AbstractPdfDocumentEvent { + public const String START_SIGNATURE_PRE_CLOSE = "StartSignaturePreClose"; + + private readonly PdfIndirectReference signatureReference; + + /// Creates an event firing before embedding the signature into the document. + /// + /// Creates an event firing before embedding the signature into the document. + /// It contains the reference to the signature object. + /// + /// + /// + /// + /// to the signature object + /// + public SignatureDocumentClosingEvent(PdfIndirectReference signatureReference) + : base(START_SIGNATURE_PRE_CLOSE) { + this.signatureReference = signatureReference; + } + + /// + /// Gets + /// + /// to the signature object. + /// + /// + /// + /// + /// to the signature object + /// + public virtual PdfIndirectReference GetSignatureReference() { + return signatureReference; + } + } +} diff --git a/itext/itext.sign/itext/signatures/mac/SignatureMacContainerLocator.cs b/itext/itext.sign/itext/signatures/mac/SignatureMacContainerLocator.cs new file mode 100644 index 0000000000..a625b578a3 --- /dev/null +++ b/itext/itext.sign/itext/signatures/mac/SignatureMacContainerLocator.cs @@ -0,0 +1,75 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using iText.Kernel.Mac; +using iText.Kernel.Pdf; + +namespace iText.Signatures.Mac { + /// + /// + /// strategy, which should be used specifically in case of signature creation. + /// + /// + /// + /// strategy, which should be used specifically in case of signature creation. + /// This strategy locates MAC container in signature unsigned attributes. + /// + public class SignatureMacContainerLocator : IMacContainerLocator { + private bool macContainerLocated = false; + + /// + /// . + /// + public virtual void LocateMacContainer(AbstractMacIntegrityProtector macIntegrityProtector) { + ((SignatureMacIntegrityProtector)macIntegrityProtector).PrepareDocument(); + macContainerLocated = true; + } + + /// + /// . + /// + public virtual bool IsMacContainerLocated() { + return macContainerLocated; + } + + /// + /// . + /// + public virtual AbstractMacIntegrityProtector CreateMacIntegrityProtector(PdfDocument document, MacProperties + macProperties) { + return new SignatureMacIntegrityProtector(document, macProperties); + } + + /// + /// . + /// + public virtual AbstractMacIntegrityProtector CreateMacIntegrityProtector(PdfDocument document, PdfDictionary + authDictionary) { + return new SignatureMacIntegrityProtector(document, authDictionary); + } + + /// + public virtual void HandleMacValidationError(MacValidationException exception) { + throw exception; + } + } +} diff --git a/itext/itext.sign/itext/signatures/mac/SignatureMacIntegrityProtector.cs b/itext/itext.sign/itext/signatures/mac/SignatureMacIntegrityProtector.cs new file mode 100644 index 0000000000..97ff710071 --- /dev/null +++ b/itext/itext.sign/itext/signatures/mac/SignatureMacIntegrityProtector.cs @@ -0,0 +1,120 @@ +/* +This file is part of the iText (R) project. +Copyright (c) 1998-2024 Apryse Group NV +Authors: Apryse Software. + +This program is offered under a commercial and under the AGPL license. +For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. + +AGPL licensing: +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +*/ +using System; +using System.IO; +using iText.Bouncycastleconnector; +using iText.Commons.Bouncycastle; +using iText.Commons.Bouncycastle.Asn1; +using iText.Commons.Bouncycastle.Security; +using iText.Kernel.Exceptions; +using iText.Kernel.Mac; +using iText.Kernel.Pdf; +using iText.Kernel.Pdf.Event; + +namespace iText.Signatures.Mac { +//\cond DO_NOT_DOCUMENT + /// Class responsible for integrity protection in encrypted documents which uses MAC container in the signature mode. + /// + internal class SignatureMacIntegrityProtector : AbstractMacIntegrityProtector { + private static readonly IBouncyCastleFactory BC_FACTORY = BouncyCastleFactoryCreator.GetFactory(); + + private const String ID_ATTR_PDF_MAC_DATA = "1.0.32004.1.2"; + +//\cond DO_NOT_DOCUMENT + internal SignatureMacIntegrityProtector(PdfDocument document, MacProperties macProperties) + : base(document, macProperties) { + } +//\endcond + +//\cond DO_NOT_DOCUMENT + internal SignatureMacIntegrityProtector(PdfDocument document, PdfDictionary authDictionary) + : base(document, authDictionary) { + } +//\endcond + +//\cond DO_NOT_DOCUMENT + internal virtual void PrepareDocument() { + document.AddEventHandler(SignatureDocumentClosingEvent.START_SIGNATURE_PRE_CLOSE, new SignatureMacIntegrityProtector.SignatureMacPdfObjectAdder + (this)); + document.AddEventHandler(SignatureContainerGenerationEvent.START_SIGNATURE_CONTAINER_GENERATION, new SignatureMacIntegrityProtector.SignatureMacContainerEmbedder + (this)); + } +//\endcond + + private void EmbedMacContainerInUnsignedAttributes(IAsn1EncodableVector unsignedAttributes, Stream documentInputStream + , byte[] signature) { + IDerSequence mac; + try { + byte[] dataDigest = DigestBytes(documentInputStream); + mac = CreateMacContainer(dataDigest, GenerateRandomBytes(32), signature); + } + catch (AbstractGeneralSecurityException e) { + throw new PdfException(KernelExceptionMessageConstant.CONTAINER_GENERATION_EXCEPTION, e); + } + IAsn1EncodableVector macAttribute = BC_FACTORY.CreateASN1EncodableVector(); + macAttribute.Add(BC_FACTORY.CreateASN1ObjectIdentifier(ID_ATTR_PDF_MAC_DATA)); + macAttribute.Add(BC_FACTORY.CreateDERSet(mac)); + unsignedAttributes.Add(BC_FACTORY.CreateDERSequence(macAttribute)); + } + + private sealed class SignatureMacPdfObjectAdder : AbstractPdfDocumentEventHandler { + protected override void OnAcceptedEvent(AbstractPdfDocumentEvent @event) { + if (@event is SignatureDocumentClosingEvent) { + PdfDictionary signatureMacDictionary = new PdfDictionary(); + signatureMacDictionary.Put(PdfName.MACLocation, PdfName.AttachedToSig); + signatureMacDictionary.Put(PdfName.SigObjRef, ((SignatureDocumentClosingEvent)@event).GetSignatureReference + ()); + this._enclosing.document.GetTrailer().Put(PdfName.AuthCode, signatureMacDictionary); + } + } + + internal SignatureMacPdfObjectAdder(SignatureMacIntegrityProtector _enclosing) { + this._enclosing = _enclosing; + } + + private readonly SignatureMacIntegrityProtector _enclosing; + } + + private sealed class SignatureMacContainerEmbedder : AbstractPdfDocumentEventHandler { + protected override void OnAcceptedEvent(AbstractPdfDocumentEvent @event) { + if (@event is SignatureContainerGenerationEvent) { + SignatureContainerGenerationEvent signatureEvent = (SignatureContainerGenerationEvent)@event; + try { + this._enclosing.EmbedMacContainerInUnsignedAttributes(signatureEvent.GetUnsignedAttributes(), signatureEvent + .GetDocumentInputStream(), signatureEvent.GetSignature()); + } + catch (System.IO.IOException e) { + throw new PdfException(KernelExceptionMessageConstant.CONTAINER_EMBEDDING_EXCEPTION, e); + } + } + } + + internal SignatureMacContainerEmbedder(SignatureMacIntegrityProtector _enclosing) { + this._enclosing = _enclosing; + } + + private readonly SignatureMacIntegrityProtector _enclosing; + } + } +//\endcond +} diff --git a/itext/itext.sign/itext/signatures/validation/v1/CRLValidator.cs b/itext/itext.sign/itext/signatures/validation/CRLValidator.cs similarity index 82% rename from itext/itext.sign/itext/signatures/validation/v1/CRLValidator.cs rename to itext/itext.sign/itext/signatures/validation/CRLValidator.cs index 1084c171d1..681633ed90 100644 --- a/itext/itext.sign/itext/signatures/validation/v1/CRLValidator.cs +++ b/itext/itext.sign/itext/signatures/validation/CRLValidator.cs @@ -22,6 +22,7 @@ You should have received a copy of the GNU Affero General Public License */ using System; using System.Collections.Generic; +using System.Linq; using iText.Bouncycastleconnector; using iText.Commons.Bouncycastle; using iText.Commons.Bouncycastle.Asn1; @@ -30,11 +31,11 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Utils; using iText.Signatures; using iText.Signatures.Logs; -using iText.Signatures.Validation.V1.Context; -using iText.Signatures.Validation.V1.Extensions; -using iText.Signatures.Validation.V1.Report; +using iText.Signatures.Validation.Context; +using iText.Signatures.Validation.Extensions; +using iText.Signatures.Validation.Report; -namespace iText.Signatures.Validation.V1 { +namespace iText.Signatures.Validation { /// Class that allows you to validate a certificate against a Certificate Revocation List (CRL) Response. /// public class CRLValidator { @@ -99,6 +100,11 @@ public class CRLValidator { internal const String UPDATE_DATE_BEFORE_CHECK_DATE = "nextUpdate: {0} of CRLResponse is before validation date {1}."; //\endcond +//\cond DO_NOT_DOCUMENT + internal const String CERTIFICATE_IN_ISSUER_CHAIN = "Unable to validate CRL response: validated certificate is" + + " part of issuer certificate chain."; +//\endcond + //\cond DO_NOT_DOCUMENT // All reasons without unspecified. internal const int ALL_REASONS = 32895; @@ -130,18 +136,6 @@ protected internal CRLValidator(ValidatorChainBuilder builder) { this.builder = builder; } - /// Validates a certificate against Certificate Revocation List (CRL) Responses. - /// to store all the chain verification results - /// the context in which to perform the validation - /// the certificate to check against CRL response - /// the crl response to be validated - /// validation date to check for - [System.ObsoleteAttribute(@"starting from 8.0.5. TODO DEVSIX-8398 To be removed.")] - public virtual void Validate(ValidationReport report, ValidationContext context, IX509Certificate certificate - , IX509Crl crl, DateTime validationDate) { - Validate(report, context, certificate, crl, validationDate, DateTimeUtil.GetCurrentUtcTime()); - } - /// Validates a certificate against Certificate Revocation List (CRL) Responses. /// to store all the chain verification results /// the context in which to perform the validation @@ -305,42 +299,60 @@ private static int ComputeInterimReasonsMask(IIssuingDistributionPoint issuingDi private void VerifyCrlIntegrity(ValidationReport report, ValidationContext context, IX509Certificate certificate , IX509Crl crl, DateTime responseGenerationDate) { - IX509Certificate[] certs = null; + IX509Certificate[][] certificateSets = null; try { - certs = certificateRetriever.GetCrlIssuerCertificates(crl); + certificateSets = certificateRetriever.GetCrlIssuerCertificatesByName(crl); } catch (Exception e) { report.AddReportItem(new CertificateReportItem(certificate, CRL_CHECK, CRL_ISSUER_REQUEST_FAILED, e, ReportItem.ReportItemStatus .INDETERMINATE)); return; } - if (certs == null || certs.Length == 0) { + if (certificateSets == null || certificateSets.Length == 0) { report.AddReportItem(new CertificateReportItem(certificate, CRL_CHECK, CRL_ISSUER_NOT_FOUND, ReportItem.ReportItemStatus .INDETERMINATE)); return; } - IX509Certificate crlIssuer = certs[0]; - IX509Certificate crlIssuerRoot = GetRoot(crlIssuer); - IX509Certificate subjectRoot = GetRoot(certificate); - if (!crlIssuerRoot.Equals(subjectRoot)) { - report.AddReportItem(new CertificateReportItem(certificate, CRL_CHECK, CRL_ISSUER_NO_COMMON_ROOT, ReportItem.ReportItemStatus - .INDETERMINATE)); - return; + ValidationReport[] candidateReports = new ValidationReport[certificateSets.Length]; + for (int i = 0; i < certificateSets.Length; i++) { + ValidationReport candidateReport = new ValidationReport(); + candidateReports[i] = candidateReport; + IX509Certificate[] certs = certificateSets[i]; + if (JavaUtil.ArraysAsList(certs).Contains(certificate)) { + candidateReport.AddReportItem(new CertificateReportItem(certificate, CRL_CHECK, CERTIFICATE_IN_ISSUER_CHAIN + , ReportItem.ReportItemStatus.INDETERMINATE)); + continue; + } + IX509Certificate crlIssuer = certs[0]; + IList crlIssuerRoots = GetRoots(crlIssuer); + IList subjectRoots = GetRoots(certificate); + if (!crlIssuerRoots.Any((cert) => subjectRoots.Contains(cert))) { + candidateReport.AddReportItem(new CertificateReportItem(certificate, CRL_CHECK, CRL_ISSUER_NO_COMMON_ROOT, + ReportItem.ReportItemStatus.INDETERMINATE)); + continue; + } + SafeCalling.OnExceptionLog(() => crl.Verify(crlIssuer.GetPublicKey()), candidateReport, (e) => new CertificateReportItem + (certificate, CRL_CHECK, CRL_INVALID, e, ReportItem.ReportItemStatus.INDETERMINATE)); + ValidationReport responderReport = new ValidationReport(); + SafeCalling.OnExceptionLog(() => builder.GetCertificateChainValidator().Validate(responderReport, context. + SetCertificateSource(CertificateSource.CRL_ISSUER), (IX509Certificate)crlIssuer, responseGenerationDate + ), candidateReport, (e) => new CertificateReportItem(certificate, CRL_CHECK, CRL_ISSUER_CHAIN_FAILED, + e, ReportItem.ReportItemStatus.INDETERMINATE)); + AddResponderValidationReport(candidateReport, responderReport); + if (candidateReport.GetValidationResult() == ValidationReport.ValidationResult.VALID) { + report.Merge(candidateReport); + return; + } + } + // if failed, add all logs + foreach (ValidationReport candidateReport in candidateReports) { + report.Merge(candidateReport); } - SafeCalling.OnExceptionLog(() => crl.Verify(crlIssuer.GetPublicKey()), report, (e) => new CertificateReportItem - (certificate, CRL_CHECK, CRL_INVALID, e, ReportItem.ReportItemStatus.INDETERMINATE)); - ValidationReport responderReport = new ValidationReport(); - SafeCalling.OnExceptionLog(() => builder.GetCertificateChainValidator().Validate(responderReport, context. - SetCertificateSource(CertificateSource.CRL_ISSUER), (IX509Certificate)crlIssuer, responseGenerationDate - ), report, (e) => new CertificateReportItem(certificate, CRL_CHECK, CRL_ISSUER_CHAIN_FAILED, e, ReportItem.ReportItemStatus - .INDETERMINATE)); - AddResponderValidationReport(report, responderReport); } - private IX509Certificate GetRoot(IX509Certificate cert) { - IX509Certificate[] chain = certificateRetriever.RetrieveMissingCertificates(new IX509Certificate[] { cert } - ); - return chain[chain.Length - 1]; + private IList GetRoots(IX509Certificate cert) { + IList chains = certificateRetriever.BuildCertificateChains((IX509Certificate)cert); + return chains.Select((certArray) => certArray[certArray.Length - 1]).ToList(); } private static void AddResponderValidationReport(ValidationReport report, ValidationReport responderReport diff --git a/itext/itext.sign/itext/signatures/validation/v1/CertificateChainValidator.cs b/itext/itext.sign/itext/signatures/validation/CertificateChainValidator.cs similarity index 82% rename from itext/itext.sign/itext/signatures/validation/v1/CertificateChainValidator.cs rename to itext/itext.sign/itext/signatures/validation/CertificateChainValidator.cs index 52a9a126ac..8c510611a5 100644 --- a/itext/itext.sign/itext/signatures/validation/v1/CertificateChainValidator.cs +++ b/itext/itext.sign/itext/signatures/validation/CertificateChainValidator.cs @@ -26,11 +26,11 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Security; using iText.Commons.Utils; using iText.Signatures; -using iText.Signatures.Validation.V1.Context; -using iText.Signatures.Validation.V1.Extensions; -using iText.Signatures.Validation.V1.Report; +using iText.Signatures.Validation.Context; +using iText.Signatures.Validation.Extensions; +using iText.Signatures.Validation.Report; -namespace iText.Signatures.Validation.V1 { +namespace iText.Signatures.Validation { /// Validator class, which is expected to be used for certificates chain validation. public class CertificateChainValidator { //\cond DO_NOT_DOCUMENT @@ -114,49 +114,6 @@ protected internal CertificateChainValidator(ValidatorChainBuilder builder) { this.revocationDataValidator = builder.GetRevocationDataValidator(); } - /// - /// Add - /// - /// to be used for CRL responses receiving. - /// - /// - /// - /// - /// to be used for CRL responses receiving - /// - /// - /// same instance of - /// . - /// - [System.ObsoleteAttribute(@"in favour of either SignatureValidationProperties.AddCrlClient(iText.Signatures.ICrlClient) or RevocationDataValidator.AddCrlClient(iText.Signatures.ICrlClient) . TODO DEVSIX-8398 To be removed." - )] - public virtual iText.Signatures.Validation.V1.CertificateChainValidator AddCrlClient(ICrlClient crlClient) { - revocationDataValidator.AddCrlClient(crlClient); - return this; - } - - /// - /// Add - /// - /// to be used for OCSP responses receiving. - /// - /// - /// - /// - /// to be used for OCSP responses receiving - /// - /// - /// same instance of - /// . - /// - [System.ObsoleteAttribute(@"in favour of either SignatureValidationProperties.AddOcspClient(iText.Signatures.IOcspClient) or RevocationDataValidator.AddOcspClient(iText.Signatures.IOcspClient) . TODO DEVSIX-8398 To be removed." - )] - public virtual iText.Signatures.Validation.V1.CertificateChainValidator AddOcspClient(IOcspClient ocpsClient - ) { - revocationDataValidator.AddOcspClient(ocpsClient); - return this; - } - /// Validate given certificate using provided validation date and required extensions. /// the validation context in which to validate the certificate chain /// @@ -172,7 +129,7 @@ public virtual iText.Signatures.Validation.V1.CertificateChainValidator AddOcspC /// /// /// - /// + /// /// which contains detailed validation results. /// public virtual ValidationReport ValidateCertificate(ValidationContext context, IX509Certificate certificate @@ -188,7 +145,7 @@ public virtual ValidationReport ValidateCertificate(ValidationContext context, I /// /// /// - /// + /// /// which is populated with detailed validation results /// /// the context in which to perform the validation @@ -205,7 +162,7 @@ public virtual ValidationReport ValidateCertificate(ValidationContext context, I /// /// /// - /// + /// /// which contains both provided and new validation results. /// public virtual ValidationReport Validate(ValidationReport result, ValidationContext context, IX509Certificate @@ -348,37 +305,50 @@ private void ValidateRevocationData(ValidationReport report, ValidationContext c private void ValidateChain(ValidationReport result, ValidationContext context, IX509Certificate certificate , DateTime validationDate, int certificateChainSize) { - IX509Certificate issuerCertificate = null; + IList issuerCertificates; try { - issuerCertificate = (IX509Certificate)certificateRetriever.RetrieveIssuerCertificate(certificate); + issuerCertificates = certificateRetriever.RetrieveIssuerCertificate(certificate); } catch (Exception e) { result.AddReportItem(new CertificateReportItem(certificate, CERTIFICATE_CHECK, ISSUER_RETRIEVAL_FAILED, e, ReportItem.ReportItemStatus.INDETERMINATE)); return; } - if (issuerCertificate == null) { + if (issuerCertificates.IsEmpty()) { result.AddReportItem(new CertificateReportItem(certificate, CERTIFICATE_CHECK, MessageFormatUtil.Format(ISSUER_MISSING , certificate.GetSubjectDN()), ReportItem.ReportItemStatus.INDETERMINATE)); return; } - try { - certificate.Verify(issuerCertificate.GetPublicKey()); - } - catch (AbstractGeneralSecurityException e) { - result.AddReportItem(new CertificateReportItem(certificate, CERTIFICATE_CHECK, MessageFormatUtil.Format(ISSUER_CANNOT_BE_VERIFIED - , issuerCertificate.GetSubjectDN(), certificate.GetSubjectDN()), e, ReportItem.ReportItemStatus.INVALID - )); - return; + ValidationReport[] candidateReports = new ValidationReport[issuerCertificates.Count]; + for (int i = 0; i < issuerCertificates.Count; i++) { + candidateReports[i] = new ValidationReport(); + try { + certificate.Verify(issuerCertificates[i].GetPublicKey()); + } + catch (AbstractGeneralSecurityException e) { + candidateReports[i].AddReportItem(new CertificateReportItem(certificate, CERTIFICATE_CHECK, MessageFormatUtil + .Format(ISSUER_CANNOT_BE_VERIFIED, issuerCertificates[i].GetSubjectDN(), certificate.GetSubjectDN()), + e, ReportItem.ReportItemStatus.INVALID)); + continue; + } + catch (Exception e) { + candidateReports[i].AddReportItem(new CertificateReportItem(certificate, CERTIFICATE_CHECK, MessageFormatUtil + .Format(ISSUER_VERIFICATION_FAILED, issuerCertificates[i].GetSubjectDN(), certificate.GetSubjectDN()), + e, ReportItem.ReportItemStatus.INVALID)); + continue; + } + this.Validate(candidateReports[i], context.SetCertificateSource(CertificateSource.CERT_ISSUER), issuerCertificates + [i], validationDate, certificateChainSize + 1); + if (candidateReports[i].GetValidationResult() == ValidationReport.ValidationResult.VALID) { + // We found valid issuer, no need to try other ones. + result.Merge(candidateReports[i]); + return; + } } - catch (Exception e) { - result.AddReportItem(new CertificateReportItem(certificate, CERTIFICATE_CHECK, MessageFormatUtil.Format(ISSUER_VERIFICATION_FAILED - , issuerCertificate.GetSubjectDN(), certificate.GetSubjectDN()), e, ReportItem.ReportItemStatus.INVALID - )); - return; + // Valid issuer wasn't found, add all the reports + foreach (ValidationReport candidateReport in candidateReports) { + result.Merge(candidateReport); } - this.Validate(result, context.SetCertificateSource(CertificateSource.CERT_ISSUER), issuerCertificate, validationDate - , certificateChainSize + 1); } } } diff --git a/itext/itext.sign/itext/signatures/validation/v1/DocumentRevisionsValidator.cs b/itext/itext.sign/itext/signatures/validation/DocumentRevisionsValidator.cs similarity index 88% rename from itext/itext.sign/itext/signatures/validation/v1/DocumentRevisionsValidator.cs rename to itext/itext.sign/itext/signatures/validation/DocumentRevisionsValidator.cs index 761030c79d..66e1bcaa3d 100644 --- a/itext/itext.sign/itext/signatures/validation/v1/DocumentRevisionsValidator.cs +++ b/itext/itext.sign/itext/signatures/validation/DocumentRevisionsValidator.cs @@ -31,10 +31,10 @@ You should have received a copy of the GNU Affero General Public License using iText.IO.Source; using iText.Kernel.Pdf; using iText.Signatures; -using iText.Signatures.Validation.V1.Context; -using iText.Signatures.Validation.V1.Report; +using iText.Signatures.Validation.Context; +using iText.Signatures.Validation.Report; -namespace iText.Signatures.Validation.V1 { +namespace iText.Signatures.Validation { /// Validator, which is responsible for document revisions validation according to doc-MDP and field-MDP rules. /// public class DocumentRevisionsValidator { @@ -103,10 +103,6 @@ public class DocumentRevisionsValidator { internal const String FIELD_REMOVED = "Form field {0} was removed or unexpectedly modified."; //\endcond -//\cond DO_NOT_DOCUMENT - internal const String LINEARIZED_NOT_SUPPORTED = "Linearized PDF documents are not supported by DocumentRevisionsValidator."; -//\endcond - //\cond DO_NOT_DOCUMENT internal const String LOCKED_FIELD_KIDS_ADDED = "Kids were added to locked form field \"{0}\"."; //\endcond @@ -136,11 +132,12 @@ public class DocumentRevisionsValidator { //\endcond //\cond DO_NOT_DOCUMENT - internal const String OBJECT_REMOVED = "Object \"{0}\", which is not allowed to be removed, was removed from the document through XREF table."; + internal const String NOT_ALLOWED_CERTIFICATION_SIGNATURE = "Certification signature is applied after " + + "the approval signature which is not allowed."; //\endcond //\cond DO_NOT_DOCUMENT - internal const String OUTLINES_MODIFIED = "Outlines entry in catalog dictionary was modified. " + "iText currently cannot identify if these modifications are allowed."; + internal const String OBJECT_REMOVED = "Object \"{0}\", which is not allowed to be removed, was removed from the document through XREF table."; //\endcond //\cond DO_NOT_DOCUMENT @@ -261,6 +258,8 @@ public class DocumentRevisionsValidator { private ICollection addedTaggedObjects; + private Pair, ICollection> usuallyModifiedObjects; + /// /// Creates new instance of /// . @@ -286,8 +285,8 @@ protected internal DocumentRevisionsValidator(ValidatorChainBuilder chainBuilder /// /// instance. /// - public virtual iText.Signatures.Validation.V1.DocumentRevisionsValidator SetEventCountingMetaInfo(IMetaInfo - metaInfo) { + public virtual iText.Signatures.Validation.DocumentRevisionsValidator SetEventCountingMetaInfo(IMetaInfo metaInfo + ) { this.metaInfo = metaInfo; return this; } @@ -307,7 +306,7 @@ public virtual iText.Signatures.Validation.V1.DocumentRevisionsValidator SetEven /// /// instance. /// - public virtual iText.Signatures.Validation.V1.DocumentRevisionsValidator SetAccessPermissions(AccessPermissions + public virtual iText.Signatures.Validation.DocumentRevisionsValidator SetAccessPermissions(AccessPermissions accessPermissions) { this.requestedAccessPermissions = accessPermissions; return this; @@ -320,11 +319,11 @@ public virtual iText.Signatures.Validation.V1.DocumentRevisionsValidator SetAcce /// /// Set the status to be used for the report items produced during docMDP validation in case revision contains /// unexpected changes in the XREF table. Default value is - /// . + /// . /// /// /// - /// + /// /// to be used in case of unexpected changes in the XREF table /// /// @@ -332,7 +331,7 @@ public virtual iText.Signatures.Validation.V1.DocumentRevisionsValidator SetAcce /// /// instance. /// - public virtual iText.Signatures.Validation.V1.DocumentRevisionsValidator SetUnexpectedXrefChangesStatus(ReportItem.ReportItemStatus + public virtual iText.Signatures.Validation.DocumentRevisionsValidator SetUnexpectedXrefChangesStatus(ReportItem.ReportItemStatus status) { this.unexpectedXrefChangesStatus = status; return this; @@ -343,11 +342,30 @@ public virtual iText.Signatures.Validation.V1.DocumentRevisionsValidator SetUnex /// the document to be validated /// /// - /// + /// /// which contains detailed validation results. /// public virtual ValidationReport ValidateAllDocumentRevisions(ValidationContext context, PdfDocument document ) { + return ValidateAllDocumentRevisions(context, document, null); + } + +//\cond DO_NOT_DOCUMENT + /// + /// Validate all document revisions according to docMDP and fieldMDP transform methods and collect validation report + /// related to the single signature field checks if specified. + /// + /// the validation context in which to validate document revisions + /// the document to be validated + /// signature field to collect validation result for. If null, all signatures will be checked + /// + /// + /// + /// + /// which contains detailed validation results. + /// + internal virtual ValidationReport ValidateAllDocumentRevisions(ValidationContext context, PdfDocument document + , String signatureName) { ResetClassFields(); ValidationContext localContext = context.SetValidatorContext(ValidatorContext.DOCUMENT_REVISIONS_VALIDATOR ); @@ -368,6 +386,7 @@ public virtual ValidationReport ValidateAllDocumentRevisions(ValidationContext c .INDETERMINATE)); return report; } + MergeRevisionsInLinearizedDocument(document, documentRevisions); SignatureUtil signatureUtil = new SignatureUtil(document); IList signatures = new List(signatureUtil.GetSignatureNames()); if (signatures.IsEmpty()) { @@ -375,48 +394,71 @@ public virtual ValidationReport ValidateAllDocumentRevisions(ValidationContext c .INFO)); return report; } - bool signatureFound = false; + bool updateAccessPermissions = true; + bool documentSigned = false; bool certificationSignatureFound = false; - PdfSignature currentSignature = signatureUtil.GetSignature(signatures[0]); + bool collectRevisionsValidationReport = signatureName == null; + String currentSignatureName = signatures[0]; + PdfSignature currentSignature = signatureUtil.GetSignature(currentSignatureName); for (int i = 0; i < documentRevisions.Count; i++) { - if (currentSignature != null && RevisionContainsSignature(documentRevisions[i], signatures[0], document, report - )) { - signatureFound = true; + if (currentSignature != null && RevisionContainsSignature(documentRevisions[i], currentSignatureName, document + , report)) { if (IsCertificationSignature(currentSignature)) { if (certificationSignatureFound) { report.AddReportItem(new ReportItem(DOC_MDP_CHECK, TOO_MANY_CERTIFICATION_SIGNATURES, ReportItem.ReportItemStatus .INDETERMINATE)); } else { - certificationSignatureFound = true; - UpdateCertificationSignatureAccessPermissions(currentSignature, report); + if (documentSigned) { + report.AddReportItem(new ReportItem(DOC_MDP_CHECK, NOT_ALLOWED_CERTIFICATION_SIGNATURE, ReportItem.ReportItemStatus + .INDETERMINATE)); + } + else { + certificationSignatureFound = true; + if (updateAccessPermissions) { + UpdateCertificationSignatureAccessPermissions(currentSignature, report); + } + } } } - UpdateApprovalSignatureAccessPermissions(signatureUtil.GetSignatureFormFieldDictionary(signatures[0]), report - ); - UpdateApprovalSignatureFieldLock(documentRevisions[i], signatureUtil.GetSignatureFormFieldDictionary(signatures - [0]), document, report); + documentSigned = true; + if (updateAccessPermissions) { + UpdateApprovalSignatureAccessPermissions(signatureUtil.GetSignatureFormFieldDictionary(currentSignatureName + ), report); + UpdateApprovalSignatureFieldLock(documentRevisions[i], signatureUtil.GetSignatureFormFieldDictionary(currentSignatureName + ), document, report); + } + if (signatureName != null && signatureName.Equals(currentSignatureName)) { + updateAccessPermissions = false; + collectRevisionsValidationReport = true; + } signatures.JRemoveAt(0); if (signatures.IsEmpty()) { currentSignature = null; } else { - currentSignature = signatureUtil.GetSignature(signatures[0]); + currentSignatureName = signatures[0]; + currentSignature = signatureUtil.GetSignature(currentSignatureName); } } - if (signatureFound && i < documentRevisions.Count - 1) { - ValidateRevision(documentRevisions[i], documentRevisions[i + 1], document, report, localContext); + if (documentSigned && i < documentRevisions.Count - 1) { + ValidationReport validationReport = new ValidationReport(); + ValidateRevision(documentRevisions[i], documentRevisions[i + 1], document, validationReport, localContext); + if (collectRevisionsValidationReport) { + report.Merge(validationReport); + } } if (StopValidation(report, localContext)) { break; } } - if (!signatureFound) { + if (!documentSigned) { report.AddReportItem(new ReportItem(DOC_MDP_CHECK, SIGNATURE_REVISION_NOT_FOUND, ReportItem.ReportItemStatus .INVALID)); } return report; } +//\endcond //\cond DO_NOT_DOCUMENT internal virtual void ValidateRevision(DocumentRevision previousRevision, DocumentRevision currentRevision @@ -428,16 +470,40 @@ internal virtual void ValidateRevision(DocumentRevision previousRevision, Docume } //\endcond + private void MergeRevisionsInLinearizedDocument(PdfDocument document, IList documentRevisions + ) { + if (documentRevisions.Count > 1) { + // We need to check if document is linearized in first revision + // We don't need to populate validation report in case of exceptions, it will happen later + CreateDocumentAndPerformOperation(documentRevisions[0], document, new ValidationReport(), (firstRevisionDocument + ) => { + if (IsLinearizedPdf(document)) { + ICollection mergedModifiedReferences = new HashSet(documentRevisions + [0].GetModifiedObjects()); + mergedModifiedReferences.AddAll(documentRevisions[1].GetModifiedObjects()); + DocumentRevision mergedRevision = new DocumentRevision(documentRevisions[0].GetEofOffset(), mergedModifiedReferences + ); + documentRevisions.Add(0, mergedRevision); + documentRevisions.JRemoveAt(1); + documentRevisions.JRemoveAt(1); + } + return true; + } + ); + } + } + private bool ValidateRevision(ValidationReport validationReport, ValidationContext context, PdfDocument documentWithoutRevision , PdfDocument documentWithRevision, DocumentRevision currentRevision) { - ICollection indirectReferences = currentRevision.GetModifiedObjects(); + usuallyModifiedObjects = new Pair, ICollection>(CreateUsuallyModifiedObjectsSet + (documentWithoutRevision), CreateUsuallyModifiedObjectsSet(documentWithRevision)); if (!CompareCatalogs(documentWithoutRevision, documentWithRevision, validationReport, context)) { return false; } ICollection currentAllowedReferences = CreateAllowedReferences(documentWithRevision); ICollection previousAllowedReferences = CreateAllowedReferences(documentWithoutRevision ); - foreach (PdfIndirectReference indirectReference in indirectReferences) { + foreach (PdfIndirectReference indirectReference in currentRevision.GetModifiedObjects()) { if (indirectReference.IsFree()) { // In this boolean flag we check that reference which is about to be removed is the one which // changed in the new revision. For instance DSS reference was 5 0 obj and changed to be 6 0 obj. @@ -681,8 +747,8 @@ private bool CreateDocumentAndPerformOperation(DocumentRevision revision, PdfDoc report, Func operation) { try { using (Stream inputStream = CreateInputStreamFromRevision(originalDocument, revision)) { - using (PdfReader reader = new PdfReader(inputStream).SetStrictnessLevel(PdfReader.StrictnessLevel.CONSERVATIVE - )) { + using (PdfReader reader = new PdfReader(inputStream, originalDocument.GetReader().GetPropertiesCopy()).SetStrictnessLevel + (PdfReader.StrictnessLevel.CONSERVATIVE)) { using (PdfDocument documentWithRevision = new PdfDocument(reader, new DocumentProperties().SetEventCountingMetaInfo (metaInfo))) { return (bool)operation.Invoke(documentWithRevision); @@ -691,25 +757,13 @@ private bool CreateDocumentAndPerformOperation(DocumentRevision revision, PdfDoc } } catch (System.IO.IOException exception) { - if (IsLinearizedPdf(originalDocument)) { - report.AddReportItem(new ReportItem(DOC_MDP_CHECK, LINEARIZED_NOT_SUPPORTED, exception, ReportItem.ReportItemStatus - .INDETERMINATE)); - } - else { - report.AddReportItem(new ReportItem(DOC_MDP_CHECK, REVISIONS_READING_EXCEPTION, exception, ReportItem.ReportItemStatus - .INDETERMINATE)); - } + report.AddReportItem(new ReportItem(DOC_MDP_CHECK, REVISIONS_READING_EXCEPTION, exception, ReportItem.ReportItemStatus + .INDETERMINATE)); return false; } catch (Exception exception) { - if (IsLinearizedPdf(originalDocument)) { - report.AddReportItem(new ReportItem(DOC_MDP_CHECK, LINEARIZED_NOT_SUPPORTED, exception, ReportItem.ReportItemStatus - .INDETERMINATE)); - } - else { - report.AddReportItem(new ReportItem(DOC_MDP_CHECK, REVISIONS_READING_EXCEPTION, exception, ReportItem.ReportItemStatus - .INDETERMINATE)); - } + report.AddReportItem(new ReportItem(DOC_MDP_CHECK, REVISIONS_READING_EXCEPTION, exception, ReportItem.ReportItemStatus + .INDETERMINATE)); return false; } } @@ -732,7 +786,7 @@ private bool CompareCatalogs(PdfDocument documentWithoutRevision, PdfDocument do PdfDictionary currentCatalogCopy = CopyCatalogEntriesToCompare(currentCatalog); removedTaggedObjects = new HashSet(); addedTaggedObjects = new HashSet(); - if (!ComparePdfObjects(previousCatalogCopy, currentCatalogCopy)) { + if (!ComparePdfObjects(previousCatalogCopy, currentCatalogCopy, usuallyModifiedObjects)) { report.AddReportItem(new ReportItem(DOC_MDP_CHECK, NOT_ALLOWED_CATALOG_CHANGES, ReportItem.ReportItemStatus .INVALID)); return false; @@ -765,27 +819,11 @@ private bool CompareCatalogs(PdfDocument documentWithoutRevision, PdfDocument do if (StopValidation(report, context)) { return result; } - result = result && CompareStructTreeRoot(previousCatalog.Get(PdfName.StructTreeRoot), currentCatalog.Get(PdfName + return result && CompareStructTreeRoot(previousCatalog.Get(PdfName.StructTreeRoot), currentCatalog.Get(PdfName .StructTreeRoot), report); - if (StopValidation(report, context)) { - return result; - } - result = result && CompareOutlines(previousCatalog.Get(PdfName.Outlines), currentCatalog.Get(PdfName.Outlines - ), report); - return result; } // Compare catalogs nested methods section: - private bool CompareOutlines(PdfObject previousOutlines, PdfObject currentOutlines, ValidationReport report - ) { - if (!ComparePdfObjects(previousOutlines, currentOutlines)) { - report.AddReportItem(new ReportItem(DOC_MDP_CHECK, OUTLINES_MODIFIED, ReportItem.ReportItemStatus.INDETERMINATE - )); - return false; - } - return true; - } - private bool CompareStructTreeRoot(PdfObject previousStructTreeRoot, PdfObject currentStructTreeRoot, ValidationReport report) { if (previousStructTreeRoot == currentStructTreeRoot) { @@ -814,7 +852,7 @@ private bool CompareStructTreeRoot(PdfObject previousStructTreeRoot, PdfObject c } } if (!(previousStructTreeRoot is PdfDictionary)) { - if (ComparePdfObjects(previousStructTreeRoot, currentStructTreeRoot)) { + if (ComparePdfObjects(previousStructTreeRoot, currentStructTreeRoot, usuallyModifiedObjects)) { return true; } else { @@ -836,7 +874,7 @@ private bool CompareStructTreeRoot(PdfObject previousStructTreeRoot, PdfObject c previousStructTreeRootDict.Remove(PdfName.K); currentStructTreeRootDict.Remove(PdfName.K); // Everything else is expected to remain unmodified and compared directly. - if (!ComparePdfObjects(previousStructTreeRootDict, currentStructTreeRootDict)) { + if (!ComparePdfObjects(previousStructTreeRootDict, currentStructTreeRootDict, usuallyModifiedObjects)) { report.AddReportItem(new ReportItem(DOC_MDP_CHECK, STRUCT_TREE_ROOT_MODIFIED, ReportItem.ReportItemStatus. INVALID)); return false; @@ -955,7 +993,7 @@ private bool CompareStructTreeElements(PdfDictionary previousStructElement, PdfD currentStructElementCopy.Remove(PdfName.P); currentStructElementCopy.Remove(PdfName.Ref); currentStructElementCopy.Remove(PdfName.Pg); - if (!ComparePdfObjects(previousStructElementCopy, currentStructElementCopy)) { + if (!ComparePdfObjects(previousStructElementCopy, currentStructElementCopy, usuallyModifiedObjects)) { report.AddReportItem(new ReportItem(DOC_MDP_CHECK, STRUCT_TREE_ELEMENT_MODIFIED, ReportItem.ReportItemStatus .INVALID)); return false; @@ -978,7 +1016,8 @@ private bool CompareStructTreeContents(PdfObject previousStructTreeContent, PdfO PdfDictionary currentContentDictionaryCopy = new PdfDictionary(currentContentDictionary); currentContentDictionaryCopy.Remove(PdfName.Pg); currentContentDictionaryCopy.Remove(PdfName.Obj); - if (!ComparePdfObjects(previousContentDictionaryCopy, currentContentDictionaryCopy)) { + if (!ComparePdfObjects(previousContentDictionaryCopy, currentContentDictionaryCopy, usuallyModifiedObjects + )) { report.AddReportItem(new ReportItem(DOC_MDP_CHECK, STRUCT_TREE_CONTENT_MODIFIED, ReportItem.ReportItemStatus .INVALID)); return false; @@ -989,13 +1028,14 @@ private bool CompareStructTreeContents(PdfObject previousStructTreeContent, PdfO ); } else { - return ComparePdfObjects(previousStructTreeContent, currentStructTreeContent); + return ComparePdfObjects(previousStructTreeContent, currentStructTreeContent, usuallyModifiedObjects); } } private bool CompareExtensions(PdfObject previousExtensions, PdfObject currentExtensions, ValidationReport report) { - if (previousExtensions == null || ComparePdfObjects(previousExtensions, currentExtensions)) { + if (previousExtensions == null || ComparePdfObjects(previousExtensions, currentExtensions, usuallyModifiedObjects + )) { return true; } if (currentExtensions == null) { @@ -1025,7 +1065,7 @@ private bool CompareExtensions(PdfObject previousExtensions, PdfObject currentEx previousExtensionCopy.Remove(PdfName.ExtensionLevel); previousExtensionCopy.Remove(PdfName.BaseVersion); // Apart from extension level and base version dictionaries are expected to be equal. - if (!ComparePdfObjects(previousExtensionCopy, currentExtensionCopy)) { + if (!ComparePdfObjects(previousExtensionCopy, currentExtensionCopy, usuallyModifiedObjects)) { report.AddReportItem(new ReportItem(DOC_MDP_CHECK, MessageFormatUtil.Format(DEVELOPER_EXTENSION_REMOVED, previousExtension .Key), ReportItem.ReportItemStatus.INVALID)); result = false; @@ -1064,7 +1104,7 @@ private bool CompareExtensions(PdfObject previousExtensions, PdfObject currentEx } private bool ComparePermissions(PdfObject previousPerms, PdfObject currentPerms, ValidationReport report) { - if (previousPerms == null || ComparePdfObjects(previousPerms, currentPerms)) { + if (previousPerms == null || ComparePdfObjects(previousPerms, currentPerms, usuallyModifiedObjects)) { return true; } if (currentPerms == null) { @@ -1154,7 +1194,7 @@ private bool CompareFormFieldWithFieldMDP(PdfDictionary previousField, PdfDictio currentFieldCopy.Remove(PdfName.P); currentFieldCopy.Remove(PdfName.Parent); currentFieldCopy.Remove(PdfName.V); - if (!ComparePdfObjects(previousFieldCopy, currentFieldCopy)) { + if (!ComparePdfObjects(previousFieldCopy, currentFieldCopy, usuallyModifiedObjects)) { report.AddReportItem(new ReportItem(FIELD_MDP_CHECK, MessageFormatUtil.Format(LOCKED_FIELD_MODIFIED, fieldName ), ReportItem.ReportItemStatus.INVALID)); return false; @@ -1169,7 +1209,7 @@ private bool CompareFormFieldWithFieldMDP(PdfDictionary previousField, PdfDictio } } else { - if (!ComparePdfObjects(prevValue, currValue)) { + if (!ComparePdfObjects(prevValue, currValue, usuallyModifiedObjects)) { report.AddReportItem(new ReportItem(FIELD_MDP_CHECK, MessageFormatUtil.Format(LOCKED_FIELD_MODIFIED, fieldName ), ReportItem.ReportItemStatus.INVALID)); return false; @@ -1250,8 +1290,8 @@ private bool CompareAcroForms(PdfDictionary prevAcroForm, PdfDictionary currAcro PdfDictionary currentAcroFormCopy = CopyAcroformDictionary(currAcroForm); PdfArray prevFields = prevAcroForm.GetAsArray(PdfName.Fields); PdfArray currFields = currAcroForm.GetAsArray(PdfName.Fields); - if (!ComparePdfObjects(previousAcroFormCopy, currentAcroFormCopy) || (prevFields.Size() > currFields.Size( - )) || !CompareFormFields(prevFields, currFields, report)) { + if (!ComparePdfObjects(previousAcroFormCopy, currentAcroFormCopy, usuallyModifiedObjects) || (prevFields.Size + () > currFields.Size()) || !CompareFormFields(prevFields, currFields, report)) { report.AddReportItem(new ReportItem(DOC_MDP_CHECK, NOT_ALLOWED_ACROFORM_CHANGES, ReportItem.ReportItemStatus .INVALID)); return false; @@ -1291,10 +1331,10 @@ private PdfDictionary RetrieveTheSameField(ICollection currFields foreach (PdfDictionary currentField in currFields) { PdfDictionary prevFormDict = CopyFieldDictionary(previousField); PdfDictionary currFormDict = CopyFieldDictionary(currentField); - if (ComparePdfObjects(prevFormDict, currFormDict) && CompareIndirectReferencesObjNums(prevFormDict.Get(PdfName - .Parent), currFormDict.Get(PdfName.Parent), new ValidationReport(), "Form field parent") && CompareIndirectReferencesObjNums - (prevFormDict.Get(PdfName.P), currFormDict.Get(PdfName.P), new ValidationReport(), "Page object with which field annotation is associated" - )) { + if (ComparePdfObjects(prevFormDict, currFormDict, usuallyModifiedObjects) && CompareIndirectReferencesObjNums + (prevFormDict.Get(PdfName.Parent), currFormDict.Get(PdfName.Parent), new ValidationReport(), "Form field parent" + ) && CompareIndirectReferencesObjNums(prevFormDict.Get(PdfName.P), currFormDict.Get(PdfName.P), new ValidationReport + (), "Page object with which field annotation is associated")) { return currentField; } } @@ -1337,7 +1377,7 @@ private bool CompareFields(PdfDictionary previousField, PdfDictionary currentFie } else { if (GetAccessPermissions() == AccessPermissions.NO_CHANGES_PERMITTED && !ComparePdfObjects(prevValue, currValue - )) { + , usuallyModifiedObjects)) { return false; } } @@ -1361,7 +1401,7 @@ private bool CompareSignatureDictionaries(PdfObject prevSigDict, PdfObject curSi PdfDictionary previousSigDictCopy = new PdfDictionary((PdfDictionary)prevSigDict); previousSigDictCopy.Remove(PdfName.Reference); // Apart from the reference, dictionaries are expected to be equal. - if (!ComparePdfObjects(previousSigDictCopy, currentSigDictCopy)) { + if (!ComparePdfObjects(previousSigDictCopy, currentSigDictCopy, usuallyModifiedObjects)) { return false; } PdfArray previousReference = ((PdfDictionary)prevSigDict).GetAsArray(PdfName.Reference); @@ -1371,7 +1411,8 @@ private bool CompareSignatureDictionaries(PdfObject prevSigDict, PdfObject curSi private bool CompareSignatureReferenceDictionaries(PdfArray previousReferences, PdfArray currentReferences , ValidationReport report) { - if (previousReferences == null || ComparePdfObjects(previousReferences, currentReferences)) { + if (previousReferences == null || ComparePdfObjects(previousReferences, currentReferences, usuallyModifiedObjects + )) { return true; } if (currentReferences == null || previousReferences.Size() != currentReferences.Size()) { @@ -1387,9 +1428,9 @@ private bool CompareSignatureReferenceDictionaries(PdfArray previousReferences, previousReferenceCopy.Remove(PdfName.Data); // Apart from the data, dictionaries are expected to be equal. Data is an indirect reference // to the object in the document upon which the object modification analysis should be performed. - if (!ComparePdfObjects(previousReferenceCopy, currentReferenceCopy) || !CompareIndirectReferencesObjNums(previousReferences - .GetAsDictionary(i).Get(PdfName.Data), currentReferences.GetAsDictionary(i).Get(PdfName.Data), report, - "Data entry in the signature reference dictionary")) { + if (!ComparePdfObjects(previousReferenceCopy, currentReferenceCopy, usuallyModifiedObjects) || !CompareIndirectReferencesObjNums + (previousReferences.GetAsDictionary(i).Get(PdfName.Data), currentReferences.GetAsDictionary(i).Get(PdfName + .Data), report, "Data entry in the signature reference dictionary")) { report.AddReportItem(new ReportItem(DOC_MDP_CHECK, REFERENCE_REMOVED, ReportItem.ReportItemStatus.INVALID) ); return false; @@ -1415,9 +1456,10 @@ private bool CompareWidgets(PdfArray prevFields, PdfArray currFields, Validation RemoveAppearanceRelatedProperties(prevAnnot); PdfDictionary currAnnot = new PdfDictionary(currAnnots[i]); RemoveAppearanceRelatedProperties(currAnnot); - if (!ComparePdfObjects(prevAnnot, currAnnot) || !CompareIndirectReferencesObjNums(prevAnnots[i].Get(PdfName - .P), currAnnots[i].Get(PdfName.P), report, "Page object with which annotation is associated") || !CompareIndirectReferencesObjNums - (prevAnnots[i].Get(PdfName.Parent), currAnnots[i].Get(PdfName.Parent), report, "Annotation parent")) { + if (!ComparePdfObjects(prevAnnot, currAnnot, usuallyModifiedObjects) || !CompareIndirectReferencesObjNums( + prevAnnots[i].Get(PdfName.P), currAnnots[i].Get(PdfName.P), report, "Page object with which annotation is associated" + ) || !CompareIndirectReferencesObjNums(prevAnnots[i].Get(PdfName.Parent), currAnnots[i].Get(PdfName.Parent + ), report, "Annotation parent")) { report.AddReportItem(new ReportItem(DOC_MDP_CHECK, ANNOTATIONS_MODIFIED, ReportItem.ReportItemStatus.INVALID )); return false; @@ -1442,8 +1484,8 @@ private bool ComparePages(PdfDictionary prevPages, PdfDictionary currPages, Vali PdfDictionary currentPagesCopy = new PdfDictionary(currPages); currentPagesCopy.Remove(PdfName.Kids); currentPagesCopy.Remove(PdfName.Parent); - if (!ComparePdfObjects(previousPagesCopy, currentPagesCopy) || !CompareIndirectReferencesObjNums(prevPages - .Get(PdfName.Parent), currPages.Get(PdfName.Parent), report, "Page tree node parent")) { + if (!ComparePdfObjects(previousPagesCopy, currentPagesCopy, usuallyModifiedObjects) || !CompareIndirectReferencesObjNums + (prevPages.Get(PdfName.Parent), currPages.Get(PdfName.Parent), report, "Page tree node parent")) { report.AddReportItem(new ReportItem(DOC_MDP_CHECK, PAGES_MODIFIED, ReportItem.ReportItemStatus.INVALID)); return false; } @@ -1472,8 +1514,8 @@ private bool ComparePages(PdfDictionary prevPages, PdfDictionary currPages, Vali currentPageCopy.Remove(PdfName.Annots); currentPageCopy.Remove(PdfName.Parent); currentPageCopy.Remove(PdfName.StructParents); - if (!ComparePdfObjects(previousPageCopy, currentPageCopy) || !CompareIndirectReferencesObjNums(previousKid - .Get(PdfName.Parent), currentKid.Get(PdfName.Parent), report, "Page parent")) { + if (!ComparePdfObjects(previousPageCopy, currentPageCopy, usuallyModifiedObjects) || !CompareIndirectReferencesObjNums + (previousKid.Get(PdfName.Parent), currentKid.Get(PdfName.Parent), report, "Page parent")) { report.AddReportItem(new ReportItem(DOC_MDP_CHECK, PAGE_MODIFIED, ReportItem.ReportItemStatus.INVALID)); return false; } @@ -1552,9 +1594,10 @@ private bool ComparePageAnnotations(PdfDictionary prevAnnot, PdfDictionary currA currAnnotCopy.Remove(PdfName.V); } } - return ComparePdfObjects(prevAnnotCopy, currAnnotCopy) && CompareIndirectReferencesObjNums(prevAnnot.Get(PdfName - .P), currAnnot.Get(PdfName.P), report, "Page object with which annotation is associated") && CompareIndirectReferencesObjNums - (prevAnnot.Get(PdfName.Parent), currAnnot.Get(PdfName.Parent), report, "Annotation parent"); + return ComparePdfObjects(prevAnnotCopy, currAnnotCopy, usuallyModifiedObjects) && CompareIndirectReferencesObjNums + (prevAnnot.Get(PdfName.P), currAnnot.Get(PdfName.P), report, "Page object with which annotation is associated" + ) && CompareIndirectReferencesObjNums(prevAnnot.Get(PdfName.Parent), currAnnot.Get(PdfName.Parent), report + , "Annotation parent"); } // Compare catalogs util methods section: @@ -1658,7 +1701,7 @@ private PdfDictionary CopyCatalogEntriesToCompare(PdfDictionary catalog) { catalogCopy.Remove(PdfName.AcroForm); catalogCopy.Remove(PdfName.Pages); catalogCopy.Remove(PdfName.StructTreeRoot); - catalogCopy.Remove(PdfName.Outlines); + catalogCopy.Remove(PdfName.Version); return catalogCopy; } @@ -1705,12 +1748,15 @@ private void RemoveAppearanceRelatedProperties(PdfDictionary annotDict) { // Compare PDF objects util section: // // - private static bool ComparePdfObjects(PdfObject pdfObject1, PdfObject pdfObject2) { - return ComparePdfObjects(pdfObject1, pdfObject2, new List>()); + private static bool ComparePdfObjects(PdfObject pdfObject1, PdfObject pdfObject2, Pair, ICollection> usuallyModifiedObjects) { + return ComparePdfObjects(pdfObject1, pdfObject2, new List>(), usuallyModifiedObjects + ); } private static bool ComparePdfObjects(PdfObject pdfObject1, PdfObject pdfObject2, IList> visitedObjects) { + >> visitedObjects, Pair, ICollection> usuallyModifiedObjects + ) { foreach (Pair pair in visitedObjects) { if (pair.GetKey() == pdfObject1) { return pair.GetValue() == pdfObject2; @@ -1726,6 +1772,13 @@ private static bool ComparePdfObjects(PdfObject pdfObject1, PdfObject pdfObject2 if (pdfObject1.GetType() != pdfObject2.GetType()) { return false; } + if (pdfObject1.GetIndirectReference() != null && usuallyModifiedObjects.GetKey().Any((reference) => IsSameReference + (reference, pdfObject1.GetIndirectReference())) && pdfObject2.GetIndirectReference() != null && usuallyModifiedObjects + .GetValue().Any((reference) => IsSameReference(reference, pdfObject2.GetIndirectReference()))) { + // These two objects are expected to not be completely equal, we check them independently. + // However, we still need to make sure those are same instances. + return IsSameReference(pdfObject1.GetIndirectReference(), pdfObject2.GetIndirectReference()); + } // We don't allow objects to change from being direct to indirect and vice versa. // Acrobat allows it, but such change can invalidate the document. if (pdfObject1.GetIndirectReference() == null ^ pdfObject2.GetIndirectReference() == null) { @@ -1743,19 +1796,22 @@ private static bool ComparePdfObjects(PdfObject pdfObject1, PdfObject pdfObject2 case PdfObject.INDIRECT_REFERENCE: { return ComparePdfObjects(((PdfIndirectReference)pdfObject1).GetRefersTo(), ((PdfIndirectReference)pdfObject2 - ).GetRefersTo(), visitedObjects); + ).GetRefersTo(), visitedObjects, usuallyModifiedObjects); } case PdfObject.ARRAY: { - return ComparePdfArrays((PdfArray)pdfObject1, (PdfArray)pdfObject2, visitedObjects); + return ComparePdfArrays((PdfArray)pdfObject1, (PdfArray)pdfObject2, visitedObjects, usuallyModifiedObjects + ); } case PdfObject.DICTIONARY: { - return ComparePdfDictionaries((PdfDictionary)pdfObject1, (PdfDictionary)pdfObject2, visitedObjects); + return ComparePdfDictionaries((PdfDictionary)pdfObject1, (PdfDictionary)pdfObject2, visitedObjects, usuallyModifiedObjects + ); } case PdfObject.STREAM: { - return ComparePdfStreams((PdfStream)pdfObject1, (PdfStream)pdfObject2, visitedObjects); + return ComparePdfStreams((PdfStream)pdfObject1, (PdfStream)pdfObject2, visitedObjects, usuallyModifiedObjects + ); } default: { @@ -1765,12 +1821,12 @@ private static bool ComparePdfObjects(PdfObject pdfObject1, PdfObject pdfObject2 } private static bool ComparePdfArrays(PdfArray array1, PdfArray array2, IList> visitedObjects - ) { + , Pair, ICollection> usuallyModifiedObjects) { if (array1.Size() != array2.Size()) { return false; } for (int i = 0; i < array1.Size(); i++) { - if (!ComparePdfObjects(array1.Get(i), array2.Get(i), visitedObjects)) { + if (!ComparePdfObjects(array1.Get(i), array2.Get(i), visitedObjects, usuallyModifiedObjects)) { return false; } } @@ -1778,7 +1834,8 @@ private static bool ComparePdfArrays(PdfArray array1, PdfArray array2, IList> visitedObjects) { + > visitedObjects, Pair, ICollection> usuallyModifiedObjects) { ICollection> entrySet1 = dictionary1.EntrySet(); ICollection> entrySet2 = dictionary2.EntrySet(); if (entrySet1.Count != entrySet2.Count) { @@ -1786,7 +1843,7 @@ private static bool ComparePdfDictionaries(PdfDictionary dictionary1, PdfDiction } foreach (KeyValuePair entry1 in entrySet1) { if (!entrySet2.Any((entry2) => entry2.Key.Equals(entry1.Key) && ComparePdfObjects(entry2.Value, entry1.Value - , visitedObjects))) { + , visitedObjects, usuallyModifiedObjects))) { return false; } } @@ -1794,9 +1851,10 @@ private static bool ComparePdfDictionaries(PdfDictionary dictionary1, PdfDiction } private static bool ComparePdfStreams(PdfStream stream1, PdfStream stream2, IList> visitedObjects) { + >> visitedObjects, Pair, ICollection> usuallyModifiedObjects + ) { return JavaUtil.ArraysEquals(stream1.GetBytes(), stream2.GetBytes()) && ComparePdfDictionaries(stream1, stream2 - , visitedObjects); + , visitedObjects, usuallyModifiedObjects); } private static bool IsSameReference(PdfIndirectReference indirectReference1, PdfIndirectReference indirectReference2 @@ -1820,6 +1878,64 @@ private static bool IsMaxGenerationObject(PdfIndirectReference indirectReference // Allowed references section: // // + private ICollection CreateUsuallyModifiedObjectsSet(PdfDocument document) { + ICollection usuallyModifiedObjectsSet = new HashSet(); + usuallyModifiedObjectsSet.Add(document.GetCatalog().GetPdfObject().GetIndirectReference()); + PdfDictionary catalog = document.GetCatalog().GetPdfObject(); + if (catalog.Get(PdfName.Pages) != null) { + usuallyModifiedObjectsSet.Add(catalog.Get(PdfName.Pages).GetIndirectReference()); + if (catalog.GetAsDictionary(PdfName.Pages) != null) { + AddPageEntriesToSet(catalog.GetAsDictionary(PdfName.Pages), usuallyModifiedObjectsSet); + } + } + if (catalog.Get(PdfName.StructTreeRoot) != null) { + usuallyModifiedObjectsSet.Add(catalog.Get(PdfName.StructTreeRoot).GetIndirectReference()); + if (catalog.GetAsDictionary(PdfName.StructTreeRoot) != null && catalog.GetAsDictionary(PdfName.StructTreeRoot + ).Get(PdfName.K) != null) { + AddStructTreeElementsToSet(catalog.GetAsDictionary(PdfName.StructTreeRoot).Get(PdfName.K), usuallyModifiedObjectsSet + ); + } + } + return usuallyModifiedObjectsSet; + } + + private void AddStructTreeElementsToSet(PdfObject structTreeRootKids, ICollection set + ) { + if (structTreeRootKids is PdfArray) { + set.Add(structTreeRootKids.GetIndirectReference()); + AddStructTreeElementsToSet((PdfArray)structTreeRootKids, set); + } + else { + AddStructTreeElementsToSet(new PdfArray(structTreeRootKids), set); + } + } + + private void AddStructTreeElementsToSet(PdfArray structTreeRootKids, ICollection set + ) { + foreach (PdfObject kid in structTreeRootKids) { + if (kid != null) { + set.Add(kid.GetIndirectReference()); + if (IsStructTreeElement(kid) && ((PdfDictionary)kid).Get(PdfName.K) != null) { + AddStructTreeElementsToSet(((PdfDictionary)kid).Get(PdfName.K), set); + } + } + } + } + + private void AddPageEntriesToSet(PdfDictionary page, ICollection set) { + PdfArray kids = page.GetAsArray(PdfName.Kids); + if (kids != null) { + set.Add(kids.GetIndirectReference()); + for (int i = 0; i < kids.Size(); ++i) { + set.Add(kids.Get(i).GetIndirectReference()); + PdfDictionary pageNode = kids.GetAsDictionary(i); + if (pageNode != null && PdfName.Pages.Equals(pageNode.GetAsName(PdfName.Type))) { + AddPageEntriesToSet(pageNode, set); + } + } + } + } + private ICollection CreateAllowedReferences(PdfDocument document) { // Each indirect reference in the set is an allowed reference to be present in the new xref table // or the same entry in the previous document. diff --git a/itext/itext.sign/itext/signatures/validation/v1/OCSPValidator.cs b/itext/itext.sign/itext/signatures/validation/OCSPValidator.cs similarity index 52% rename from itext/itext.sign/itext/signatures/validation/v1/OCSPValidator.cs rename to itext/itext.sign/itext/signatures/validation/OCSPValidator.cs index 42f3dad3ba..6a32859904 100644 --- a/itext/itext.sign/itext/signatures/validation/v1/OCSPValidator.cs +++ b/itext/itext.sign/itext/signatures/validation/OCSPValidator.cs @@ -21,6 +21,7 @@ You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ using System; +using System.Collections.Generic; using iText.Bouncycastleconnector; using iText.Commons.Bouncycastle; using iText.Commons.Bouncycastle.Asn1; @@ -30,10 +31,10 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Utils; using iText.Signatures; using iText.Signatures.Logs; -using iText.Signatures.Validation.V1.Context; -using iText.Signatures.Validation.V1.Report; +using iText.Signatures.Validation.Context; +using iText.Signatures.Validation.Report; -namespace iText.Signatures.Validation.V1 { +namespace iText.Signatures.Validation { /// Class that allows you to validate a single OCSP response. public class OCSPValidator { //\cond DO_NOT_DOCUMENT @@ -57,6 +58,10 @@ public class OCSPValidator { internal const String ISSUERS_DO_NOT_MATCH = "OCSP: Issuers don't match."; //\endcond +//\cond DO_NOT_DOCUMENT + internal const String ISSUER_MISSING = "Issuer certificate wasn't found."; +//\endcond + //\cond DO_NOT_DOCUMENT internal const String FRESHNESS_CHECK = "OCSP response is not fresh enough: " + "this update: {0}, validation date: {1}, freshness: {2}."; //\endcond @@ -74,11 +79,23 @@ public class OCSPValidator { internal const String OCSP_RESPONDER_NOT_VERIFIED = "OCSP response could not be verified: \" +\n" + " \" Unexpected exception occurred while validating responder certificate."; //\endcond +//\cond DO_NOT_DOCUMENT + internal const String OCSP_RESPONDER_DID_NOT_SIGN = "OCSP response could not be verified against this responder."; +//\endcond + //\cond DO_NOT_DOCUMENT internal const String OCSP_RESPONDER_TRUST_NOT_RETRIEVED = "OCSP response could not be verified: \" +\n" + " \"responder trust state could not be retrieved."; //\endcond +//\cond DO_NOT_DOCUMENT + internal const String OCSP_RESPONDER_TRUSTED = "Responder certificate is a trusted certificate."; +//\endcond + +//\cond DO_NOT_DOCUMENT + internal const String OCSP_RESPONDER_IS_CA = "Responder certificate is the CA certificate."; +//\endcond + //\cond DO_NOT_DOCUMENT internal const String OCSP_IS_NO_LONGER_VALID = "OCSP is no longer valid: {0} after {1}"; //\endcond @@ -88,11 +105,13 @@ public class OCSPValidator { //\endcond //\cond DO_NOT_DOCUMENT - internal const String UNABLE_TO_CHECK_IF_ISSUERS_MATCH = "OCSP response could not be verified: Unexpected exception occurred checking if issuers match."; + internal const String UNABLE_TO_CHECK_IF_ISSUERS_MATCH = "OCSP response could not be verified: Unexpected exception" + + " occurred checking if issuers match."; //\endcond //\cond DO_NOT_DOCUMENT - internal const String UNABLE_TO_RETRIEVE_ISSUER = "OCSP response could not be verified: Unexpected exception occurred while retrieving issuer"; + internal const String UNABLE_TO_RETRIEVE_ISSUER = "OCSP response could not be verified: Unexpected exception " + + "occurred while retrieving issuer"; //\endcond //\cond DO_NOT_DOCUMENT @@ -123,20 +142,6 @@ protected internal OCSPValidator(ValidatorChainBuilder builder) { this.builder = builder; } - /// Validates a certificate against single OCSP Response. - /// to store all the chain verification results - /// the context in which to perform the validation - /// the certificate to check for - /// single response to check - /// basic OCSP response which contains single response to check - /// validation date to check for - [System.ObsoleteAttribute(@"starting from 8.0.5. TODO DEVSIX-8398 To be removed.")] - public virtual void Validate(ValidationReport report, ValidationContext context, IX509Certificate certificate - , ISingleResponse singleResp, IBasicOcspResponse ocspResp, DateTime validationDate) { - Validate(report, context, certificate, singleResp, ocspResp, validationDate, DateTimeUtil.GetCurrentUtcTime - ()); - } - /// Validates a certificate against single OCSP Response. /// to store all the chain verification results /// the context in which to perform the validation @@ -161,78 +166,99 @@ public virtual void Validate(ValidationReport report, ValidationContext context, .INDETERMINATE)); return; } - IX509Certificate issuerCert; + IList issuerCerts; try { - issuerCert = certificateRetriever.RetrieveIssuerCertificate(certificate); + issuerCerts = certificateRetriever.RetrieveIssuerCertificate(certificate); } catch (Exception e) { report.AddReportItem(new CertificateReportItem(certificate, OCSP_CHECK, UNABLE_TO_RETRIEVE_ISSUER, e, ReportItem.ReportItemStatus .INDETERMINATE)); return; } - // Check if the issuer of the certID and signCert matches, i.e. check that issuerNameHash and issuerKeyHash - // fields of the certID is the hash of the issuer's name and public key: - try { - if (!CertificateUtil.CheckIfIssuersMatch(singleResp.GetCertID(), (IX509Certificate)issuerCert)) { - report.AddReportItem(new CertificateReportItem(certificate, OCSP_CHECK, ISSUERS_DO_NOT_MATCH, ReportItem.ReportItemStatus - .INDETERMINATE)); - return; - } - } - catch (Exception e) { - report.AddReportItem(new CertificateReportItem(certificate, OCSP_CHECK, UNABLE_TO_CHECK_IF_ISSUERS_MATCH, - e, ReportItem.ReportItemStatus.INDETERMINATE)); + if (issuerCerts.IsEmpty()) { + report.AddReportItem(new CertificateReportItem(certificate, OCSP_CHECK, MessageFormatUtil.Format(ISSUER_MISSING + , certificate.GetSubjectDN()), ReportItem.ReportItemStatus.INDETERMINATE)); return; } - // So, since the issuer name and serial number identify a unique certificate, we found the single response - // for the provided certificate. - TimeSpan freshness = properties.GetFreshness(localContext); - // Check that thisUpdate + freshness < validation. - if (DateTimeUtil.AddMillisToDate(singleResp.GetThisUpdate(), (long)freshness.TotalMilliseconds).Before(validationDate - )) { - report.AddReportItem(new CertificateReportItem(certificate, OCSP_CHECK, MessageFormatUtil.Format(FRESHNESS_CHECK - , singleResp.GetThisUpdate(), validationDate, freshness), ReportItem.ReportItemStatus.INDETERMINATE)); - return; - } - // If nextUpdate is not set, the responder is indicating that newer revocation information - // is available all the time. - if (singleResp.GetNextUpdate() != TimestampConstants.UNDEFINED_TIMESTAMP_DATE && validationDate.After(singleResp - .GetNextUpdate())) { - report.AddReportItem(new CertificateReportItem(certificate, OCSP_CHECK, MessageFormatUtil.Format(OCSP_IS_NO_LONGER_VALID - , validationDate, singleResp.GetNextUpdate()), ReportItem.ReportItemStatus.INDETERMINATE)); - return; - } - // Check the status of the certificate: - ICertStatus status = singleResp.GetCertStatus(); - IRevokedCertStatus revokedStatus = BOUNCY_CASTLE_FACTORY.CreateRevokedStatus(status); - bool isStatusGood = BOUNCY_CASTLE_FACTORY.CreateCertificateStatus().GetGood().Equals(status); - // Check OCSP Archive Cutoff extension in case OCSP response was generated after the certificate is expired. - if (isStatusGood && certificate.GetNotAfter().Before(ocspResp.GetProducedAt())) { - DateTime startExpirationDate = GetArchiveCutoffExtension(ocspResp); - if (TimestampConstants.UNDEFINED_TIMESTAMP_DATE == startExpirationDate || certificate.GetNotAfter().Before - (startExpirationDate)) { - report.AddReportItem(new CertificateReportItem(certificate, OCSP_CHECK, MessageFormatUtil.Format(CERT_IS_EXPIRED - , certificate.GetNotAfter()), ReportItem.ReportItemStatus.INDETERMINATE)); - return; + ValidationReport[] candidateReports = new ValidationReport[issuerCerts.Count]; + for (int i = 0; i < issuerCerts.Count; i++) { + candidateReports[i] = new ValidationReport(); + // Check if the issuer of the certID and signCert matches, i.e. check that issuerNameHash and issuerKeyHash + // fields of the certID is the hash of the issuer's name and public key: + try { + if (!CertificateUtil.CheckIfIssuersMatch(singleResp.GetCertID(), issuerCerts[i])) { + candidateReports[i].AddReportItem(new CertificateReportItem(certificate, OCSP_CHECK, ISSUERS_DO_NOT_MATCH, + ReportItem.ReportItemStatus.INDETERMINATE)); + continue; + } } - } - if (isStatusGood || (revokedStatus != null && validationDate.Before(revokedStatus.GetRevocationTime()))) { - // Check if the OCSP response is genuine. - VerifyOcspResponder(report, localContext, ocspResp, (IX509Certificate)issuerCert, responseGenerationDate); - if (!isStatusGood) { - report.AddReportItem(new CertificateReportItem(certificate, OCSP_CHECK, MessageFormatUtil.Format(SignLogMessageConstant - .VALID_CERTIFICATE_IS_REVOKED, revokedStatus.GetRevocationTime()), ReportItem.ReportItemStatus.INFO)); + catch (Exception e) { + candidateReports[i].AddReportItem(new CertificateReportItem(certificate, OCSP_CHECK, UNABLE_TO_CHECK_IF_ISSUERS_MATCH + , e, ReportItem.ReportItemStatus.INDETERMINATE)); + continue; } - } - else { - if (revokedStatus != null) { - report.AddReportItem(new CertificateReportItem(certificate, OCSP_CHECK, CERT_IS_REVOKED, ReportItem.ReportItemStatus - .INVALID)); + // So, since the issuer name and serial number identify a unique certificate, we found the single response + // for the provided certificate. + TimeSpan freshness = properties.GetFreshness(localContext); + // Check that thisUpdate + freshness < validation. + if (DateTimeUtil.AddMillisToDate(singleResp.GetThisUpdate(), (long)freshness.TotalMilliseconds).Before(validationDate + )) { + candidateReports[i].AddReportItem(new CertificateReportItem(certificate, OCSP_CHECK, MessageFormatUtil.Format + (FRESHNESS_CHECK, singleResp.GetThisUpdate(), validationDate, freshness), ReportItem.ReportItemStatus. + INDETERMINATE)); + continue; + } + // If nextUpdate is not set, the responder is indicating that newer revocation information + // is available all the time. + if (singleResp.GetNextUpdate() != TimestampConstants.UNDEFINED_TIMESTAMP_DATE && validationDate.After(singleResp + .GetNextUpdate())) { + candidateReports[i].AddReportItem(new CertificateReportItem(certificate, OCSP_CHECK, MessageFormatUtil.Format + (OCSP_IS_NO_LONGER_VALID, validationDate, singleResp.GetNextUpdate()), ReportItem.ReportItemStatus.INDETERMINATE + )); + continue; + } + // Check the status of the certificate: + ICertStatus status = singleResp.GetCertStatus(); + IRevokedCertStatus revokedStatus = BOUNCY_CASTLE_FACTORY.CreateRevokedStatus(status); + bool isStatusGood = BOUNCY_CASTLE_FACTORY.CreateCertificateStatus().GetGood().Equals(status); + // Check OCSP Archive Cutoff extension in case OCSP response was generated after the certificate is expired. + if (isStatusGood && certificate.GetNotAfter().Before(ocspResp.GetProducedAt())) { + DateTime startExpirationDate = GetArchiveCutoffExtension(ocspResp); + if (TimestampConstants.UNDEFINED_TIMESTAMP_DATE == startExpirationDate || certificate.GetNotAfter().Before + (startExpirationDate)) { + candidateReports[i].AddReportItem(new CertificateReportItem(certificate, OCSP_CHECK, MessageFormatUtil.Format + (CERT_IS_EXPIRED, certificate.GetNotAfter()), ReportItem.ReportItemStatus.INDETERMINATE)); + continue; + } + } + if (isStatusGood || (revokedStatus != null && validationDate.Before(revokedStatus.GetRevocationTime()))) { + // Check if the OCSP response is genuine. + VerifyOcspResponder(candidateReports[i], localContext, ocspResp, issuerCerts[i], responseGenerationDate); + if (!isStatusGood) { + candidateReports[i].AddReportItem(new CertificateReportItem(certificate, OCSP_CHECK, MessageFormatUtil.Format + (SignLogMessageConstant.VALID_CERTIFICATE_IS_REVOKED, revokedStatus.GetRevocationTime()), ReportItem.ReportItemStatus + .INFO)); + } } else { - report.AddReportItem(new CertificateReportItem(certificate, OCSP_CHECK, CERT_STATUS_IS_UNKNOWN, ReportItem.ReportItemStatus - .INDETERMINATE)); + if (revokedStatus != null) { + candidateReports[i].AddReportItem(new CertificateReportItem(certificate, OCSP_CHECK, CERT_IS_REVOKED, ReportItem.ReportItemStatus + .INVALID)); + } + else { + candidateReports[i].AddReportItem(new CertificateReportItem(certificate, OCSP_CHECK, CERT_STATUS_IS_UNKNOWN + , ReportItem.ReportItemStatus.INDETERMINATE)); + } } + if (candidateReports[i].GetValidationResult() == ValidationReport.ValidationResult.VALID) { + // We found valid issuer, no need to try other ones. + report.Merge(candidateReports[i]); + return; + } + } + // Valid issuer wasn't found, add all the reports + foreach (ValidationReport candidateReport in candidateReports) { + report.Merge(candidateReport); } } @@ -253,90 +279,87 @@ public virtual void Validate(ValidationReport report, ValidationContext context, private void VerifyOcspResponder(ValidationReport report, ValidationContext context, IBasicOcspResponse ocspResp , IX509Certificate issuerCert, DateTime responseGenerationDate) { ValidationContext localContext = context.SetCertificateSource(CertificateSource.OCSP_ISSUER); - ValidationReport responderReport = new ValidationReport(); // OCSP response might be signed by the issuer certificate or // the Authorized OCSP responder certificate containing the id-kp-OCSPSigning extended key usage extension. - IX509Certificate responderCert = null; // First check if the issuer certificate signed the response since it is expected to be the most common case: + // the CA will already be validated by the chain validator if (CertificateUtil.IsSignatureValid(ocspResp, issuerCert)) { - responderCert = issuerCert; + report.AddReportItem(new CertificateReportItem(issuerCert, OCSP_CHECK, OCSP_RESPONDER_IS_CA, ReportItem.ReportItemStatus + .INFO)); + return; } // If the issuer certificate didn't sign the ocsp response, look for authorized ocsp responses // from the properties or from the certificate chain received with response. - if (responderCert == null) { - try { - responderCert = (IX509Certificate)certificateRetriever.RetrieveOCSPResponderCertificate(ocspResp); - } - catch (Exception e) { - report.AddReportItem(new CertificateReportItem(issuerCert, OCSP_CHECK, OCSP_RESPONDER_NOT_RETRIEVED, e, ReportItem.ReportItemStatus - .INDETERMINATE)); - return; - } - if (responderCert == null) { - report.AddReportItem(new CertificateReportItem(issuerCert, OCSP_CHECK, OCSP_COULD_NOT_BE_VERIFIED, ReportItem.ReportItemStatus - .INDETERMINATE)); - return; + ICollection candidates = SafeCalling.OnRuntimeExceptionLog(() => certificateRetriever.RetrieveOCSPResponderByNameCertificate + (ocspResp), JavaCollectionsUtil.EmptySet(), report, (e) => new CertificateReportItem + (issuerCert, OCSP_CHECK, OCSP_RESPONDER_NOT_RETRIEVED, e, ReportItem.ReportItemStatus.INDETERMINATE)); + if (candidates.IsEmpty()) { + report.AddReportItem(new CertificateReportItem(issuerCert, OCSP_CHECK, OCSP_COULD_NOT_BE_VERIFIED, ReportItem.ReportItemStatus + .INDETERMINATE)); + return; + } + ValidationReport[] candidateReports = new ValidationReport[candidates.Count]; + int reportIndex = 0; + foreach (IX509Certificate cert in candidates) { + IX509Certificate responderCert = (IX509Certificate)cert; + ValidationReport candidateReport = new ValidationReport(); + candidateReports[reportIndex++] = candidateReport; + // if the response was not signed by this candidate we can stop further processing + if (!CertificateUtil.IsSignatureValid(ocspResp, responderCert)) { + candidateReport.AddReportItem(new CertificateReportItem(responderCert, OCSP_CHECK, OCSP_RESPONDER_DID_NOT_SIGN + , ReportItem.ReportItemStatus.INDETERMINATE)); + continue; } - bool needsToBeSignedByIssuer = false; + // if the responder is trusted validation is successful try { - needsToBeSignedByIssuer = (!certificateRetriever.IsCertificateTrusted(responderCert) && !certificateRetriever - .GetTrustedCertificatesStore().IsCertificateTrustedForOcsp(responderCert)); + if (certificateRetriever.GetTrustedCertificatesStore().IsCertificateTrustedForOcsp(responderCert) || certificateRetriever + .GetTrustedCertificatesStore().IsCertificateGenerallyTrusted(responderCert)) { + candidateReport.AddReportItem(new CertificateReportItem(responderCert, OCSP_CHECK, OCSP_RESPONDER_TRUSTED, + ReportItem.ReportItemStatus.INFO)); + report.Merge(candidateReport); + return; + } } catch (Exception e) { report.AddReportItem(new CertificateReportItem(responderCert, OCSP_CHECK, OCSP_RESPONDER_TRUST_NOT_RETRIEVED , e, ReportItem.ReportItemStatus.INDETERMINATE)); - return; + continue; } - if (needsToBeSignedByIssuer) { - // RFC 6960 4.2.2.2. Authorized Responders: - // "Systems relying on OCSP responses MUST recognize a delegation certificate as being issued - // by the CA that issued the certificate in question only if the delegation certificate and the - // certificate being checked for revocation were signed by the same key." - // and "This certificate MUST be issued directly by the CA that is identified in the request". - try { - responderCert.Verify(issuerCert.GetPublicKey()); - } - catch (Exception e) { - report.AddReportItem(new CertificateReportItem(responderCert, OCSP_CHECK, INVALID_OCSP, e, ReportItem.ReportItemStatus - .INVALID)); - return; - } - // Validating of the ocsp signer's certificate (responderCert) described in the - // RFC6960 4.2.2.2.1. Revocation Checking of an Authorized Responder. - try { - builder.GetCertificateChainValidator().Validate(responderReport, localContext, responderCert, responseGenerationDate - ); - } - catch (Exception e) { - report.AddReportItem(new CertificateReportItem(responderCert, OCSP_CHECK, OCSP_RESPONDER_NOT_VERIFIED, e, - ReportItem.ReportItemStatus.INDETERMINATE)); - return; - } + // RFC 6960 4.2.2.2. Authorized Responders: + // "Systems relying on OCSP responses MUST recognize a delegation certificate as being issued + // by the CA that issued the certificate in question only if the delegation certificate and the + // certificate being checked for revocation were signed by the same key." + // and "This certificate MUST be issued directly by the CA that is identified in the request". + try { + responderCert.Verify(issuerCert.GetPublicKey()); } - else { - try { - builder.GetCertificateChainValidator().Validate(responderReport, localContext.SetCertificateSource(CertificateSource - .TRUSTED), responderCert, responseGenerationDate); - } - catch (Exception e) { - report.AddReportItem(new CertificateReportItem(responderCert, OCSP_CHECK, OCSP_RESPONDER_NOT_VERIFIED, e, - ReportItem.ReportItemStatus.INDETERMINATE)); - return; - } + catch (Exception e) { + candidateReport.AddReportItem(new CertificateReportItem(responderCert, OCSP_CHECK, INVALID_OCSP, e, ReportItem.ReportItemStatus + .INVALID)); + continue; } - } - else { + // Validating of the ocsp signer's certificate (responderCert) described in the + // RFC6960 4.2.2.2.1. Revocation Checking of an Authorized Responder. + ValidationReport responderReport = new ValidationReport(); try { - builder.GetCertificateChainValidator().Validate(responderReport, localContext.SetCertificateSource(CertificateSource - .CERT_ISSUER), responderCert, responseGenerationDate); + builder.GetCertificateChainValidator().Validate(responderReport, localContext, responderCert, responseGenerationDate + ); } catch (Exception e) { - report.AddReportItem(new CertificateReportItem(responderCert, OCSP_CHECK, OCSP_RESPONDER_NOT_VERIFIED, e, - ReportItem.ReportItemStatus.INDETERMINATE)); + candidateReport.AddReportItem(new CertificateReportItem(responderCert, OCSP_CHECK, OCSP_RESPONDER_NOT_VERIFIED + , e, ReportItem.ReportItemStatus.INDETERMINATE)); + continue; + } + AddResponderValidationReport(candidateReport, responderReport); + if (candidateReport.GetValidationResult() == ValidationReport.ValidationResult.VALID) { + AddResponderValidationReport(report, candidateReport); return; } } - AddResponderValidationReport(report, responderReport); + //if we get here, none of the candidates were successful + foreach (ValidationReport subReport in candidateReports) { + report.Merge(subReport); + } } private static void AddResponderValidationReport(ValidationReport report, ValidationReport responderReport diff --git a/itext/itext.sign/itext/signatures/validation/v1/RevocationDataValidator.cs b/itext/itext.sign/itext/signatures/validation/RevocationDataValidator.cs similarity index 78% rename from itext/itext.sign/itext/signatures/validation/v1/RevocationDataValidator.cs rename to itext/itext.sign/itext/signatures/validation/RevocationDataValidator.cs index 12dcdaa265..11aed3377f 100644 --- a/itext/itext.sign/itext/signatures/validation/v1/RevocationDataValidator.cs +++ b/itext/itext.sign/itext/signatures/validation/RevocationDataValidator.cs @@ -30,11 +30,12 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Cert.Ocsp; using iText.Commons.Utils; using iText.Commons.Utils.Collections; +using iText.Kernel.Crypto; using iText.Signatures; -using iText.Signatures.Validation.V1.Context; -using iText.Signatures.Validation.V1.Report; +using iText.Signatures.Validation.Context; +using iText.Signatures.Validation.Report; -namespace iText.Signatures.Validation.V1 { +namespace iText.Signatures.Validation { /// Class that allows you to fetch and validate revocation data for the certificate. public class RevocationDataValidator { //\cond DO_NOT_DOCUMENT @@ -58,6 +59,16 @@ public class RevocationDataValidator { internal const String VALIDITY_ASSURED = "Certificate is trusted due to validity assured - short term extension."; //\endcond +//\cond DO_NOT_DOCUMENT + internal const String NO_REV_AVAILABLE = "noRevAvail extension from RFC 9608 is present on {0} certificate. " + + "Revocation data checks are not required."; +//\endcond + +//\cond DO_NOT_DOCUMENT + internal const String NO_REV_AVAILABLE_CA = "noRevAvail extension from RFC 9608 is present on {0} certificate, " + + "however this certificate is a CA, which is not allowed."; +//\endcond + //\cond DO_NOT_DOCUMENT internal const String CANNOT_PARSE_OCSP = "OCSP response from \"{0}\" OCSP response cannot be parsed."; //\endcond @@ -86,6 +97,10 @@ public class RevocationDataValidator { internal const String CRL_VALIDATOR_FAILURE = "Unexpected exception occurred in CRL validator."; //\endcond +//\cond DO_NOT_DOCUMENT + internal const String UNABLE_TO_RETRIEVE_REV_DATA_ONLINE = "Online revocation data wasn't generated: Unexpected exception occurred."; +//\endcond + private static readonly IBouncyCastleFactory BOUNCY_CASTLE_FACTORY = BouncyCastleFactoryCreator.GetFactory (); @@ -133,7 +148,7 @@ protected internal RevocationDataValidator(ValidatorChainBuilder builder) { /// same instance of /// . /// - public virtual iText.Signatures.Validation.V1.RevocationDataValidator AddCrlClient(ICrlClient crlClient) { + public virtual iText.Signatures.Validation.RevocationDataValidator AddCrlClient(ICrlClient crlClient) { this.crlClients.Add(crlClient); return this; } @@ -152,8 +167,7 @@ public virtual iText.Signatures.Validation.V1.RevocationDataValidator AddCrlClie /// same instance of /// . /// - public virtual iText.Signatures.Validation.V1.RevocationDataValidator AddOcspClient(IOcspClient ocspClient - ) { + public virtual iText.Signatures.Validation.RevocationDataValidator AddOcspClient(IOcspClient ocspClient) { this.ocspClients.Add(ocspClient); return this; } @@ -163,7 +177,7 @@ public virtual iText.Signatures.Validation.V1.RevocationDataValidator AddOcspCli /// to store all the verification results /// /// - /// + /// /// the context /// /// the certificate to check revocation data for @@ -184,6 +198,17 @@ public virtual void Validate(ValidationReport report, ValidationContext context, .INFO)); return; } + if (CertificateUtil.GetExtensionValueByOid(certificate, OID.X509Extensions.NO_REV_AVAILABLE) != null) { + if (certificate.GetBasicConstraints() < 0) { + report.AddReportItem(new CertificateReportItem(certificate, REVOCATION_DATA_CHECK, MessageFormatUtil.Format + (NO_REV_AVAILABLE, certificate.GetSubjectDN()), ReportItem.ReportItemStatus.INFO)); + } + else { + report.AddReportItem(new CertificateReportItem(certificate, REVOCATION_DATA_CHECK, MessageFormatUtil.Format + (NO_REV_AVAILABLE_CA, certificate.GetSubjectDN()), ReportItem.ReportItemStatus.INDETERMINATE)); + } + return; + } if (CertificateSource.OCSP_ISSUER == localContext.GetCertificateSource()) { // Check if Authorised OCSP Responder certificate has id-pkix-ocsp-nocheck extension, in which case we // do not perform revocation check for it. @@ -212,7 +237,13 @@ public virtual void Validate(ValidationReport report, ValidationContext context, >(); IList onlineOcspResponses = new List(); - TryToFetchRevInfoOnline(report, context, certificate, onlineCrlResponses, onlineOcspResponses); + try { + TryToFetchRevInfoOnline(report, context, certificate, onlineCrlResponses, onlineOcspResponses); + } + catch (Exception e) { + report.AddReportItem(new CertificateReportItem(certificate, REVOCATION_DATA_CHECK, UNABLE_TO_RETRIEVE_REV_DATA_ONLINE + , e, ReportItem.ReportItemStatus.INFO)); + } if (!onlineCrlResponses.IsEmpty() || !onlineOcspResponses.IsEmpty()) { // Merge the report excluding NO_REVOCATION_DATA message. foreach (ReportItem reportItem in revDataValidationReport.GetLogs()) { @@ -309,9 +340,9 @@ private void ValidateRevocationData(ValidationReport report, ValidationContext c report, ValidationContext context, IX509Certificate certificate) { IList ocspResponses = new List(); - IX509Certificate issuerCert; + IList issuerCerts; try { - issuerCert = (IX509Certificate)certificateRetriever.RetrieveIssuerCertificate(certificate); + issuerCerts = certificateRetriever.RetrieveIssuerCertificate(certificate); } catch (Exception e) { report.AddReportItem(new CertificateReportItem(certificate, REVOCATION_DATA_CHECK, ISSUER_RETRIEVAL_FAILED @@ -328,24 +359,26 @@ private void ValidateRevocationData(ValidationReport report, ValidationContext c } } else { - byte[] basicOcspRespBytes = null; - basicOcspRespBytes = SafeCalling.OnRuntimeExceptionLog(() => ocspClient.GetEncoded(certificate, issuerCert - , null), null, report, (e) => new CertificateReportItem(certificate, REVOCATION_DATA_CHECK, MessageFormatUtil - .Format(OCSP_CLIENT_FAILURE, ocspClient), e, ReportItem.ReportItemStatus.INFO)); - if (basicOcspRespBytes != null) { - try { - IBasicOcspResponse basicOCSPResp = BOUNCY_CASTLE_FACTORY.CreateBasicOCSPResponse(BOUNCY_CASTLE_FACTORY.CreateASN1Primitive - (basicOcspRespBytes)); - FillOcspResponses(ocspResponses, basicOCSPResp, DateTimeUtil.GetCurrentUtcTime(), TimeBasedContext.PRESENT - ); - } - catch (System.IO.IOException e) { - report.AddReportItem(new ReportItem(REVOCATION_DATA_CHECK, MessageFormatUtil.Format(CANNOT_PARSE_OCSP, ocspClient - ), e, ReportItem.ReportItemStatus.INFO)); - } - catch (Exception e) { - report.AddReportItem(new ReportItem(REVOCATION_DATA_CHECK, MessageFormatUtil.Format(CANNOT_PARSE_OCSP, ocspClient - ), e, ReportItem.ReportItemStatus.INFO)); + foreach (IX509Certificate issuerCert in issuerCerts) { + byte[] basicOcspRespBytes = null; + basicOcspRespBytes = SafeCalling.OnRuntimeExceptionLog(() => ocspClient.GetEncoded(certificate, issuerCert + , null), null, report, (e) => new CertificateReportItem(certificate, REVOCATION_DATA_CHECK, MessageFormatUtil + .Format(OCSP_CLIENT_FAILURE, ocspClient), e, ReportItem.ReportItemStatus.INFO)); + if (basicOcspRespBytes != null) { + try { + IBasicOcspResponse basicOCSPResp = BOUNCY_CASTLE_FACTORY.CreateBasicOCSPResponse(BOUNCY_CASTLE_FACTORY.CreateASN1Primitive + (basicOcspRespBytes)); + FillOcspResponses(ocspResponses, basicOCSPResp, DateTimeUtil.GetCurrentUtcTime(), TimeBasedContext.PRESENT + ); + } + catch (System.IO.IOException e) { + report.AddReportItem(new ReportItem(REVOCATION_DATA_CHECK, MessageFormatUtil.Format(CANNOT_PARSE_OCSP, ocspClient + ), e, ReportItem.ReportItemStatus.INFO)); + } + catch (Exception e) { + report.AddReportItem(new ReportItem(REVOCATION_DATA_CHECK, MessageFormatUtil.Format(CANNOT_PARSE_OCSP, ocspClient + ), e, ReportItem.ReportItemStatus.INFO)); + } } } } @@ -353,14 +386,16 @@ private void ValidateRevocationData(ValidationReport report, ValidationContext c SignatureValidationProperties.OnlineFetching onlineFetching = properties.GetRevocationOnlineFetching(context .SetValidatorContext(ValidatorContext.OCSP_VALIDATOR)); if (SignatureValidationProperties.OnlineFetching.ALWAYS_FETCH == onlineFetching) { - SafeCalling.OnRuntimeExceptionLog(() => { - IBasicOcspResponse basicOCSPResp = new OcspClientBouncyCastle().GetBasicOCSPResp(certificate, issuerCert, - null); - FillOcspResponses(ocspResponses, basicOCSPResp, DateTimeUtil.GetCurrentUtcTime(), TimeBasedContext.PRESENT - ); + foreach (IX509Certificate issuerCert in issuerCerts) { + SafeCalling.OnRuntimeExceptionLog(() => { + IBasicOcspResponse basicOCSPResp = new OcspClientBouncyCastle().GetBasicOCSPResp(certificate, issuerCert, + null); + FillOcspResponses(ocspResponses, basicOCSPResp, DateTimeUtil.GetCurrentUtcTime(), TimeBasedContext.PRESENT + ); + } + , report, (e) => new CertificateReportItem(certificate, REVOCATION_DATA_CHECK, MessageFormatUtil.Format(OCSP_CLIENT_FAILURE + , "OcspClientBouncyCastle"), e, ReportItem.ReportItemStatus.INDETERMINATE)); } - , report, (e) => new CertificateReportItem(certificate, REVOCATION_DATA_CHECK, MessageFormatUtil.Format(OCSP_CLIENT_FAILURE - , "OcspClientBouncyCastle"), e, ReportItem.ReportItemStatus.INDETERMINATE)); } return ocspResponses; } @@ -394,19 +429,21 @@ private void TryToFetchRevInfoOnline(ValidationReport report, ValidationContext SignatureValidationProperties.OnlineFetching ocspOnlineFetching = properties.GetRevocationOnlineFetching(context .SetValidatorContext(ValidatorContext.OCSP_VALIDATOR)); if (SignatureValidationProperties.OnlineFetching.FETCH_IF_NO_OTHER_DATA_AVAILABLE == ocspOnlineFetching) { - SafeCalling.OnRuntimeExceptionLog(() => { - IBasicOcspResponse basicOCSPResp = new OcspClientBouncyCastle().GetBasicOCSPResp(certificate, (IX509Certificate - )certificateRetriever.RetrieveIssuerCertificate(certificate), null); - IList ocspResponses = new List(); - FillOcspResponses(ocspResponses, basicOCSPResp, DateTimeUtil.GetCurrentUtcTime(), TimeBasedContext.PRESENT - ); - // Sort all the OCSP responses available based on the most recent revocation data. - onlineOcspResponses.AddAll(ocspResponses.Sorted((o1, o2) => o2.singleResp.GetThisUpdate().CompareTo(o1.singleResp - .GetThisUpdate())).ToList()); + foreach (IX509Certificate issuerCert in certificateRetriever.RetrieveIssuerCertificate(certificate)) { + SafeCalling.OnRuntimeExceptionLog(() => { + IBasicOcspResponse basicOCSPResp = new OcspClientBouncyCastle().GetBasicOCSPResp(certificate, issuerCert, + null); + IList ocspResponses = new List(); + FillOcspResponses(ocspResponses, basicOCSPResp, DateTimeUtil.GetCurrentUtcTime(), TimeBasedContext.PRESENT + ); + // Sort all the OCSP responses available based on the most recent revocation data. + onlineOcspResponses.AddAll(ocspResponses.Sorted((o1, o2) => o2.singleResp.GetThisUpdate().CompareTo(o1.singleResp + .GetThisUpdate())).ToList()); + } + , report, (e) => new CertificateReportItem(certificate, REVOCATION_DATA_CHECK, MessageFormatUtil.Format(OCSP_CLIENT_FAILURE + , "OcspClientBouncyCastle"), e, ReportItem.ReportItemStatus.INDETERMINATE)); } - , report, (e) => new CertificateReportItem(certificate, REVOCATION_DATA_CHECK, MessageFormatUtil.Format(OCSP_CLIENT_FAILURE - , "OcspClientBouncyCastle"), e, ReportItem.ReportItemStatus.INDETERMINATE)); } } @@ -446,7 +483,7 @@ public class OcspResponseValidationInfo { /// /// /// - /// + /// /// time based context which corresponds to generation date /// public OcspResponseValidationInfo(ISingleResponse singleResp, IBasicOcspResponse basicOCSPResp, DateTime trustedGenerationDate @@ -485,7 +522,7 @@ public class CrlValidationInfo { /// /// /// - /// + /// /// time based context which corresponds to generation date /// public CrlValidationInfo(IX509Crl crl, DateTime trustedGenerationDate, TimeBasedContext timeBasedContext) { diff --git a/itext/itext.sign/itext/signatures/validation/v1/SafeCalling.cs b/itext/itext.sign/itext/signatures/validation/SafeCalling.cs similarity index 97% rename from itext/itext.sign/itext/signatures/validation/v1/SafeCalling.cs rename to itext/itext.sign/itext/signatures/validation/SafeCalling.cs index 12c8b294bb..053894a8e1 100644 --- a/itext/itext.sign/itext/signatures/validation/v1/SafeCalling.cs +++ b/itext/itext.sign/itext/signatures/validation/SafeCalling.cs @@ -21,9 +21,9 @@ You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ using System; -using iText.Signatures.Validation.V1.Report; +using iText.Signatures.Validation.Report; -namespace iText.Signatures.Validation.V1 { +namespace iText.Signatures.Validation { //\cond DO_NOT_DOCUMENT internal sealed class SafeCalling { private SafeCalling() { diff --git a/itext/itext.sign/itext/signatures/validation/v1/SignatureValidationProperties.cs b/itext/itext.sign/itext/signatures/validation/SignatureValidationProperties.cs similarity index 96% rename from itext/itext.sign/itext/signatures/validation/v1/SignatureValidationProperties.cs rename to itext/itext.sign/itext/signatures/validation/SignatureValidationProperties.cs index 87dc2498c7..a3848e455b 100644 --- a/itext/itext.sign/itext/signatures/validation/v1/SignatureValidationProperties.cs +++ b/itext/itext.sign/itext/signatures/validation/SignatureValidationProperties.cs @@ -24,10 +24,10 @@ You should have received a copy of the GNU Affero General Public License using System.Collections.Generic; using iText.Commons.Utils; using iText.Commons.Utils.Collections; -using iText.Signatures.Validation.V1.Context; -using iText.Signatures.Validation.V1.Extensions; +using iText.Signatures.Validation.Context; +using iText.Signatures.Validation.Extensions; -namespace iText.Signatures.Validation.V1 { +namespace iText.Signatures.Validation { /// /// Class which stores properties, which are related to signature validation process. /// @@ -105,7 +105,7 @@ public virtual TimeSpan GetFreshness(ValidationContext validationContext) { /// /// instance. /// - public iText.Signatures.Validation.V1.SignatureValidationProperties SetFreshness(ValidatorContexts validatorContexts + public iText.Signatures.Validation.SignatureValidationProperties SetFreshness(ValidatorContexts validatorContexts , CertificateSources certificateSources, TimeBasedContexts timeBasedContexts, TimeSpan value) { SetParameterValueFor(validatorContexts.GetSet(), certificateSources.GetSet(), timeBasedContexts.GetSet(), (p) => p.SetFreshness(value)); @@ -135,7 +135,7 @@ public virtual bool GetContinueAfterFailure(ValidationContext validationContext) /// /// instance. /// - public iText.Signatures.Validation.V1.SignatureValidationProperties SetContinueAfterFailure(ValidatorContexts + public iText.Signatures.Validation.SignatureValidationProperties SetContinueAfterFailure(ValidatorContexts validatorContexts, CertificateSources certificateSources, bool value) { SetParameterValueFor(validatorContexts.GetSet(), certificateSources.GetSet(), TimeBasedContexts.All().GetSet (), (p) => p.SetContinueAfterFailure(value)); @@ -162,7 +162,7 @@ public virtual SignatureValidationProperties.OnlineFetching GetRevocationOnlineF /// /// instance. /// - public iText.Signatures.Validation.V1.SignatureValidationProperties SetRevocationOnlineFetching(ValidatorContexts + public iText.Signatures.Validation.SignatureValidationProperties SetRevocationOnlineFetching(ValidatorContexts validatorContexts, CertificateSources certificateSources, TimeBasedContexts timeBasedContexts, SignatureValidationProperties.OnlineFetching onlineFetching) { SetParameterValueFor(validatorContexts.GetSet(), certificateSources.GetSet(), timeBasedContexts.GetSet(), @@ -187,7 +187,7 @@ public virtual IList GetRequiredExtensions(ValidationConte /// for extensions to be present /// list of required /// this same instance - public iText.Signatures.Validation.V1.SignatureValidationProperties SetRequiredExtensions(CertificateSources + public iText.Signatures.Validation.SignatureValidationProperties SetRequiredExtensions(CertificateSources certificateSources, IList requiredExtensions) { // make a defensive copy of requiredExtensions and already wrap it with unmodifiableList so that we don't have // to do this every time it is retrieved. Now we are protected against changes in th passed list and from diff --git a/itext/itext.sign/itext/signatures/validation/v1/SignatureValidator.cs b/itext/itext.sign/itext/signatures/validation/SignatureValidator.cs similarity index 86% rename from itext/itext.sign/itext/signatures/validation/v1/SignatureValidator.cs rename to itext/itext.sign/itext/signatures/validation/SignatureValidator.cs index 2c361986ac..199f9f763b 100644 --- a/itext/itext.sign/itext/signatures/validation/v1/SignatureValidator.cs +++ b/itext/itext.sign/itext/signatures/validation/SignatureValidator.cs @@ -32,12 +32,13 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Cert.Ocsp; using iText.Commons.Bouncycastle.Security; using iText.Commons.Utils; +using iText.Kernel.Exceptions; using iText.Kernel.Pdf; using iText.Signatures; -using iText.Signatures.Validation.V1.Context; -using iText.Signatures.Validation.V1.Report; +using iText.Signatures.Validation.Context; +using iText.Signatures.Validation.Report; -namespace iText.Signatures.Validation.V1 { +namespace iText.Signatures.Validation { /// Validator class, which is expected to be used for signatures validation. public class SignatureValidator { public const String VALIDATING_SIGNATURE_NAME = "Validating signature {0}"; @@ -98,6 +99,14 @@ public class SignatureValidator { internal const String ADD_KNOWN_CERTIFICATES_FAILED = "Unexpected exception occurred adding known certificates to certificate retriever."; //\endcond +//\cond DO_NOT_DOCUMENT + internal const String SIGNATURE_NOT_FOUND = "Document doesn't contain signature field {0}."; +//\endcond + +//\cond DO_NOT_DOCUMENT + internal const String VALIDATION_PERFORMED = "Validation has already been performed. " + "You should create new SignatureValidator instance for each validation call."; +//\endcond + private static readonly IBouncyCastleFactory BOUNCY_CASTLE_FACTORY = BouncyCastleFactoryCreator.GetFactory (); @@ -122,6 +131,8 @@ public class SignatureValidator { private ValidationCrlClient validationCrlClient; + private bool validationPerformed = false; + /// /// Creates new instance of /// . @@ -157,8 +168,7 @@ protected internal SignatureValidator(PdfDocument originalDocument, ValidatorCha /// /// instance /// - public virtual iText.Signatures.Validation.V1.SignatureValidator SetEventCountingMetaInfo(IMetaInfo metaInfo - ) { + public virtual iText.Signatures.Validation.SignatureValidator SetEventCountingMetaInfo(IMetaInfo metaInfo) { this.metaInfo = metaInfo; return this; } @@ -166,10 +176,14 @@ public virtual iText.Signatures.Validation.V1.SignatureValidator SetEventCountin /// Validate all signatures in the document. /// /// - /// + /// /// which contains detailed validation results /// public virtual ValidationReport ValidateSignatures() { + if (validationPerformed) { + throw new PdfException(VALIDATION_PERFORMED); + } + validationPerformed = true; ValidationReport report = new ValidationReport(); SafeCalling.OnRuntimeExceptionLog(() => { documentRevisionsValidator.SetEventCountingMetaInfo(metaInfo); @@ -182,30 +196,34 @@ public virtual ValidationReport ValidateSignatures() { if (StopValidation(report, validationContext)) { return report; } - SignatureUtil util = new SignatureUtil(originalDocument); - IList signatureNames = util.GetSignatureNames(); - JavaCollectionsUtil.Reverse(signatureNames); - foreach (String fieldName in signatureNames) { - try { - using (PdfDocument doc = new PdfDocument(new PdfReader(util.ExtractRevision(fieldName)), new DocumentProperties - ().SetEventCountingMetaInfo(metaInfo))) { - ValidationReport subReport = ValidateLatestSignature(doc); - report.Merge(subReport); - if (StopValidation(report, validationContext)) { - return report; - } - } - } - catch (System.IO.IOException e) { - report.AddReportItem(new ReportItem(SIGNATURE_VERIFICATION, REVISIONS_RETRIEVAL_FAILED, e, ReportItem.ReportItemStatus - .INDETERMINATE)); - } - catch (Exception e) { - report.AddReportItem(new ReportItem(SIGNATURE_VERIFICATION, REVISIONS_RETRIEVAL_FAILED, e, ReportItem.ReportItemStatus - .INDETERMINATE)); - } + return report.Merge(Validate(null)); + } + + /// Validate single signature in the document. + /// name of the signature to validate + /// + /// + /// + /// which contains detailed validation results. + /// + public virtual ValidationReport ValidateSignature(String signatureName) { + if (validationPerformed) { + throw new PdfException(VALIDATION_PERFORMED); } - return report; + validationPerformed = true; + ValidationReport report = new ValidationReport(); + SafeCalling.OnRuntimeExceptionLog(() => { + documentRevisionsValidator.SetEventCountingMetaInfo(metaInfo); + ValidationReport revisionsValidationReport = documentRevisionsValidator.ValidateAllDocumentRevisions(validationContext + , originalDocument, signatureName); + report.Merge(revisionsValidationReport); + } + , report, (e) => new ReportItem(SIGNATURE_VERIFICATION, REVISIONS_VALIDATION_FAILED, e, ReportItem.ReportItemStatus + .INDETERMINATE)); + if (StopValidation(report, validationContext)) { + return report; + } + return report.Merge(Validate(signatureName)); } //\cond DO_NOT_DOCUMENT @@ -267,6 +285,48 @@ internal virtual ValidationReport ValidateLatestSignature(PdfDocument document) } //\endcond + private ValidationReport Validate(String signatureName) { + ValidationReport validationReport = new ValidationReport(); + bool validateSingleSignature = signatureName != null; + SignatureUtil util = new SignatureUtil(originalDocument); + IList signatureNames = util.GetSignatureNames(); + JavaCollectionsUtil.Reverse(signatureNames); + foreach (String fieldName in signatureNames) { + ValidationReport subReport = new ValidationReport(); + try { + using (PdfDocument doc = new PdfDocument(new PdfReader(util.ExtractRevision(fieldName), originalDocument.GetReader + ().GetPropertiesCopy()).SetStrictnessLevel(PdfReader.StrictnessLevel.CONSERVATIVE), new DocumentProperties + ().SetEventCountingMetaInfo(metaInfo))) { + subReport.Merge(ValidateLatestSignature(doc)); + } + } + catch (System.IO.IOException e) { + subReport.AddReportItem(new ReportItem(SIGNATURE_VERIFICATION, REVISIONS_RETRIEVAL_FAILED, e, ReportItem.ReportItemStatus + .INDETERMINATE)); + } + catch (Exception e) { + subReport.AddReportItem(new ReportItem(SIGNATURE_VERIFICATION, REVISIONS_RETRIEVAL_FAILED, e, ReportItem.ReportItemStatus + .INDETERMINATE)); + } + if (!validateSingleSignature) { + validationReport.Merge(subReport); + if (StopValidation(subReport, validationContext)) { + return validationReport; + } + } + else { + if (fieldName.Equals(signatureName)) { + return subReport; + } + } + } + if (validateSingleSignature) { + validationReport.AddReportItem(new ReportItem(SIGNATURE_VERIFICATION, MessageFormatUtil.Format(SIGNATURE_NOT_FOUND + , signatureName), ReportItem.ReportItemStatus.INDETERMINATE)); + } + return validationReport; + } + private void FindValidationClients() { foreach (IOcspClient ocspClient in this.properties.GetOcspClients()) { if (ocspClient.GetType() == typeof(ValidationOcspClient)) { diff --git a/itext/itext.sign/itext/signatures/validation/v1/TrustedCertificatesStore.cs b/itext/itext.sign/itext/signatures/validation/TrustedCertificatesStore.cs similarity index 56% rename from itext/itext.sign/itext/signatures/validation/v1/TrustedCertificatesStore.cs rename to itext/itext.sign/itext/signatures/validation/TrustedCertificatesStore.cs index 11022b390b..0117a37df5 100644 --- a/itext/itext.sign/itext/signatures/validation/v1/TrustedCertificatesStore.cs +++ b/itext/itext.sign/itext/signatures/validation/TrustedCertificatesStore.cs @@ -23,25 +23,27 @@ You should have received a copy of the GNU Affero General Public License using System; using System.Collections.Generic; using iText.Commons.Bouncycastle.Cert; +using iText.Commons.Utils; +using iText.Commons.Utils.Collections; -namespace iText.Signatures.Validation.V1 { +namespace iText.Signatures.Validation { /// Trusted certificates storage class to be used to configure trusted certificates in a particular way. /// public class TrustedCertificatesStore { - private readonly IDictionary generallyTrustedCertificates = new Dictionary(); + private readonly IDictionary> generallyTrustedCertificates = new Dictionary + >(); - private readonly IDictionary ocspTrustedCertificates = new Dictionary(); + private readonly IDictionary> ocspTrustedCertificates = new Dictionary + >(); - private readonly IDictionary timestampTrustedCertificates = new Dictionary(); + private readonly IDictionary> timestampTrustedCertificates = new Dictionary + >(); - private readonly IDictionary crlTrustedCertificates = new Dictionary(); + private readonly IDictionary> crlTrustedCertificates = new Dictionary + >(); - private readonly IDictionary caTrustedCertificates = new Dictionary(); + private readonly IDictionary> caTrustedCertificates = new Dictionary + >(); /// Add collection of certificates to be trusted for any possible usage. /// @@ -53,7 +55,7 @@ public class TrustedCertificatesStore { /// public virtual void AddGenerallyTrustedCertificates(ICollection certificates) { foreach (IX509Certificate certificate in certificates) { - generallyTrustedCertificates.Put(((IX509Certificate)certificate).GetSubjectDN().ToString(), certificate); + AddCertificateToMap(certificate, generallyTrustedCertificates); } } @@ -72,7 +74,7 @@ public virtual void AddGenerallyTrustedCertificates(ICollection public virtual void AddOcspTrustedCertificates(ICollection certificates) { foreach (IX509Certificate certificate in certificates) { - ocspTrustedCertificates.Put(((IX509Certificate)certificate).GetSubjectDN().ToString(), certificate); + AddCertificateToMap(certificate, ocspTrustedCertificates); } } @@ -91,7 +93,7 @@ public virtual void AddOcspTrustedCertificates(ICollection cer /// public virtual void AddCrlTrustedCertificates(ICollection certificates) { foreach (IX509Certificate certificate in certificates) { - crlTrustedCertificates.Put(((IX509Certificate)certificate).GetSubjectDN().ToString(), certificate); + AddCertificateToMap(certificate, crlTrustedCertificates); } } @@ -110,7 +112,7 @@ public virtual void AddCrlTrustedCertificates(ICollection cert /// public virtual void AddTimestampTrustedCertificates(ICollection certificates) { foreach (IX509Certificate certificate in certificates) { - timestampTrustedCertificates.Put(((IX509Certificate)certificate).GetSubjectDN().ToString(), certificate); + AddCertificateToMap(certificate, timestampTrustedCertificates); } } @@ -128,7 +130,7 @@ public virtual void AddTimestampTrustedCertificates(ICollection public virtual void AddCATrustedCertificates(ICollection certificates) { foreach (IX509Certificate certificate in certificates) { - caTrustedCertificates.Put(((IX509Certificate)certificate).GetSubjectDN().ToString(), certificate); + AddCertificateToMap(certificate, caTrustedCertificates); } } @@ -146,7 +148,7 @@ public virtual void AddCATrustedCertificates(ICollection certi /// otherwise /// public virtual bool IsCertificateGenerallyTrusted(IX509Certificate certificate) { - return generallyTrustedCertificates.ContainsKey(((IX509Certificate)certificate).GetSubjectDN().ToString()); + return MapContainsCertificate(certificate, generallyTrustedCertificates); } /// Check if provided certificate is configured to be trusted for OCSP response generation. @@ -163,7 +165,7 @@ public virtual bool IsCertificateGenerallyTrusted(IX509Certificate certificate) /// otherwise /// public virtual bool IsCertificateTrustedForOcsp(IX509Certificate certificate) { - return ocspTrustedCertificates.ContainsKey(((IX509Certificate)certificate).GetSubjectDN().ToString()); + return MapContainsCertificate(certificate, ocspTrustedCertificates); } /// Check if provided certificate is configured to be trusted for CRL generation. @@ -180,7 +182,7 @@ public virtual bool IsCertificateTrustedForOcsp(IX509Certificate certificate) { /// otherwise /// public virtual bool IsCertificateTrustedForCrl(IX509Certificate certificate) { - return crlTrustedCertificates.ContainsKey(((IX509Certificate)certificate).GetSubjectDN().ToString()); + return MapContainsCertificate(certificate, crlTrustedCertificates); } /// Check if provided certificate is configured to be trusted for timestamp generation. @@ -197,7 +199,7 @@ public virtual bool IsCertificateTrustedForCrl(IX509Certificate certificate) { /// otherwise /// public virtual bool IsCertificateTrustedForTimestamp(IX509Certificate certificate) { - return timestampTrustedCertificates.ContainsKey(((IX509Certificate)certificate).GetSubjectDN().ToString()); + return MapContainsCertificate(certificate, timestampTrustedCertificates); } /// Check if provided certificate is configured to be trusted to be CA. @@ -214,10 +216,10 @@ public virtual bool IsCertificateTrustedForTimestamp(IX509Certificate certificat /// otherwise /// public virtual bool IsCertificateTrustedForCA(IX509Certificate certificate) { - return caTrustedCertificates.ContainsKey(((IX509Certificate)certificate).GetSubjectDN().ToString()); + return MapContainsCertificate(certificate, caTrustedCertificates); } - /// Get certificate, if any, which is trusted for any usage, which corresponds to the provided certificate name. + /// Get certificates, if any, which is trusted for any usage, which corresponds to the provided certificate name. /// /// /// @@ -225,16 +227,17 @@ public virtual bool IsCertificateTrustedForCA(IX509Certificate certificate) { /// certificate name /// /// - /// + /// set of /// - /// which corresponds to the provided certificate name + /// which correspond to the provided certificate name /// - public virtual IX509Certificate GetGenerallyTrustedCertificate(String certificateName) { - return generallyTrustedCertificates.Get(certificateName); + public virtual ICollection GetGenerallyTrustedCertificates(String certificateName) { + return generallyTrustedCertificates.GetOrDefault(certificateName, JavaCollectionsUtil.EmptySet()); } /// - /// Get certificate, if any, which is trusted for OCSP response generation, + /// Get certificates, if any, which is trusted for OCSP response generation, /// which corresponds to the provided certificate name. /// /// @@ -243,28 +246,32 @@ public virtual IX509Certificate GetGenerallyTrustedCertificate(String certificat /// certificate name /// /// - /// + /// set of /// - /// which corresponds to the provided certificate name + /// which correspond to the provided certificate name /// - public virtual IX509Certificate GetCertificateTrustedForOcsp(String certificateName) { - return ocspTrustedCertificates.Get(certificateName); + public virtual ICollection GetCertificatesTrustedForOcsp(String certificateName) { + return ocspTrustedCertificates.GetOrDefault(certificateName, JavaCollectionsUtil.EmptySet()); } - /// Get certificate, if any, which is trusted for CRL generation, which corresponds to the provided certificate name. - /// + /// + /// Get certificates, if any, which is trusted for CRL generation, + /// which corresponds to the provided certificate name. + /// /// /// /// /// certificate name /// /// - /// + /// set of /// - /// which corresponds to the provided certificate name + /// which correspond to the provided certificate name /// - public virtual IX509Certificate GetCertificateTrustedForCrl(String certificateName) { - return crlTrustedCertificates.Get(certificateName); + public virtual ICollection GetCertificatesTrustedForCrl(String certificateName) { + return crlTrustedCertificates.GetOrDefault(certificateName, JavaCollectionsUtil.EmptySet + ()); } /// @@ -277,55 +284,53 @@ public virtual IX509Certificate GetCertificateTrustedForCrl(String certificateNa /// certificate name /// /// - /// + /// set of /// - /// which corresponds to the provided certificate name + /// which correspond to the provided certificate name /// - public virtual IX509Certificate GetCertificateTrustedForTimestamp(String certificateName) { - return timestampTrustedCertificates.Get(certificateName); + public virtual ICollection GetCertificatesTrustedForTimestamp(String certificateName) { + return timestampTrustedCertificates.GetOrDefault(certificateName, JavaCollectionsUtil.EmptySet()); } - /// Get certificate, if any, which is trusted to be a CA, which corresponds to the provided certificate name. - /// + /// + /// Get certificates, if any, + /// which is trusted to be a CA, which corresponds to the provided certificate name. + /// /// /// /// /// certificate name /// /// - /// + /// set of /// - /// which corresponds to the provided certificate name + /// which correspond to the provided certificate name /// - public virtual IX509Certificate GetCertificateTrustedForCA(String certificateName) { - return caTrustedCertificates.Get(certificateName); + public virtual ICollection GetCertificatesTrustedForCA(String certificateName) { + return caTrustedCertificates.GetOrDefault(certificateName, JavaCollectionsUtil.EmptySet( + )); } - /// Get certificate, if any, which corresponds to the provided certificate name. + /// Get certificates, if any, which corresponds to the provided certificate name. /// /// /// /// certificate name /// /// - /// + /// set of /// - /// which corresponds to the provided certificate name + /// which correspond to the provided certificate name /// - public virtual IX509Certificate GetKnownCertificate(String certificateName) { - if (generallyTrustedCertificates.ContainsKey(certificateName)) { - return generallyTrustedCertificates.Get(certificateName); - } - if (ocspTrustedCertificates.ContainsKey(certificateName)) { - return ocspTrustedCertificates.Get(certificateName); - } - if (crlTrustedCertificates.ContainsKey(certificateName)) { - return crlTrustedCertificates.Get(certificateName); - } - if (timestampTrustedCertificates.ContainsKey(certificateName)) { - return timestampTrustedCertificates.Get(certificateName); - } - return caTrustedCertificates.Get(certificateName); + public virtual ICollection GetKnownCertificates(String certificateName) { + ICollection result = new HashSet(); + AddMatched(result, generallyTrustedCertificates, certificateName); + AddMatched(result, ocspTrustedCertificates, certificateName); + AddMatched(result, crlTrustedCertificates, certificateName); + AddMatched(result, timestampTrustedCertificates, certificateName); + AddMatched(result, caTrustedCertificates, certificateName); + return result; } /// Get all the certificates, which where provided to this storage as trusted certificate. @@ -337,13 +342,80 @@ public virtual IX509Certificate GetKnownCertificate(String certificateName) { /// instances /// public virtual ICollection GetAllTrustedCertificates() { - IList certificates = new List(); - certificates.AddAll(generallyTrustedCertificates.Values); - certificates.AddAll(ocspTrustedCertificates.Values); - certificates.AddAll(crlTrustedCertificates.Values); - certificates.AddAll(timestampTrustedCertificates.Values); - certificates.AddAll(caTrustedCertificates.Values); + ICollection certificates = new HashSet(); + foreach (ICollection set in generallyTrustedCertificates.Values) { + certificates.AddAll(set); + } + foreach (ICollection set in ocspTrustedCertificates.Values) { + certificates.AddAll(set); + } + foreach (ICollection set in crlTrustedCertificates.Values) { + certificates.AddAll(set); + } + foreach (ICollection set in timestampTrustedCertificates.Values) { + certificates.AddAll(set); + } + foreach (ICollection set in caTrustedCertificates.Values) { + certificates.AddAll(set); + } return certificates; } + + /// Get all the certificates having name as subject, which where provided to this storage as trusted certificate. + /// + /// the subject name value for which to retrieve all trusted certificate + /// + /// set of + /// + /// which correspond to the provided certificate name + /// + public virtual ICollection GetAllTrustedCertificates(String name) { + ICollection certificates = new HashSet(); + ICollection set = generallyTrustedCertificates.Get(name); + if (set != null) { + certificates.AddAll(set); + } + set = ocspTrustedCertificates.Get(name); + if (set != null) { + certificates.AddAll(set); + } + set = crlTrustedCertificates.Get(name); + if (set != null) { + certificates.AddAll(set); + } + set = timestampTrustedCertificates.Get(name); + if (set != null) { + certificates.AddAll(set); + } + set = caTrustedCertificates.Get(name); + if (set != null) { + certificates.AddAll(set); + } + return certificates; + } + + private static void AddCertificateToMap(IX509Certificate certificate, IDictionary> map) { + String name = ((IX509Certificate)certificate).GetSubjectDN().ToString(); + ICollection set = map.ComputeIfAbsent(name, (k) => new HashSet()); + set.Add(certificate); + } + + private static bool MapContainsCertificate(IX509Certificate certificate, IDictionary> map) { + ICollection set = map.Get(((IX509Certificate)certificate).GetSubjectDN().ToString()); + if (set == null) { + return false; + } + return set.Contains(certificate); + } + + private static void AddMatched(ICollection target, IDictionary> source, String certificateName) { + ICollection subset = source.Get(certificateName); + if (subset != null) { + target.AddAll(subset); + } + } } } diff --git a/itext/itext.sign/itext/signatures/validation/v1/ValidationCrlClient.cs b/itext/itext.sign/itext/signatures/validation/ValidationCrlClient.cs similarity index 95% rename from itext/itext.sign/itext/signatures/validation/v1/ValidationCrlClient.cs rename to itext/itext.sign/itext/signatures/validation/ValidationCrlClient.cs index 02eba73211..590bb69335 100644 --- a/itext/itext.sign/itext/signatures/validation/v1/ValidationCrlClient.cs +++ b/itext/itext.sign/itext/signatures/validation/ValidationCrlClient.cs @@ -26,9 +26,9 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Security; using iText.Commons.Utils; using iText.Signatures; -using iText.Signatures.Validation.V1.Context; +using iText.Signatures.Validation.Context; -namespace iText.Signatures.Validation.V1 { +namespace iText.Signatures.Validation { /// CRL client which is expected to be used in case CRL responses shall be linked with generation date. /// public class ValidationCrlClient : ICrlClient { @@ -57,7 +57,7 @@ public ValidationCrlClient() { /// /// /// - /// + /// /// time based context which corresponds to generation date /// public virtual void AddCrl(IX509Crl response, DateTime date, TimeBasedContext context) { diff --git a/itext/itext.sign/itext/signatures/validation/v1/ValidationMetaInfo.cs b/itext/itext.sign/itext/signatures/validation/ValidationMetaInfo.cs similarity index 96% rename from itext/itext.sign/itext/signatures/validation/v1/ValidationMetaInfo.cs rename to itext/itext.sign/itext/signatures/validation/ValidationMetaInfo.cs index 99f42397f2..f56ff28935 100644 --- a/itext/itext.sign/itext/signatures/validation/v1/ValidationMetaInfo.cs +++ b/itext/itext.sign/itext/signatures/validation/ValidationMetaInfo.cs @@ -22,7 +22,7 @@ You should have received a copy of the GNU Affero General Public License */ using iText.Commons.Actions.Contexts; -namespace iText.Signatures.Validation.V1 { +namespace iText.Signatures.Validation { //\cond DO_NOT_DOCUMENT internal class ValidationMetaInfo : IMetaInfo { } diff --git a/itext/itext.sign/itext/signatures/validation/v1/ValidationOcspClient.cs b/itext/itext.sign/itext/signatures/validation/ValidationOcspClient.cs similarity index 95% rename from itext/itext.sign/itext/signatures/validation/v1/ValidationOcspClient.cs rename to itext/itext.sign/itext/signatures/validation/ValidationOcspClient.cs index da39bd7f26..47c89bb7cf 100644 --- a/itext/itext.sign/itext/signatures/validation/v1/ValidationOcspClient.cs +++ b/itext/itext.sign/itext/signatures/validation/ValidationOcspClient.cs @@ -28,9 +28,9 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Utils; using iText.Commons.Utils.Collections; using iText.Signatures; -using iText.Signatures.Validation.V1.Context; +using iText.Signatures.Validation.Context; -namespace iText.Signatures.Validation.V1 { +namespace iText.Signatures.Validation { /// OCSP client which is expected to be used in case OCSP responses shall be linked with generation date. /// public class ValidationOcspClient : IOcspClient { @@ -59,7 +59,7 @@ public ValidationOcspClient() { /// /// /// - /// + /// /// time based context which corresponds to generation date /// public virtual void AddResponse(IBasicOcspResponse response, DateTime date, TimeBasedContext context) { diff --git a/itext/itext.sign/itext/signatures/validation/v1/ValidatorChainBuilder.cs b/itext/itext.sign/itext/signatures/validation/ValidatorChainBuilder.cs similarity index 71% rename from itext/itext.sign/itext/signatures/validation/v1/ValidatorChainBuilder.cs rename to itext/itext.sign/itext/signatures/validation/ValidatorChainBuilder.cs index 22b904a04d..cbd6fef9c4 100644 --- a/itext/itext.sign/itext/signatures/validation/v1/ValidatorChainBuilder.cs +++ b/itext/itext.sign/itext/signatures/validation/ValidatorChainBuilder.cs @@ -20,12 +20,13 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ +using System; using System.Collections.Generic; using iText.Commons.Bouncycastle.Cert; using iText.Kernel.Pdf; using iText.Signatures; -namespace iText.Signatures.Validation.V1 { +namespace iText.Signatures.Validation { /// A builder class to construct all necessary parts of a validation chain. /// /// A builder class to construct all necessary parts of a validation chain. @@ -34,17 +35,21 @@ namespace iText.Signatures.Validation.V1 { public class ValidatorChainBuilder { private SignatureValidationProperties properties; - private IssuingCertificateRetriever certificateRetriever; + private Func certificateRetrieverFactory; - private CertificateChainValidator certificateChainValidator; + private Func certificateChainValidatorFactory; - private RevocationDataValidator revocationDataValidator; + private Func revocationDataValidatorFactory; - private OCSPValidator ocspValidator; + private Func ocspValidatorFactory; - private CRLValidator crlValidator; + private Func crlValidatorFactory; - private DocumentRevisionsValidator documentRevisionsValidator; + private Func documentRevisionsValidatorFactory; + + private ICollection trustedCertificates; + + private ICollection knownCertificates; /// /// Create a new @@ -143,65 +148,65 @@ public virtual CRLValidator BuildCRLValidator() { } /// - /// Use this instance of a + /// Use this factory method to create instances of /// - /// in the validation chain. + /// for use in the validation chain. /// - /// the document revisions validator instance to use + /// the document revisions validator factory method to use /// the current ValidatorChainBuilder. - public virtual ValidatorChainBuilder WithDocumentRevisionsValidator(DocumentRevisionsValidator documentRevisionsValidator - ) { - this.documentRevisionsValidator = documentRevisionsValidator; + public virtual ValidatorChainBuilder WithDocumentRevisionsValidatorFactory(Func documentRevisionsValidatorFactory) { + this.documentRevisionsValidatorFactory = documentRevisionsValidatorFactory; return this; } /// - /// Use this instance of a + /// Use this factory method to create instances of /// - /// in the validation chain. + /// for use in the validation chain. /// - /// the CRLValidator instance to use + /// the CRLValidatorFactory method to use /// the current ValidatorChainBuilder. - public virtual ValidatorChainBuilder WithCRLValidator(CRLValidator crlValidator) { - this.crlValidator = crlValidator; + public virtual ValidatorChainBuilder WithCRLValidatorFactory(Func crlValidatorFactory) { + this.crlValidatorFactory = crlValidatorFactory; return this; } /// - /// Use this instance of a + /// Use this factory method to create instances of /// - /// in the validation chain. + /// for use in the validation chain. /// - /// the OCSPValidator instance to use + /// the OCSPValidatorFactory method to use /// the current ValidatorChainBuilder. - public virtual ValidatorChainBuilder WithOCSPValidator(OCSPValidator ocspValidator) { - this.ocspValidator = ocspValidator; + public virtual ValidatorChainBuilder WithOCSPValidatorFactory(Func ocspValidatorFactory) { + this.ocspValidatorFactory = ocspValidatorFactory; return this; } /// - /// Use this instance of a + /// Use this factory method to create instances of /// - /// in the validation chain. + /// for use in the validation chain. /// - /// the RevocationDataValidator instance to use + /// the RevocationDataValidator factory method to use /// the current ValidatorChainBuilder. - public virtual ValidatorChainBuilder WithRevocationDataValidator(RevocationDataValidator revocationDataValidator + public virtual ValidatorChainBuilder WithRevocationDataValidatorFactory(Func revocationDataValidatorFactory ) { - this.revocationDataValidator = revocationDataValidator; + this.revocationDataValidatorFactory = revocationDataValidatorFactory; return this; } /// - /// Use this instance of a + /// Use this factory method to create instances of /// - /// in the validation chain. + /// for use in the validation chain. /// - /// the CertificateChainValidator instance to use + /// the CertificateChainValidator factory method to use /// the current ValidatorChainBuilder. - public virtual ValidatorChainBuilder WithCertificateChainValidator(CertificateChainValidator certificateChainValidator - ) { - this.certificateChainValidator = certificateChainValidator; + public virtual ValidatorChainBuilder WithCertificateChainValidatorFactory(Func + certificateChainValidatorFactory) { + this.certificateChainValidatorFactory = certificateChainValidatorFactory; return this; } @@ -219,15 +224,15 @@ public virtual ValidatorChainBuilder WithSignatureValidationProperties(Signature } /// - /// Use this instance of a + /// Use this factory method to create instances of /// - /// in the validation chain. + /// for use in the validation chain. /// - /// the IssuingCertificateRetriever instance to use + /// the IssuingCertificateRetriever factory method to use /// the current ValidatorChainBuilder. - public virtual ValidatorChainBuilder WithIssuingCertificateRetriever(IssuingCertificateRetriever certificateRetriever - ) { - this.certificateRetriever = certificateRetriever; + public virtual ValidatorChainBuilder WithIssuingCertificateRetrieverFactory(Func certificateRetrieverFactory) { + this.certificateRetrieverFactory = certificateRetrieverFactory; return this; } @@ -239,7 +244,7 @@ public virtual ValidatorChainBuilder WithIssuingCertificateRetriever(IssuingCert /// the current ValidatorChainBuilder. public virtual ValidatorChainBuilder WithKnownCertificates(ICollection knownCertificates ) { - GetCertificateRetriever().AddKnownCertificates(knownCertificates); + this.knownCertificates = new List(knownCertificates); return this; } @@ -251,10 +256,44 @@ public virtual ValidatorChainBuilder WithKnownCertificates(ICollectionthe current ValidatorChainBuilder. public virtual ValidatorChainBuilder WithTrustedCertificates(ICollection trustedCertificates ) { - GetCertificateRetriever().SetTrustedCertificates(trustedCertificates); + this.trustedCertificates = new List(trustedCertificates); return this; } + /// + /// Retrieves the explicitly added or automatically created + /// + /// instance. + /// + /// + /// the explicitly added or automatically created + /// + /// instance. + /// + public virtual IssuingCertificateRetriever GetCertificateRetriever() { + if (certificateRetrieverFactory == null) { + return BuildIssuingCertificateRetriever(); + } + return certificateRetrieverFactory(); + } + + /// + /// Retrieves the explicitly added or automatically created + /// + /// instance. + /// + /// + /// the explicitly added or automatically created + /// + /// instance. + /// + public virtual SignatureValidationProperties GetProperties() { + if (properties == null) { + properties = new SignatureValidationProperties(); + } + return properties; + } + //\cond DO_NOT_DOCUMENT /// /// Retrieves the explicitly added or automatically created @@ -267,10 +306,10 @@ public virtual ValidatorChainBuilder WithTrustedCertificates(ICollection internal virtual DocumentRevisionsValidator GetDocumentRevisionsValidator() { - if (documentRevisionsValidator == null) { - documentRevisionsValidator = BuildDocumentRevisionsValidator(); + if (documentRevisionsValidatorFactory == null) { + return BuildDocumentRevisionsValidator(); } - return documentRevisionsValidator; + return documentRevisionsValidatorFactory(); } //\endcond @@ -286,10 +325,10 @@ internal virtual DocumentRevisionsValidator GetDocumentRevisionsValidator() { /// instance. /// internal virtual CertificateChainValidator GetCertificateChainValidator() { - if (certificateChainValidator == null) { - certificateChainValidator = BuildCertificateChainValidator(); + if (certificateChainValidatorFactory == null) { + return BuildCertificateChainValidator(); } - return certificateChainValidator; + return certificateChainValidatorFactory(); } //\endcond @@ -305,10 +344,10 @@ internal virtual CertificateChainValidator GetCertificateChainValidator() { /// instance. /// internal virtual RevocationDataValidator GetRevocationDataValidator() { - if (revocationDataValidator == null) { - revocationDataValidator = BuildRevocationDataValidator(); + if (revocationDataValidatorFactory == null) { + return BuildRevocationDataValidator(); } - return revocationDataValidator; + return revocationDataValidatorFactory(); } //\endcond @@ -324,10 +363,10 @@ internal virtual RevocationDataValidator GetRevocationDataValidator() { /// instance. /// internal virtual CRLValidator GetCRLValidator() { - if (crlValidator == null) { - crlValidator = BuildCRLValidator(); + if (crlValidatorFactory == null) { + return BuildCRLValidator(); } - return crlValidator; + return crlValidatorFactory(); } //\endcond @@ -343,45 +382,22 @@ internal virtual CRLValidator GetCRLValidator() { /// instance. /// internal virtual OCSPValidator GetOCSPValidator() { - if (ocspValidator == null) { - ocspValidator = BuildOCSPValidator(); + if (ocspValidatorFactory == null) { + return BuildOCSPValidator(); } - return ocspValidator; + return ocspValidatorFactory(); } //\endcond - /// - /// Retrieves the explicitly added or automatically created - /// - /// instance. - /// - /// - /// the explicitly added or automatically created - /// - /// instance. - /// - public virtual IssuingCertificateRetriever GetCertificateRetriever() { - if (certificateRetriever == null) { - certificateRetriever = new IssuingCertificateRetriever(); + private IssuingCertificateRetriever BuildIssuingCertificateRetriever() { + IssuingCertificateRetriever result = new IssuingCertificateRetriever(); + if (trustedCertificates != null) { + result.SetTrustedCertificates(trustedCertificates); } - return certificateRetriever; - } - - /// - /// Retrieves the explicitly added or automatically created - /// - /// instance. - /// - /// - /// the explicitly added or automatically created - /// - /// instance. - /// - public virtual SignatureValidationProperties GetProperties() { - if (properties == null) { - properties = new SignatureValidationProperties(); + if (knownCertificates != null) { + result.AddKnownCertificates(knownCertificates); } - return properties; + return result; } } } diff --git a/itext/itext.sign/itext/signatures/validation/v1/context/CertificateSource.cs b/itext/itext.sign/itext/signatures/validation/context/CertificateSource.cs similarity index 97% rename from itext/itext.sign/itext/signatures/validation/v1/context/CertificateSource.cs rename to itext/itext.sign/itext/signatures/validation/context/CertificateSource.cs index f6924660cf..92b307624c 100644 --- a/itext/itext.sign/itext/signatures/validation/v1/context/CertificateSource.cs +++ b/itext/itext.sign/itext/signatures/validation/context/CertificateSource.cs @@ -20,7 +20,7 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ -namespace iText.Signatures.Validation.V1.Context { +namespace iText.Signatures.Validation.Context { /// This enum lists all possible contexts related to the certificate origin in which a validation may take place /// public enum CertificateSource { diff --git a/itext/itext.sign/itext/signatures/validation/v1/context/CertificateSources.cs b/itext/itext.sign/itext/signatures/validation/context/CertificateSources.cs similarity index 97% rename from itext/itext.sign/itext/signatures/validation/v1/context/CertificateSources.cs rename to itext/itext.sign/itext/signatures/validation/context/CertificateSources.cs index 91d26c8a47..f548514dbb 100644 --- a/itext/itext.sign/itext/signatures/validation/v1/context/CertificateSources.cs +++ b/itext/itext.sign/itext/signatures/validation/context/CertificateSources.cs @@ -22,9 +22,9 @@ You should have received a copy of the GNU Affero General Public License */ using System; using iText.Commons.Utils.Collections; -using iText.Signatures.Validation.V1.Context; +using iText.Signatures.Validation.Context; -namespace iText.Signatures.Validation.V1.Context { +namespace iText.Signatures.Validation.Context { /// /// Container class, which contains set of single /// diff --git a/itext/itext.sign/itext/signatures/validation/v1/context/TimeBasedContext.cs b/itext/itext.sign/itext/signatures/validation/context/TimeBasedContext.cs similarity index 96% rename from itext/itext.sign/itext/signatures/validation/v1/context/TimeBasedContext.cs rename to itext/itext.sign/itext/signatures/validation/context/TimeBasedContext.cs index 37da06cd55..7c7216ab71 100644 --- a/itext/itext.sign/itext/signatures/validation/v1/context/TimeBasedContext.cs +++ b/itext/itext.sign/itext/signatures/validation/context/TimeBasedContext.cs @@ -20,7 +20,7 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ -namespace iText.Signatures.Validation.V1.Context { +namespace iText.Signatures.Validation.Context { /// This enum is used for giving a perspective on a time period at which validation is happening. public enum TimeBasedContext { /// The date used lies in the past. diff --git a/itext/itext.sign/itext/signatures/validation/v1/context/TimeBasedContexts.cs b/itext/itext.sign/itext/signatures/validation/context/TimeBasedContexts.cs similarity index 98% rename from itext/itext.sign/itext/signatures/validation/v1/context/TimeBasedContexts.cs rename to itext/itext.sign/itext/signatures/validation/context/TimeBasedContexts.cs index 9c4992c5c1..26b3588dec 100644 --- a/itext/itext.sign/itext/signatures/validation/v1/context/TimeBasedContexts.cs +++ b/itext/itext.sign/itext/signatures/validation/context/TimeBasedContexts.cs @@ -23,7 +23,7 @@ You should have received a copy of the GNU Affero General Public License using System; using iText.Commons.Utils.Collections; -namespace iText.Signatures.Validation.V1.Context { +namespace iText.Signatures.Validation.Context { /// /// Container class, which contains set of single /// diff --git a/itext/itext.sign/itext/signatures/validation/v1/context/ValidationContext.cs b/itext/itext.sign/itext/signatures/validation/context/ValidationContext.cs similarity index 86% rename from itext/itext.sign/itext/signatures/validation/v1/context/ValidationContext.cs rename to itext/itext.sign/itext/signatures/validation/context/ValidationContext.cs index 6c8ea4b345..ab6830f993 100644 --- a/itext/itext.sign/itext/signatures/validation/v1/context/ValidationContext.cs +++ b/itext/itext.sign/itext/signatures/validation/context/ValidationContext.cs @@ -23,7 +23,7 @@ You should have received a copy of the GNU Affero General Public License using System; using iText.Commons.Utils; -namespace iText.Signatures.Validation.V1.Context { +namespace iText.Signatures.Validation.Context { /// Validation context class, which encapsulates specific context values, related to validation process. /// public class ValidationContext { @@ -33,7 +33,7 @@ public class ValidationContext { private readonly TimeBasedContext timeBasedContext; - private iText.Signatures.Validation.V1.Context.ValidationContext previousValidationContext; + private iText.Signatures.Validation.Context.ValidationContext previousValidationContext; /// /// Create @@ -64,7 +64,7 @@ public ValidationContext(ValidatorContext validatorContext, CertificateSource ce //\cond DO_NOT_DOCUMENT internal ValidationContext(ValidatorContext validatorContext, CertificateSource certificateSource, TimeBasedContext - timeBasedContext, iText.Signatures.Validation.V1.Context.ValidationContext previousValidationContext) + timeBasedContext, iText.Signatures.Validation.Context.ValidationContext previousValidationContext) : this(validatorContext, certificateSource, timeBasedContext) { this.previousValidationContext = previousValidationContext; } @@ -76,7 +76,7 @@ internal ValidationContext(ValidatorContext validatorContext, CertificateSource /// /// instance /// - public virtual iText.Signatures.Validation.V1.Context.ValidationContext GetPreviousValidationContext() { + public virtual iText.Signatures.Validation.Context.ValidationContext GetPreviousValidationContext() { return previousValidationContext; } @@ -105,9 +105,9 @@ public virtual CertificateSource GetCertificateSource() { /// /// instance /// - public virtual iText.Signatures.Validation.V1.Context.ValidationContext SetCertificateSource(CertificateSource + public virtual iText.Signatures.Validation.Context.ValidationContext SetCertificateSource(CertificateSource certificateSource) { - return new iText.Signatures.Validation.V1.Context.ValidationContext(validatorContext, certificateSource, timeBasedContext + return new iText.Signatures.Validation.Context.ValidationContext(validatorContext, certificateSource, timeBasedContext , this); } @@ -136,9 +136,9 @@ public virtual TimeBasedContext GetTimeBasedContext() { /// /// instance /// - public virtual iText.Signatures.Validation.V1.Context.ValidationContext SetTimeBasedContext(TimeBasedContext - timeBasedContext) { - return new iText.Signatures.Validation.V1.Context.ValidationContext(validatorContext, certificateSource, timeBasedContext + public virtual iText.Signatures.Validation.Context.ValidationContext SetTimeBasedContext(TimeBasedContext + timeBasedContext) { + return new iText.Signatures.Validation.Context.ValidationContext(validatorContext, certificateSource, timeBasedContext , this); } @@ -167,9 +167,9 @@ public virtual ValidatorContext GetValidatorContext() { /// /// instance /// - public virtual iText.Signatures.Validation.V1.Context.ValidationContext SetValidatorContext(ValidatorContext - validatorContext) { - return new iText.Signatures.Validation.V1.Context.ValidationContext(validatorContext, certificateSource, timeBasedContext + public virtual iText.Signatures.Validation.Context.ValidationContext SetValidatorContext(ValidatorContext + validatorContext) { + return new iText.Signatures.Validation.Context.ValidationContext(validatorContext, certificateSource, timeBasedContext , this); } @@ -195,7 +195,7 @@ public virtual iText.Signatures.Validation.V1.Context.ValidationContext SetValid /// /// otherwise /// - public static bool CheckIfContextChainContainsCertificateSource(iText.Signatures.Validation.V1.Context.ValidationContext + public static bool CheckIfContextChainContainsCertificateSource(iText.Signatures.Validation.Context.ValidationContext context, CertificateSource source) { if (context == null) { return false; @@ -244,7 +244,7 @@ public override bool Equals(Object o) { if (o == null || GetType() != o.GetType()) { return false; } - iText.Signatures.Validation.V1.Context.ValidationContext that = (iText.Signatures.Validation.V1.Context.ValidationContext + iText.Signatures.Validation.Context.ValidationContext that = (iText.Signatures.Validation.Context.ValidationContext )o; return certificateSource == that.certificateSource && validatorContext == that.validatorContext && timeBasedContext == that.timeBasedContext; diff --git a/itext/itext.sign/itext/signatures/validation/v1/context/ValidatorContext.cs b/itext/itext.sign/itext/signatures/validation/context/ValidatorContext.cs similarity index 96% rename from itext/itext.sign/itext/signatures/validation/v1/context/ValidatorContext.cs rename to itext/itext.sign/itext/signatures/validation/context/ValidatorContext.cs index bee283cc5d..14cca219dc 100644 --- a/itext/itext.sign/itext/signatures/validation/v1/context/ValidatorContext.cs +++ b/itext/itext.sign/itext/signatures/validation/context/ValidatorContext.cs @@ -20,9 +20,9 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ -using iText.Signatures.Validation.V1; +using iText.Signatures.Validation; -namespace iText.Signatures.Validation.V1.Context { +namespace iText.Signatures.Validation.Context { /// This enum lists all possible contexts related to the validator in which the validation is taking place. /// public enum ValidatorContext { diff --git a/itext/itext.sign/itext/signatures/validation/v1/context/ValidatorContexts.cs b/itext/itext.sign/itext/signatures/validation/context/ValidatorContexts.cs similarity index 98% rename from itext/itext.sign/itext/signatures/validation/v1/context/ValidatorContexts.cs rename to itext/itext.sign/itext/signatures/validation/context/ValidatorContexts.cs index 5512a2771f..42829578fd 100644 --- a/itext/itext.sign/itext/signatures/validation/v1/context/ValidatorContexts.cs +++ b/itext/itext.sign/itext/signatures/validation/context/ValidatorContexts.cs @@ -23,7 +23,7 @@ You should have received a copy of the GNU Affero General Public License using System; using iText.Commons.Utils.Collections; -namespace iText.Signatures.Validation.V1.Context { +namespace iText.Signatures.Validation.Context { /// /// Container class, which contains set of single /// diff --git a/itext/itext.sign/itext/signatures/validation/v1/extensions/CertificateExtension.cs b/itext/itext.sign/itext/signatures/validation/extensions/CertificateExtension.cs similarity index 95% rename from itext/itext.sign/itext/signatures/validation/v1/extensions/CertificateExtension.cs rename to itext/itext.sign/itext/signatures/validation/extensions/CertificateExtension.cs index 8486be8e06..4f571149a3 100644 --- a/itext/itext.sign/itext/signatures/validation/v1/extensions/CertificateExtension.cs +++ b/itext/itext.sign/itext/signatures/validation/extensions/CertificateExtension.cs @@ -26,7 +26,7 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Utils; using iText.Signatures; -namespace iText.Signatures.Validation.V1.Extensions { +namespace iText.Signatures.Validation.Extensions { /// Class representing certificate extension with all the information required for validation. public class CertificateExtension { private readonly String extensionOid; @@ -113,7 +113,7 @@ public override bool Equals(Object o) { if (o == null || GetType() != o.GetType()) { return false; } - iText.Signatures.Validation.V1.Extensions.CertificateExtension that = (iText.Signatures.Validation.V1.Extensions.CertificateExtension + iText.Signatures.Validation.Extensions.CertificateExtension that = (iText.Signatures.Validation.Extensions.CertificateExtension )o; return Object.Equals(extensionOid, that.extensionOid) && Object.Equals(extensionValue, that.extensionValue ); diff --git a/itext/itext.sign/itext/signatures/validation/v1/extensions/DynamicBasicConstraintsExtension.cs b/itext/itext.sign/itext/signatures/validation/extensions/DynamicBasicConstraintsExtension.cs similarity index 97% rename from itext/itext.sign/itext/signatures/validation/v1/extensions/DynamicBasicConstraintsExtension.cs rename to itext/itext.sign/itext/signatures/validation/extensions/DynamicBasicConstraintsExtension.cs index 3e68e2665e..7b72278e3f 100644 --- a/itext/itext.sign/itext/signatures/validation/v1/extensions/DynamicBasicConstraintsExtension.cs +++ b/itext/itext.sign/itext/signatures/validation/extensions/DynamicBasicConstraintsExtension.cs @@ -23,9 +23,10 @@ You should have received a copy of the GNU Affero General Public License using iText.Bouncycastleconnector; using iText.Commons.Bouncycastle; using iText.Commons.Bouncycastle.Cert; +using iText.Kernel.Crypto; using iText.Signatures; -namespace iText.Signatures.Validation.V1.Extensions { +namespace iText.Signatures.Validation.Extensions { /// /// Class representing "Basic Constraints" certificate extension, /// which uses provided amount of certificates in chain during the comparison. diff --git a/itext/itext.sign/itext/signatures/validation/v1/extensions/DynamicCertificateExtension.cs b/itext/itext.sign/itext/signatures/validation/extensions/DynamicCertificateExtension.cs similarity index 94% rename from itext/itext.sign/itext/signatures/validation/v1/extensions/DynamicCertificateExtension.cs rename to itext/itext.sign/itext/signatures/validation/extensions/DynamicCertificateExtension.cs index a745e7371d..5f1ac03ee4 100644 --- a/itext/itext.sign/itext/signatures/validation/v1/extensions/DynamicCertificateExtension.cs +++ b/itext/itext.sign/itext/signatures/validation/extensions/DynamicCertificateExtension.cs @@ -23,7 +23,7 @@ You should have received a copy of the GNU Affero General Public License using System; using iText.Commons.Bouncycastle.Asn1; -namespace iText.Signatures.Validation.V1.Extensions { +namespace iText.Signatures.Validation.Extensions { /// Certificate extension which is populated with additional dynamically changing validation related information. /// public class DynamicCertificateExtension : CertificateExtension { @@ -55,7 +55,7 @@ public DynamicCertificateExtension(String extensionOid, IAsn1Object extensionVal /// /// instance /// - public virtual iText.Signatures.Validation.V1.Extensions.DynamicCertificateExtension WithCertificateChainSize + public virtual iText.Signatures.Validation.Extensions.DynamicCertificateExtension WithCertificateChainSize (int certificateChainSize) { this.certificateChainSize = certificateChainSize; return this; diff --git a/itext/itext.sign/itext/signatures/validation/v1/extensions/ExtendedKeyUsageExtension.cs b/itext/itext.sign/itext/signatures/validation/extensions/ExtendedKeyUsageExtension.cs similarity index 98% rename from itext/itext.sign/itext/signatures/validation/v1/extensions/ExtendedKeyUsageExtension.cs rename to itext/itext.sign/itext/signatures/validation/extensions/ExtendedKeyUsageExtension.cs index 8d2993fa60..02f1191da6 100644 --- a/itext/itext.sign/itext/signatures/validation/v1/extensions/ExtendedKeyUsageExtension.cs +++ b/itext/itext.sign/itext/signatures/validation/extensions/ExtendedKeyUsageExtension.cs @@ -27,8 +27,9 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle.Asn1; using iText.Commons.Bouncycastle.Cert; using iText.Commons.Bouncycastle.Security; +using iText.Kernel.Crypto; -namespace iText.Signatures.Validation.V1.Extensions { +namespace iText.Signatures.Validation.Extensions { /// Class representing "Extended Key Usage" extension. public class ExtendedKeyUsageExtension : CertificateExtension { public const String ANY_EXTENDED_KEY_USAGE_OID = "2.5.29.37.0"; diff --git a/itext/itext.sign/itext/signatures/validation/v1/extensions/KeyUsage.cs b/itext/itext.sign/itext/signatures/validation/extensions/KeyUsage.cs similarity index 97% rename from itext/itext.sign/itext/signatures/validation/v1/extensions/KeyUsage.cs rename to itext/itext.sign/itext/signatures/validation/extensions/KeyUsage.cs index 27ee6dccb5..9ef88f4941 100644 --- a/itext/itext.sign/itext/signatures/validation/v1/extensions/KeyUsage.cs +++ b/itext/itext.sign/itext/signatures/validation/extensions/KeyUsage.cs @@ -20,7 +20,7 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ -namespace iText.Signatures.Validation.V1.Extensions { +namespace iText.Signatures.Validation.Extensions { /// Enum representing possible "Key Usage" extension values. public enum KeyUsage { /// "Digital Signature" key usage value diff --git a/itext/itext.sign/itext/signatures/validation/v1/extensions/KeyUsageExtension.cs b/itext/itext.sign/itext/signatures/validation/extensions/KeyUsageExtension.cs similarity index 98% rename from itext/itext.sign/itext/signatures/validation/v1/extensions/KeyUsageExtension.cs rename to itext/itext.sign/itext/signatures/validation/extensions/KeyUsageExtension.cs index 87b4e6f03c..b48708254a 100644 --- a/itext/itext.sign/itext/signatures/validation/v1/extensions/KeyUsageExtension.cs +++ b/itext/itext.sign/itext/signatures/validation/extensions/KeyUsageExtension.cs @@ -25,9 +25,9 @@ You should have received a copy of the GNU Affero General Public License using iText.Commons.Bouncycastle; using iText.Commons.Bouncycastle.Cert; using iText.Commons.Utils; -using iText.Signatures; +using iText.Kernel.Crypto; -namespace iText.Signatures.Validation.V1.Extensions { +namespace iText.Signatures.Validation.Extensions { /// Class representing "Key Usage" extenstion. public class KeyUsageExtension : CertificateExtension { private static readonly IBouncyCastleFactory FACTORY = BouncyCastleFactoryCreator.GetFactory(); diff --git a/itext/itext.sign/itext/signatures/validation/v1/report/CertificateReportItem.cs b/itext/itext.sign/itext/signatures/validation/report/CertificateReportItem.cs similarity index 98% rename from itext/itext.sign/itext/signatures/validation/v1/report/CertificateReportItem.cs rename to itext/itext.sign/itext/signatures/validation/report/CertificateReportItem.cs index 455c9c6c8d..95ba65abd5 100644 --- a/itext/itext.sign/itext/signatures/validation/v1/report/CertificateReportItem.cs +++ b/itext/itext.sign/itext/signatures/validation/report/CertificateReportItem.cs @@ -23,7 +23,7 @@ You should have received a copy of the GNU Affero General Public License using System; using iText.Commons.Bouncycastle.Cert; -namespace iText.Signatures.Validation.V1.Report { +namespace iText.Signatures.Validation.Report { /// Report item to be used for single certificate related failure or log message. public class CertificateReportItem : ReportItem { private readonly IX509Certificate certificate; diff --git a/itext/itext.sign/itext/signatures/validation/v1/report/ReportItem.cs b/itext/itext.sign/itext/signatures/validation/report/ReportItem.cs similarity index 96% rename from itext/itext.sign/itext/signatures/validation/v1/report/ReportItem.cs rename to itext/itext.sign/itext/signatures/validation/report/ReportItem.cs index 5f8afe46c1..ec9d167e1d 100644 --- a/itext/itext.sign/itext/signatures/validation/v1/report/ReportItem.cs +++ b/itext/itext.sign/itext/signatures/validation/report/ReportItem.cs @@ -22,7 +22,7 @@ You should have received a copy of the GNU Affero General Public License */ using System; -namespace iText.Signatures.Validation.V1.Report { +namespace iText.Signatures.Validation.Report { /// Report item to be used for single failure or log message. public class ReportItem { private readonly String checkName; @@ -140,8 +140,7 @@ public virtual ReportItem.ReportItemStatus GetStatus() { /// /// instance. /// - public virtual iText.Signatures.Validation.V1.Report.ReportItem SetStatus(ReportItem.ReportItemStatus status - ) { + public virtual iText.Signatures.Validation.Report.ReportItem SetStatus(ReportItem.ReportItemStatus status) { this.status = status; return this; } diff --git a/itext/itext.sign/itext/signatures/validation/v1/report/ValidationReport.cs b/itext/itext.sign/itext/signatures/validation/report/ValidationReport.cs similarity index 96% rename from itext/itext.sign/itext/signatures/validation/v1/report/ValidationReport.cs rename to itext/itext.sign/itext/signatures/validation/report/ValidationReport.cs index 909ce7ed3d..e69dd4c816 100644 --- a/itext/itext.sign/itext/signatures/validation/v1/report/ValidationReport.cs +++ b/itext/itext.sign/itext/signatures/validation/report/ValidationReport.cs @@ -26,7 +26,7 @@ You should have received a copy of the GNU Affero General Public License using System.Text; using iText.Commons.Utils; -namespace iText.Signatures.Validation.V1.Report { +namespace iText.Signatures.Validation.Report { /// Validation report, which contains detailed validation results. public class ValidationReport { private readonly IList reportItems = new List(); @@ -135,7 +135,7 @@ public override String ToString() { /// /// the same updated validation report instance. /// - public virtual iText.Signatures.Validation.V1.Report.ValidationReport Merge(iText.Signatures.Validation.V1.Report.ValidationReport + public virtual iText.Signatures.Validation.Report.ValidationReport Merge(iText.Signatures.Validation.Report.ValidationReport subReport) { foreach (ReportItem item in subReport.GetLogs()) { AddReportItem(item); diff --git a/itext/itext.sign/itext/signatures/validation/v1/extensions/BasicConstraintsExtension.cs b/itext/itext.sign/itext/signatures/validation/v1/extensions/BasicConstraintsExtension.cs deleted file mode 100644 index 3c8a986a0e..0000000000 --- a/itext/itext.sign/itext/signatures/validation/v1/extensions/BasicConstraintsExtension.cs +++ /dev/null @@ -1,113 +0,0 @@ -/* -This file is part of the iText (R) project. -Copyright (c) 1998-2024 Apryse Group NV -Authors: Apryse Software. - -This program is offered under a commercial and under the AGPL license. -For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. - -AGPL licensing: -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . -*/ -using System; -using iText.Bouncycastleconnector; -using iText.Commons.Bouncycastle; -using iText.Commons.Bouncycastle.Cert; -using iText.Signatures; - -namespace iText.Signatures.Validation.V1.Extensions { - /// Class representing "Basic Constraints" certificate extension. - [System.ObsoleteAttribute(@"since 8.0.5. To be removed.")] - public class BasicConstraintsExtension : CertificateExtension { - private static readonly IBouncyCastleFactory FACTORY = BouncyCastleFactoryCreator.GetFactory(); - - private readonly int pathLength; - - /// - /// Create new - /// - /// instance using provided - /// boolean - /// value. - /// - /// - /// - /// boolean - /// value, which represents if this certificate is a "Certificate Authority" - /// - public BasicConstraintsExtension(bool ca) - : base(OID.X509Extensions.BASIC_CONSTRAINTS, FACTORY.CreateBasicConstraints(ca).ToASN1Primitive()) { - if (ca) { - this.pathLength = int.MaxValue; - } - else { - this.pathLength = -1; - } - } - - /// - /// Create new - /// - /// instance using provided - /// int - /// path length. - /// - /// - /// - /// int - /// value, which represents acceptable path length for this certificate as a "CA" - /// - public BasicConstraintsExtension(int pathLength) - : base(OID.X509Extensions.BASIC_CONSTRAINTS, FACTORY.CreateBasicConstraints(pathLength).ToASN1Primitive()) { - this.pathLength = pathLength; - } - - /// Check if this extension is present in the provided certificate. - /// - /// Check if this extension is present in the provided certificate. In case of - /// - /// , - /// check if path length for this extension is less or equal to the path length, specified in the certificate. - /// - /// - /// - /// - /// in which this extension shall be present - /// - /// - /// - /// - /// if this path length is less or equal to a one from the certificate, - /// - /// otherwise - /// - public override bool ExistsInCertificate(IX509Certificate certificate) { - try { - if (CertificateUtil.GetExtensionValue(certificate, OID.X509Extensions.BASIC_CONSTRAINTS) == null) { - return false; - } - } - catch (System.IO.IOException) { - return false; - } - catch (Exception) { - return false; - } - if (pathLength >= 0) { - return certificate.GetBasicConstraints() >= pathLength; - } - return certificate.GetBasicConstraints() < 0; - } - } -} diff --git a/itext/itext.styledxmlparser/Properties/AssemblyInfo.cs b/itext/itext.styledxmlparser/Properties/AssemblyInfo.cs index 4c9192a332..f044158a41 100644 --- a/itext/itext.styledxmlparser/Properties/AssemblyInfo.cs +++ b/itext/itext.styledxmlparser/Properties/AssemblyInfo.cs @@ -21,6 +21,6 @@ [assembly: Guid("8636f290-00df-403e-b841-e4bfd6d9ce7a")] -[assembly: AssemblyVersion("8.0.5.0")] -[assembly: AssemblyFileVersion("8.0.5.0")] -[assembly: AssemblyInformationalVersion("8.0.5")] +[assembly: AssemblyVersion("9.0.0.0")] +[assembly: AssemblyFileVersion("9.0.0.0")] +[assembly: AssemblyInformationalVersion("9.0.0")] diff --git a/itext/itext.styledxmlparser/itext/styledxmlparser/PortUtil.cs b/itext/itext.styledxmlparser/itext/styledxmlparser/PortUtil.cs index 29690b4896..4516ba5e54 100644 --- a/itext/itext.styledxmlparser/itext/styledxmlparser/PortUtil.cs +++ b/itext/itext.styledxmlparser/itext/styledxmlparser/PortUtil.cs @@ -28,7 +28,7 @@ You should have received a copy of the GNU Affero General Public License namespace iText.StyledXmlParser { /// /// This file is a helper class for internal usage only. - /// Be aware that its API and functionality may be changed in future. + /// Be aware that its API and functionality may be changed in the future. /// public class PortUtil { private PortUtil() { diff --git a/itext/itext.svg/Properties/AssemblyInfo.cs b/itext/itext.svg/Properties/AssemblyInfo.cs index 301438a177..7f82f65a9b 100644 --- a/itext/itext.svg/Properties/AssemblyInfo.cs +++ b/itext/itext.svg/Properties/AssemblyInfo.cs @@ -21,6 +21,6 @@ [assembly: Guid("ff6ba09d-3655-466a-8c17-a7bfd3479ca1")] -[assembly: AssemblyVersion("8.0.5.0")] -[assembly: AssemblyFileVersion("8.0.5.0")] -[assembly: AssemblyInformationalVersion("8.0.5")] +[assembly: AssemblyVersion("9.0.0.0")] +[assembly: AssemblyFileVersion("9.0.0.0")] +[assembly: AssemblyInformationalVersion("9.0.0")] diff --git a/itext/itext.svg/itext/svg/renderers/SvgDrawContext.cs b/itext/itext.svg/itext/svg/renderers/SvgDrawContext.cs index 00d4c6531c..e42a2575c2 100644 --- a/itext/itext.svg/itext/svg/renderers/SvgDrawContext.cs +++ b/itext/itext.svg/itext/svg/renderers/SvgDrawContext.cs @@ -57,7 +57,9 @@ public class SvgDrawContext { private SvgCssContext cssContext; - private AffineTransform lastTextTransform = new AffineTransform(); + private AffineTransform lastTextTransform; + + private AffineTransform rootTransform; private float[] textMove = new float[] { 0.0f, 0.0f }; @@ -241,6 +243,25 @@ public virtual void SetLastTextTransform(AffineTransform newTransform) { this.lastTextTransform = newTransform; } + /// Get the current root transformation that was last applied. + /// + /// + /// + /// representing the root transformation. + /// + public virtual AffineTransform GetRootTransform() { + if (rootTransform == null) { + rootTransform = new AffineTransform(); + } + return this.rootTransform; + } + + /// Set the current root transformation. + /// root transformation. + public virtual void SetRootTransform(AffineTransform newTransform) { + this.rootTransform = newTransform; + } + /// Get the stored current text move /// [horizontal text move, vertical text move] public virtual float[] GetTextMove() { diff --git a/itext/itext.svg/itext/svg/renderers/impl/PathSvgNodeRenderer.cs b/itext/itext.svg/itext/svg/renderers/impl/PathSvgNodeRenderer.cs index bfe1c6cf67..a78209e4ce 100644 --- a/itext/itext.svg/itext/svg/renderers/impl/PathSvgNodeRenderer.cs +++ b/itext/itext.svg/itext/svg/renderers/impl/PathSvgNodeRenderer.cs @@ -422,8 +422,8 @@ public virtual void DrawMarker(SvgDrawContext context, MarkerVertexType markerVe } } if (point != null) { - String moveX = SvgCssUtils.ConvertDoubleToString(point.x); - String moveY = SvgCssUtils.ConvertDoubleToString(point.y); + String moveX = SvgCssUtils.ConvertDoubleToString(point.GetX()); + String moveY = SvgCssUtils.ConvertDoubleToString(point.GetY()); MarkerSvgNodeRenderer.DrawMarker(context, moveX, moveY, markerVertexType, this); } } diff --git a/itext/itext.svg/itext/svg/renderers/impl/PolygonSvgNodeRenderer.cs b/itext/itext.svg/itext/svg/renderers/impl/PolygonSvgNodeRenderer.cs index c5bfffef84..15ca40f2ed 100644 --- a/itext/itext.svg/itext/svg/renderers/impl/PolygonSvgNodeRenderer.cs +++ b/itext/itext.svg/itext/svg/renderers/impl/PolygonSvgNodeRenderer.cs @@ -54,8 +54,9 @@ private void ConnectPoints() { } Point start = points[0]; Point end = points[points.Count - 1]; - if (JavaUtil.DoubleCompare(start.x, end.x) != 0 || JavaUtil.DoubleCompare(start.y, end.y) != 0) { - points.Add(new Point(start.x, start.y)); + if (JavaUtil.DoubleCompare(start.GetX(), end.GetX()) != 0 || JavaUtil.DoubleCompare(start.GetY(), end.GetY + ()) != 0) { + points.Add(new Point(start.GetX(), start.GetY())); } } diff --git a/itext/itext.svg/itext/svg/renderers/impl/PolylineSvgNodeRenderer.cs b/itext/itext.svg/itext/svg/renderers/impl/PolylineSvgNodeRenderer.cs index 8956998a97..1b8a6cddde 100644 --- a/itext/itext.svg/itext/svg/renderers/impl/PolylineSvgNodeRenderer.cs +++ b/itext/itext.svg/itext/svg/renderers/impl/PolylineSvgNodeRenderer.cs @@ -143,8 +143,8 @@ public virtual void DrawMarker(SvgDrawContext context, MarkerVertexType markerVe } } if (point != null) { - String moveX = SvgCssUtils.ConvertDoubleToString(CssUtils.ConvertPtsToPx(point.x)); - String moveY = SvgCssUtils.ConvertDoubleToString(CssUtils.ConvertPtsToPx(point.y)); + String moveX = SvgCssUtils.ConvertDoubleToString(CssUtils.ConvertPtsToPx(point.GetX())); + String moveY = SvgCssUtils.ConvertDoubleToString(CssUtils.ConvertPtsToPx(point.GetY())); MarkerSvgNodeRenderer.DrawMarker(context, moveX, moveY, markerVertexType, this); } } diff --git a/itext/itext.svg/itext/svg/renderers/impl/TextSvgBranchRenderer.cs b/itext/itext.svg/itext/svg/renderers/impl/TextSvgBranchRenderer.cs index 8cbaa2635e..6ab80792bd 100644 --- a/itext/itext.svg/itext/svg/renderers/impl/TextSvgBranchRenderer.cs +++ b/itext/itext.svg/itext/svg/renderers/impl/TextSvgBranchRenderer.cs @@ -155,7 +155,7 @@ public virtual TextRectangle GetTextRectangle(SvgDrawContext context, Point base } } basePoint = new Point(x, y); - basePoint.Translate(GetRelativeTranslation()[0], GetRelativeTranslation()[1]); + basePoint.Move(GetRelativeTranslation()[0], GetRelativeTranslation()[1]); Rectangle commonRect = null; foreach (ISvgTextNodeRenderer child in GetChildren()) { if (child != null) { @@ -190,6 +190,7 @@ protected internal override void DoDraw(SvgDrawContext context) { PdfCanvas currentCanvas = context.GetCurrentCanvas(); context.ResetTextMove(); context.SetLastTextTransform(null); + context.SetRootTransform(null); if (this.attributesAndStyles != null) { foreach (ISvgTextNodeRenderer c in children) { currentCanvas.SaveState(); @@ -214,6 +215,10 @@ protected internal override void DoDraw(SvgDrawContext context) { if (c is TextLeafSvgNodeRenderer && !context.GetLastTextTransform().IsIdentity()) { currentCanvas.SetTextMatrix(context.GetLastTextTransform()); } + else { + // If we don't update the matrix, we should set root matrix as the last text matrix + context.SetLastTextTransform(context.GetRootTransform()); + } } // Handle Text-Anchor declarations float textAnchorCorrection = GetTextAnchorAlignmentCorrection(childLength); @@ -246,6 +251,7 @@ internal virtual void PerformRootTransformations(PdfCanvas currentCanvas, SvgDra else { rootTf = new AffineTransform(TEXTFLIP); } + context.SetRootTransform(rootTf); currentCanvas.SetTextMatrix(rootTf); // Apply relative move if (this.ContainsRelativeMove()) { @@ -356,11 +362,12 @@ internal static AffineTransform GetTextTransform(float[][] absolutePositions, Sv AffineTransform tf = new AffineTransform(); // If x is not specified, but y is, we need to correct for preceding text. if (absolutePositions[0] == null && absolutePositions[1] != null) { - absolutePositions[0] = new float[] { context.GetTextMove()[0] }; + absolutePositions[0] = new float[] { context.GetTextMove()[0] + (float)context.GetLastTextTransform().GetTranslateX + () }; } - // If y is not present, we can replace it with a neutral transformation (0.0f) + // If y is not present, we should take the last text y if (absolutePositions[1] == null) { - absolutePositions[1] = new float[] { 0.0f }; + absolutePositions[1] = new float[] { (float)context.GetLastTextTransform().GetTranslateY() }; } tf.Concatenate(TEXTFLIP); tf.Concatenate(AffineTransform.GetTranslateInstance(absolutePositions[0][0], -absolutePositions[1][0])); diff --git a/itext/itext.svg/itext/svg/renderers/path/impl/EllipticalCurveTo.cs b/itext/itext.svg/itext/svg/renderers/path/impl/EllipticalCurveTo.cs index 1473eaa932..43c8d08982 100644 --- a/itext/itext.svg/itext/svg/renderers/path/impl/EllipticalCurveTo.cs +++ b/itext/itext.svg/itext/svg/renderers/path/impl/EllipticalCurveTo.cs @@ -77,7 +77,7 @@ public override void SetCoordinates(String[] inputCoordinates, Point previous) { } public override void Draw(PdfCanvas canvas) { - Point start = new Point(startPoint.x * .75, startPoint.y * .75); + Point start = new Point(startPoint.GetX() * .75, startPoint.GetY() * .75); // pixels to points double rx = Math.Abs(CssDimensionParsingUtils.ParseAbsoluteLength(coordinates[0])); double ry = Math.Abs(CssDimensionParsingUtils.ParseAbsoluteLength(coordinates[1])); @@ -90,7 +90,7 @@ public override void Draw(PdfCanvas canvas) { bool sweep = !CssUtils.CompareFloats((float)CssDimensionParsingUtils.ParseFloat(coordinates[4]), 0); Point end = new Point(CssDimensionParsingUtils.ParseAbsoluteLength(coordinates[5]), CssDimensionParsingUtils .ParseAbsoluteLength(coordinates[6])); - if (CssUtils.CompareFloats(start.x, end.x) && CssUtils.CompareFloats(start.y, end.y)) { + if (CssUtils.CompareFloats(start.GetX(), end.GetX()) && CssUtils.CompareFloats(start.GetY(), end.GetY())) { /* edge case: If the endpoints (x1, y1) and (x2, y2) are identical, * then this is equivalent to omitting the elliptical arc segment entirely. */ @@ -100,7 +100,7 @@ public override void Draw(PdfCanvas canvas) { /* edge case: If rx = 0 or ry = 0 then this arc is treated as a straight line segment (a "lineto") * joining the endpoints. */ - canvas.LineTo(end.x, end.y); + canvas.LineTo(end.GetX(), end.GetY()); } else { /* This is the first step of calculating a rotated elliptical path. @@ -114,13 +114,13 @@ but an incorrect starting angle and/or extent. } else { AffineTransform normalizer = AffineTransform.GetRotateInstance(-rotation); - normalizer.Translate(-start.x, -start.y); + normalizer.Translate(-start.GetX(), -start.GetY()); Point newArcEnd = normalizer.Transform(end, null); - newArcEnd.Translate(start.x, start.y); + newArcEnd.Move(start.GetX(), start.GetY()); arc = EllipticalCurveTo.EllipseArc.GetEllipse(start, newArcEnd, rx, ry, sweep, largeArc); } - Point[][] points = MakePoints(PdfCanvas.BezierArc(arc.ll.x, arc.ll.y, arc.ur.x, arc.ur.y, arc.startAng, arc - .extent)); + Point[][] points = MakePoints(PdfCanvas.BezierArc(arc.ll.GetX(), arc.ll.GetY(), arc.ur.GetX(), arc.ur.GetY + (), arc.startAng, arc.extent)); if (sweep) { points = Rotate(points, rotation, points[0][0]); for (int i = 0; i < points.Length; i++) { @@ -145,7 +145,8 @@ but an incorrect starting angle and/or extent. internal static Point[][] Rotate(Point[][] list, double rotation, Point rotator) { if (!CssUtils.CompareFloats(rotation, 0)) { Point[][] result = new Point[list.Length][]; - AffineTransform transRotTrans = AffineTransform.GetRotateInstance(rotation, rotator.x, rotator.y); + AffineTransform transRotTrans = AffineTransform.GetRotateInstance(rotation, rotator.GetX(), rotator.GetY() + ); for (int i = 0; i < list.Length; i++) { Point[] input = list[i]; Point[] row = new Point[input.Length]; @@ -167,7 +168,7 @@ internal virtual String[] GetCoordinates() { //\endcond private static void DrawCurve(PdfCanvas canvas, Point cp1, Point cp2, Point end) { - canvas.CurveTo(cp1.x, cp1.y, cp2.x, cp2.y, end.x, end.y); + canvas.CurveTo(cp1.GetX(), cp1.GetY(), cp2.GetX(), cp2.GetY(), end.GetX(), end.GetY()); } private Point[][] MakePoints(IList input) { @@ -214,8 +215,8 @@ internal class EllipseArc { //\cond DO_NOT_DOCUMENT internal EllipseArc(Point center, double a, double b, double startAng, double extent) { - ll = new Point(center.x - a, center.y - b); - ur = new Point(center.x + a, center.y + b); + ll = new Point(center.GetX() - a, center.GetY() - b); + ur = new Point(center.GetX() + a, center.GetY() + b); this.startAng = startAng; this.extent = extent; } @@ -224,8 +225,8 @@ internal EllipseArc(Point center, double a, double b, double startAng, double ex //\cond DO_NOT_DOCUMENT internal static EllipticalCurveTo.EllipseArc GetEllipse(Point start, Point end, double a, double b, bool sweep , bool largeArc) { - double r1 = (start.x - end.x) / (-2.0 * a); - double r2 = (start.y - end.y) / (2.0 * b); + double r1 = (start.GetX() - end.GetX()) / (-2.0 * a); + double r2 = (start.GetY() - end.GetY()) / (2.0 * b); double factor = Math.Sqrt(r1 * r1 + r2 * r2); if (factor > 1) { /* If rx, ry and φ are such that there is no solution (basically, the ellipse is not big enough @@ -261,10 +262,11 @@ internal static EllipticalCurveTo.EllipseArc GetEllipse(Point start, Point end, //\cond DO_NOT_DOCUMENT internal static EllipticalCurveTo.EllipseArc CalculatePossibleMiddle(Point start, Point end, double a, double b, double startToCenterAngle, bool sweep, bool largeArc) { - double x0 = start.x - a * Math.Cos(startToCenterAngle); - double y0 = start.y - b * Math.Sin(startToCenterAngle); + double x0 = start.GetX() - a * Math.Cos(startToCenterAngle); + double y0 = start.GetY() - b * Math.Sin(startToCenterAngle); Point center = new Point(x0, y0); - double check = Math.Pow(((end.x - center.x) / a), 2) + Math.Pow(((end.y - center.y) / b), 2); + double check = Math.Pow(((end.GetX() - center.GetX()) / a), 2) + Math.Pow(((end.GetY() - center.GetY()) / + b), 2); /* If center is an actual candidate for a middle point, then the value of check will be very close to 1.0. * Otherwise it is always larger than 1. * Due to floating point math, we need to introduce an epsilon value. @@ -334,9 +336,10 @@ internal static EllipticalCurveTo.EllipseArc CalculatePossibleMiddle(Point start //\cond DO_NOT_DOCUMENT internal static double CalculateAngle(Point pt, Point center, double a, double b) { - double result = Math.Pow(((pt.x - center.x) / a), 2.0) + Math.Pow(((pt.y - center.y) / b), 2.0); - double cos = (pt.x - center.x) / a; - double sin = (pt.y - center.y) / b; + double result = Math.Pow(((pt.GetX() - center.GetX()) / a), 2.0) + Math.Pow(((pt.GetY() - center.GetY()) / + b), 2.0); + double cos = (pt.GetX() - center.GetX()) / a; + double sin = (pt.GetY() - center.GetY()) / b; // catch very small floating point errors and keep cos between [-1, 1], so we can calculate the arc cosine cos = Math.Max(Math.Min(cos, 1.0), -1.0); if ((cos >= 0 && sin >= 0) || (cos < 0 && sin >= 0)) { diff --git a/itext/itext.svg/itext/svg/renderers/path/impl/LineTo.cs b/itext/itext.svg/itext/svg/renderers/path/impl/LineTo.cs index 213f9b9b24..3357487f43 100644 --- a/itext/itext.svg/itext/svg/renderers/path/impl/LineTo.cs +++ b/itext/itext.svg/itext/svg/renderers/path/impl/LineTo.cs @@ -55,8 +55,8 @@ public override void SetCoordinates(String[] inputCoordinates, Point startPoint) } this.coordinates = new String[] { inputCoordinates[0], inputCoordinates[1] }; if (IsRelative()) { - this.coordinates = copier.MakeCoordinatesAbsolute(coordinates, new double[] { startPoint.x, startPoint.y } - ); + this.coordinates = copier.MakeCoordinatesAbsolute(coordinates, new double[] { startPoint.GetX(), startPoint + .GetY() }); } } } diff --git a/itext/itext.svg/itext/svg/renderers/path/impl/MoveTo.cs b/itext/itext.svg/itext/svg/renderers/path/impl/MoveTo.cs index 132dff7a8d..df96a5f614 100644 --- a/itext/itext.svg/itext/svg/renderers/path/impl/MoveTo.cs +++ b/itext/itext.svg/itext/svg/renderers/path/impl/MoveTo.cs @@ -55,8 +55,8 @@ public override void SetCoordinates(String[] inputCoordinates, Point startPoint) } this.coordinates = new String[] { inputCoordinates[0], inputCoordinates[1] }; if (IsRelative()) { - this.coordinates = copier.MakeCoordinatesAbsolute(coordinates, new double[] { startPoint.x, startPoint.y } - ); + this.coordinates = copier.MakeCoordinatesAbsolute(coordinates, new double[] { startPoint.GetX(), startPoint + .GetY() }); } } } diff --git a/itext/itext.svg/itext/svg/utils/TransformUtils.cs b/itext/itext.svg/itext/svg/utils/TransformUtils.cs index c5fba3eb02..db57f76f43 100644 --- a/itext/itext.svg/itext/svg/utils/TransformUtils.cs +++ b/itext/itext.svg/itext/svg/utils/TransformUtils.cs @@ -148,6 +148,9 @@ private static IList SplitString(String transform) { while (tokenizer.HasMoreTokens()) { String trim = tokenizer.NextToken().Trim(); if (trim != null && !String.IsNullOrEmpty(trim)) { + if (trim.StartsWith(",")) { + trim = trim.Substring(1).Trim(); + } list.Add(trim + ")"); } } diff --git a/port-hash b/port-hash index b6721ff694..072c0c03e3 100644 --- a/port-hash +++ b/port-hash @@ -1 +1 @@ -8ea4324aae69de42d28a0b90ea73fbdad5d7a267 +a157a78b6d83a0415dccc3a3b8409c6cfbc11889