Agregar archivos de proyecto.

This commit is contained in:
2026-05-27 17:09:59 +02:00
parent 73b30b7de7
commit 03813aff5a
9144 changed files with 4026729 additions and 0 deletions

View File

@@ -0,0 +1,24 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("TSpdf.Kernel.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("TSpdf")]
[assembly: AssemblyProduct("TSpdf")]
[assembly: AssemblyCopyright("Copyright (c) 1987-2023 TSpdf")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("02e54061-eb72-409d-b2c0-307ce66b57e9")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0.0")]
#if !NETSTANDARD2_0
[assembly: NUnit.Framework.Timeout(300000)]
#endif

View File

@@ -0,0 +1,60 @@
<Project Sdk="Microsoft.NET.Sdk" ToolsVersion="15.0">
<PropertyGroup Label="Globals">
<SccProjectName>SAK</SccProjectName>
<SccProvider>SAK</SccProvider>
<SccAuxPath>SAK</SccAuxPath>
<SccLocalPath>SAK</SccLocalPath>
</PropertyGroup>
<PropertyGroup Label="Configuration">
<SignAssembly>True</SignAssembly>
<DelaySign>False</DelaySign>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<TargetFrameworks>netcoreapp3.1;net461;net48</TargetFrameworks>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetFramework)' == 'net461' ">
<OutputType>library</OutputType>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetFramework)' == 'netcoreapp3.1' ">
<OutputType>Library</OutputType>
<DefineConstants>NETSTANDARD2_0</DefineConstants>
</PropertyGroup>
<PropertyGroup>
<AssemblyOriginatorKeyFile>TSpdf.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<PropertyGroup>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<ApplicationIcon />
<OutputTypeEx>library</OutputTypeEx>
<StartupObject />
<RootNamespace />
<AssemblyName>TSpdf.kernel.tests</AssemblyName>
</PropertyGroup>
<PropertyGroup>
<NoWarn>1701;1702;1591;1570;1572;1573;1574;1580;1584;1658</NoWarn>
</PropertyGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net461' ">
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="TeamCity.VSTest.TestAdapter" Version="1.0.0" />
<PackageReference Include="NUnit" Version="3.7.1" />
<PackageReference Include="NUnit3TestAdapter" Version="3.10.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\TSpdf\TSpdf.io\TSpdf.io.csproj" />
<ProjectReference Include="..\..\TSpdf\TSpdf.kernel\TSpdf.kernel.csproj" />
<ProjectReference Include="..\..\TSpdf\TSpdf.pdftest\TSpdf.pdftest.csproj" />
<ProjectReference Include="..\..\TSpdf\TSpdf.font-asian\TSpdf.font-asian.csproj" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'netcoreapp3.1'">
<PackageReference Include="Microsoft.NET.Test.Sdk">
<Version>15.0.0</Version>
</PackageReference>
<PackageReference Include="System.Runtime.InteropServices.RuntimeInformation">
<Version>4.3.0</Version>
</PackageReference>
</ItemGroup>
</Project>

Binary file not shown.

View File

@@ -0,0 +1,39 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.Kernel.Exceptions;
using TSpdf.Test;
namespace TSpdf.Kernel {
[NUnit.Framework.Category("UnitTest")]
public class PdfExceptionTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void WhenCreatedPdfExceptionWrapsCauseWithUnknownExceptionMessageTest() {
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => {
throw new PdfException(new Exception("TSpdf"));
}
);
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.UNKNOWN_PDF_EXCEPTION, e.Message);
}
}
}

View File

@@ -0,0 +1,76 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using TSpdf.Commons.Actions;
using TSpdf.Commons.Actions.Processors;
using TSpdf.Commons.Actions.Sequence;
namespace TSpdf.Kernel.Actions {
/// <summary>This class is used for testing purposes to have an access to ProductEventHandler.</summary>
/// <remarks>
/// This class is used for testing purposes to have an access to ProductEventHandler. Note
/// that work with it may access further tests because the state of ProductEventHandler is shared
/// across application. It is strongly recommended to call
/// <see cref="Close()"/>
/// method to return ProductEventHandler to initial state.
/// </remarks>
public class ProductEventHandlerAccess : AbstractTSpdfConfigurationEvent, IDisposable {
private readonly ICollection<String> registeredProducts = new HashSet<String>();
public virtual TSpdfProductEventProcessor PublicAddProcessor(TSpdfProductEventProcessor processor) {
registeredProducts.Add(processor.GetProductName());
return base.AddProcessor(processor);
}
public virtual TSpdfProductEventProcessor PublicRemoveProcessor(String productName) {
return base.RemoveProcessor(productName);
}
public virtual IDictionary<String, TSpdfProductEventProcessor> PublicGetProcessors() {
return base.GetProcessors();
}
public virtual IList<AbstractProductProcessTSpdfEvent> PublicGetEvents(SequenceId id) {
return base.GetEvents(id);
}
public virtual void PublicAddEvent(SequenceId id, AbstractProductProcessTSpdfEvent @event) {
base.AddEvent(id, @event);
}
protected override void DoAction() {
throw new InvalidOperationException();
}
public virtual void Close() {
foreach (String product in registeredProducts) {
RemoveProcessor(product);
}
}
void System.IDisposable.Dispose() {
Close();
}
}
}

View File

@@ -0,0 +1,53 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.Commons.Actions;
using TSpdf.Kernel.Actions.Ecosystem;
using TSpdf.Kernel.Pdf;
using TSpdf.Test;
namespace TSpdf.Kernel.Actions {
[NUnit.Framework.Category("UnitTest")]
public class ProductEventHandlerTest : ExtendedTSpdfTest {
private static readonly String SOURCE_FOLDER = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/actions/";
[NUnit.Framework.Test]
public virtual void DocumentIdBasedEventTest() {
ProductEventHandlerAccess handler = new ProductEventHandlerAccess();
using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "hello.pdf"))) {
int alreadyRegisteredEvents = handler.PublicGetEvents(document.GetDocumentIdWrapper()).Count;
EventManager.GetInstance().OnEvent(new TSpdfTestEvent(document.GetDocumentIdWrapper(), null, "test-event",
ProductNameConstant.TSpdf_CORE));
NUnit.Framework.Assert.AreEqual(alreadyRegisteredEvents + 1, handler.PublicGetEvents(document.GetDocumentIdWrapper
()).Count);
AbstractProductProcessTSpdfEvent @event = handler.PublicGetEvents(document.GetDocumentIdWrapper())[alreadyRegisteredEvents
];
NUnit.Framework.Assert.AreEqual(document.GetDocumentIdWrapper(), @event.GetSequenceId());
NUnit.Framework.Assert.AreEqual("test-event", @event.GetEventType());
NUnit.Framework.Assert.AreEqual(ProductNameConstant.TSpdf_CORE, @event.GetProductName());
NUnit.Framework.Assert.IsNotNull(@event.GetProductData());
}
}
}
}

View File

@@ -0,0 +1,55 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.Commons.Actions;
using TSpdf.Commons.Actions.Confirmations;
using TSpdf.Commons.Actions.Contexts;
using TSpdf.Commons.Actions.Data;
using TSpdf.Commons.Actions.Sequence;
namespace TSpdf.Kernel.Actions.Ecosystem {
public class TSpdfTestEvent : AbstractProductProcessTSpdfEvent {
private readonly String eventType;
public TSpdfTestEvent(SequenceId sequenceId, IMetaInfo metaInfo, String eventType, String productName)
: base(sequenceId, new ProductData("", productName, "", 2000, 2100), metaInfo, EventConfirmationType.ON_CLOSE
) {
this.eventType = eventType;
}
public TSpdfTestEvent(SequenceId sequenceId, ProductData productData, IMetaInfo metaInfo, String eventType
, EventConfirmationType confirmationType)
: base(sequenceId, productData, metaInfo, confirmationType) {
this.eventType = eventType;
}
public TSpdfTestEvent(SequenceId sequenceId, ProductData productData, IMetaInfo metaInfo, String eventType
)
: this(sequenceId, productData, metaInfo, eventType, EventConfirmationType.ON_CLOSE) {
}
public override String GetEventType() {
return eventType;
}
}
}

View File

@@ -0,0 +1,38 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using Microsoft.Extensions.Logging;
using TSpdf.Commons;
using TSpdf.Commons.Actions;
namespace TSpdf.Kernel.Actions.Ecosystem {
public class TestConfigurationEvent : AbstractTSpdfConfigurationEvent {
public const String MESSAGE = "Test configuration event was processed";
private static readonly ILogger LOGGER = TSpdfLogManager.GetLogger(typeof(TestConfigurationEvent));
protected override void DoAction() {
LOGGER.LogWarning(MESSAGE);
}
}
}

View File

@@ -0,0 +1,38 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.Commons.Actions.Contexts;
namespace TSpdf.Kernel.Actions.Ecosystem {
public class TestMetaInfo : IMetaInfo {
private readonly String metaData;
public TestMetaInfo(String metaData) {
this.metaData = metaData;
}
public virtual String GetMetaData() {
return metaData;
}
}
}

View File

@@ -0,0 +1,167 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using System.IO;
using TSpdf.Commons.Actions;
using TSpdf.Commons.Actions.Confirmations;
using TSpdf.Commons.Actions.Data;
using TSpdf.Commons.Actions.Processors;
using TSpdf.Commons.Actions.Sequence;
using TSpdf.IO.Source;
using TSpdf.Kernel.Actions;
using TSpdf.Kernel.Actions.Data;
using TSpdf.Kernel.Actions.Ecosystem;
using TSpdf.Kernel.Logs;
using TSpdf.Kernel.Pdf;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.Kernel.Actions.Events {
[NUnit.Framework.Category("UnitTest")]
public class FlushPdfDocumentEventTest : ExtendedTSpdfTest {
private static readonly String SOURCE_FOLDER = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/actions/";
[NUnit.Framework.Test]
public virtual void OnCloseReportingTest() {
using (ProductEventHandlerAccess access = new ProductEventHandlerAccess()) {
using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "hello.pdf"))) {
TSpdfTestEvent @event = new TSpdfTestEvent(document.GetDocumentIdWrapper(), TSpdfCoreProductData.GetInstance
(), null, "test-event", EventConfirmationType.ON_CLOSE);
int initialLength = access.PublicGetEvents(document.GetDocumentIdWrapper()).Count;
EventManager.GetInstance().OnEvent(@event);
new FlushPdfDocumentEvent(document).DoAction();
AbstractProductProcessTSpdfEvent reportedEvent = access.PublicGetEvents(document.GetDocumentIdWrapper())[initialLength
];
NUnit.Framework.Assert.IsTrue(reportedEvent is ConfirmedEventWrapper);
ConfirmedEventWrapper wrappedEvent = (ConfirmedEventWrapper)reportedEvent;
NUnit.Framework.Assert.AreEqual(@event, wrappedEvent.GetEvent());
}
}
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.UNCONFIRMED_EVENT)]
public virtual void OnDemandReportingIgnoredTest() {
using (ProductEventHandlerAccess access = new ProductEventHandlerAccess()) {
using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "hello.pdf"))) {
TSpdfTestEvent @event = new TSpdfTestEvent(document.GetDocumentIdWrapper(), TSpdfCoreProductData.GetInstance
(), null, "test-event", EventConfirmationType.ON_DEMAND);
int initialLength = access.PublicGetEvents(document.GetDocumentIdWrapper()).Count;
EventManager.GetInstance().OnEvent(@event);
new FlushPdfDocumentEvent(document).DoAction();
AbstractProductProcessTSpdfEvent reportedEvent = access.PublicGetEvents(document.GetDocumentIdWrapper())[initialLength
];
NUnit.Framework.Assert.IsFalse(reportedEvent is ConfirmedEventWrapper);
}
}
}
[NUnit.Framework.Test]
public virtual void OnDemandReportingConfirmedTest() {
using (ProductEventHandlerAccess access = new ProductEventHandlerAccess()) {
using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "hello.pdf"))) {
TSpdfTestEvent @event = new TSpdfTestEvent(document.GetDocumentIdWrapper(), TSpdfCoreProductData.GetInstance
(), null, "test-event", EventConfirmationType.ON_DEMAND);
int initialLength = access.PublicGetEvents(document.GetDocumentIdWrapper()).Count;
EventManager.GetInstance().OnEvent(@event);
AbstractProductProcessTSpdfEvent reportedEvent = access.PublicGetEvents(document.GetDocumentIdWrapper())[initialLength
];
NUnit.Framework.Assert.IsFalse(reportedEvent is ConfirmedEventWrapper);
NUnit.Framework.Assert.AreEqual(@event, reportedEvent);
EventManager.GetInstance().OnEvent(new ConfirmEvent(document.GetDocumentIdWrapper(), @event));
new FlushPdfDocumentEvent(document).DoAction();
AbstractProductProcessTSpdfEvent confirmedEvent = access.PublicGetEvents(document.GetDocumentIdWrapper())[
initialLength];
NUnit.Framework.Assert.IsTrue(confirmedEvent is ConfirmedEventWrapper);
ConfirmedEventWrapper wrappedEvent = (ConfirmedEventWrapper)confirmedEvent;
NUnit.Framework.Assert.AreEqual(@event, wrappedEvent.GetEvent());
}
}
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.UNKNOWN_PRODUCT_INVOLVED)]
public virtual void UnknownProductTest() {
using (ProductEventHandlerAccess access = new ProductEventHandlerAccess()) {
using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "hello.pdf"))) {
access.PublicAddEvent(document.GetDocumentIdWrapper(), GetEvent("unknown product", document.GetDocumentIdWrapper
()));
NUnit.Framework.Assert.DoesNotThrow(() => new FlushPdfDocumentEvent(document).DoAction());
}
}
}
[NUnit.Framework.Test]
public virtual void DoActionNullDocumentTest() {
FlushPdfDocumentEvent closeEvent = new FlushPdfDocumentEvent(null);
NUnit.Framework.Assert.DoesNotThrow(() => closeEvent.DoAction());
}
[NUnit.Framework.Test]
public virtual void FlushEventAfterEachEventTest() {
String resourceInit = SOURCE_FOLDER + "hello.pdf";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
using (PdfDocument pdf = new PdfDocument(new PdfReader(resourceInit), new PdfWriter(baos))) {
pdf.AddNewPage();
EventManager.GetInstance().OnEvent(new FlushPdfDocumentEvent(pdf));
}
using (PdfDocument pdf_1 = new PdfDocument(new PdfReader(new MemoryStream(baos.ToArray())))) {
String producerLine = pdf_1.GetDocumentInfo().GetProducer();
String modifiedByTSpdf = "modified using TSpdf\u00ae Core";
NUnit.Framework.Assert.AreNotEqual(producerLine.IndexOf(modifiedByTSpdf, StringComparison.Ordinal), producerLine
.LastIndexOf(modifiedByTSpdf));
}
}
private class TestProductEventProcessor : TSpdfProductEventProcessor {
private readonly String processorId;
public TestProductEventProcessor(String processorId) {
this.processorId = processorId;
}
public virtual void OnEvent(AbstractProductProcessTSpdfEvent @event) {
}
// do nothing here
public virtual String GetProductName() {
return processorId;
}
public virtual String GetUsageType() {
return "AGPL Version";
}
public virtual String GetProducer() {
return "TSpdf";
}
}
private static ConfirmedEventWrapper GetEvent(String productName, SequenceId sequenceId) {
ProductData productData = new ProductData(productName, productName, "2.0", 1999, 2020);
return new ConfirmedEventWrapper(new TSpdfTestEvent(sequenceId, productData, null, "testing"), "AGPL Version"
, "TSpdf");
}
}
}

View File

@@ -0,0 +1,147 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using TSpdf.Commons.Actions;
using TSpdf.Commons.Actions.Confirmations;
using TSpdf.Commons.Actions.Sequence;
using TSpdf.Kernel.Actions;
using TSpdf.Kernel.Actions.Ecosystem;
using TSpdf.Kernel.Pdf;
using TSpdf.Test;
namespace TSpdf.Kernel.Actions.Events {
[NUnit.Framework.Category("UnitTest")]
public class LinkDocumentIdEventTest : ExtendedTSpdfTest {
private static readonly String SOURCE_FOLDER = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/actions/";
[NUnit.Framework.Test]
public virtual void DoActionLinkModifiedDocumentBySequenceIdTest() {
using (ProductEventHandlerAccess access = new ProductEventHandlerAccess()) {
using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "hello.pdf"))) {
SequenceId sequenceId = new SequenceId();
access.PublicAddEvent(sequenceId, WrapEvent(new TSpdfTestEvent(sequenceId, null, "sequenceId-testing", "test-product-0"
)));
access.PublicAddEvent(sequenceId, WrapEvent(new TSpdfTestEvent(sequenceId, null, "sequenceId-testing", "test-product-1"
)));
access.PublicAddEvent(sequenceId, WrapEvent(new TSpdfTestEvent(sequenceId, null, "sequenceId-testing", "test-product-2"
)));
access.PublicAddEvent(document.GetDocumentIdWrapper(), WrapEvent(new TSpdfTestEvent(document.GetDocumentIdWrapper
(), null, "document-testing", "test-product-3")));
access.PublicAddEvent(document.GetDocumentIdWrapper(), WrapEvent(new TSpdfTestEvent(document.GetDocumentIdWrapper
(), null, "document-testing", "test-product-4")));
int initialSequenceEventsNumber = access.PublicGetEvents(sequenceId).Count;
int initialDocumentEventsNumber = access.PublicGetEvents(document.GetDocumentIdWrapper()).Count;
new LinkDocumentIdEvent(document, sequenceId).DoAction();
NUnit.Framework.Assert.AreEqual(initialSequenceEventsNumber, access.PublicGetEvents(sequenceId).Count);
IList<AbstractProductProcessTSpdfEvent> actualDocumentEvents = access.PublicGetEvents(document.GetDocumentIdWrapper
());
NUnit.Framework.Assert.AreEqual(initialDocumentEventsNumber + 3, actualDocumentEvents.Count);
for (int i = initialDocumentEventsNumber; i < initialDocumentEventsNumber + 3; i++) {
AbstractProductProcessTSpdfEvent sequenceEvent = actualDocumentEvents[i];
NUnit.Framework.Assert.AreEqual("sequenceId-testing", sequenceEvent.GetEventType());
NUnit.Framework.Assert.AreEqual("test-product-" + (i - initialDocumentEventsNumber), sequenceEvent.GetProductName
());
NUnit.Framework.Assert.AreEqual(sequenceId, sequenceEvent.GetSequenceId());
}
}
}
}
[NUnit.Framework.Test]
public virtual void DoActionLinkModifiedDocumentByIdentifiableElemTest() {
using (ProductEventHandlerAccess access = new ProductEventHandlerAccess()) {
using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "hello.pdf"))) {
SequenceId sequenceId = new SequenceId();
access.PublicAddEvent(sequenceId, WrapEvent(new TSpdfTestEvent(sequenceId, null, "sequenceId-testing", "test-product-0"
)));
access.PublicAddEvent(sequenceId, WrapEvent(new TSpdfTestEvent(sequenceId, null, "sequenceId-testing", "test-product-1"
)));
access.PublicAddEvent(sequenceId, WrapEvent(new TSpdfTestEvent(sequenceId, null, "sequenceId-testing", "test-product-2"
)));
access.PublicAddEvent(document.GetDocumentIdWrapper(), WrapEvent(new TSpdfTestEvent(document.GetDocumentIdWrapper
(), null, "document-testing", "test-product-3")));
access.PublicAddEvent(document.GetDocumentIdWrapper(), WrapEvent(new TSpdfTestEvent(document.GetDocumentIdWrapper
(), null, "document-testing", "test-product-4")));
int initialSequenceEventsNumber = access.PublicGetEvents(sequenceId).Count;
int initialDocumentEventsNumber = access.PublicGetEvents(document.GetDocumentIdWrapper()).Count;
LinkDocumentIdEventTest.IdentifiableElement identifiableElement = new LinkDocumentIdEventTest.IdentifiableElement
();
SequenceIdManager.SetSequenceId(identifiableElement, sequenceId);
new LinkDocumentIdEvent(document, identifiableElement).DoAction();
NUnit.Framework.Assert.AreEqual(initialSequenceEventsNumber, access.PublicGetEvents(sequenceId).Count);
IList<AbstractProductProcessTSpdfEvent> actualDocumentEvents = access.PublicGetEvents(document.GetDocumentIdWrapper
());
NUnit.Framework.Assert.AreEqual(initialDocumentEventsNumber + 3, actualDocumentEvents.Count);
for (int i = initialDocumentEventsNumber; i < initialDocumentEventsNumber + 3; i++) {
AbstractProductProcessTSpdfEvent sequenceEvent = actualDocumentEvents[i];
NUnit.Framework.Assert.AreEqual("sequenceId-testing", sequenceEvent.GetEventType());
NUnit.Framework.Assert.AreEqual("test-product-" + (i - initialDocumentEventsNumber), sequenceEvent.GetProductName
());
NUnit.Framework.Assert.AreEqual(sequenceId, sequenceEvent.GetSequenceId());
}
}
}
}
[NUnit.Framework.Test]
public virtual void LinkSimilarEventsButDifferentInstanceTest() {
using (ProductEventHandlerAccess access = new ProductEventHandlerAccess()) {
using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "hello.pdf"))) {
SequenceId sequenceId = new SequenceId();
access.PublicAddEvent(sequenceId, new TSpdfTestEvent(sequenceId, null, "sequenceId-testing", "test-product-1"
));
access.PublicAddEvent(document.GetDocumentIdWrapper(), new TSpdfTestEvent(sequenceId, null, "sequenceId-testing"
, "test-product-1"));
new LinkDocumentIdEvent(document, sequenceId).DoAction();
// Check that first event will be linked to document but it was the
// similar to stored second event, but they have different instance
NUnit.Framework.Assert.AreEqual(3, access.PublicGetEvents(document.GetDocumentIdWrapper()).Count);
}
}
}
[NUnit.Framework.Test]
public virtual void NullValuesAreAcceptableTest() {
NUnit.Framework.Assert.DoesNotThrow(() => new LinkDocumentIdEvent(null, (SequenceId)null));
NUnit.Framework.Assert.DoesNotThrow(() => new LinkDocumentIdEvent(null, (AbstractIdentifiableElement)null)
);
NUnit.Framework.Assert.DoesNotThrow(() => new LinkDocumentIdEvent(null, new SequenceId()));
NUnit.Framework.Assert.DoesNotThrow(() => new LinkDocumentIdEvent(null, new LinkDocumentIdEventTest.IdentifiableElement
()));
using (PdfDocument document = new PdfDocument(new PdfReader(SOURCE_FOLDER + "hello.pdf"))) {
NUnit.Framework.Assert.DoesNotThrow(() => new LinkDocumentIdEvent(document, (SequenceId)null));
NUnit.Framework.Assert.DoesNotThrow(() => new LinkDocumentIdEvent(document, (AbstractIdentifiableElement)null
));
}
}
private static ConfirmedEventWrapper WrapEvent(AbstractProductProcessTSpdfEvent @event) {
return new ConfirmedEventWrapper(@event, "AGPL Version", "TSpdf");
}
private class IdentifiableElement : AbstractIdentifiableElement {
}
}
}

View File

@@ -0,0 +1,74 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using TSpdf.Commons.Actions;
using TSpdf.Commons.Actions.Confirmations;
using TSpdf.Commons.Actions.Sequence;
using TSpdf.Kernel.Actions.Data;
using TSpdf.Kernel.Actions.Ecosystem;
using TSpdf.Test;
namespace TSpdf.Kernel.Actions.Events {
[NUnit.Framework.Category("UnitTest")]
public class TSpdfCoreProductEventTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void OpenDocumentEventTest() {
SequenceId sequenceId = new SequenceId();
TSpdfCoreProductEvent @event = TSpdfCoreProductEvent.CreateProcessPdfEvent(sequenceId, new TestMetaInfo("meta data"
), EventConfirmationType.ON_CLOSE);
NUnit.Framework.Assert.AreEqual(TSpdfCoreProductEvent.PROCESS_PDF, @event.GetEventType());
NUnit.Framework.Assert.AreEqual(ProductNameConstant.TSpdf_CORE, @event.GetProductName());
NUnit.Framework.Assert.AreEqual(EventConfirmationType.ON_CLOSE, @event.GetConfirmationType());
NUnit.Framework.Assert.AreEqual(sequenceId, @event.GetSequenceId());
NUnit.Framework.Assert.AreEqual(TSpdfCoreProductData.GetInstance().GetPublicProductName(), @event.GetProductData
().GetPublicProductName());
NUnit.Framework.Assert.AreEqual(TSpdfCoreProductData.GetInstance().GetProductName(), @event.GetProductData
().GetProductName());
NUnit.Framework.Assert.AreEqual(TSpdfCoreProductData.GetInstance().GetVersion(), @event.GetProductData().GetVersion
());
NUnit.Framework.Assert.AreEqual(TSpdfCoreProductData.GetInstance().GetSinceCopyrightYear(), @event.GetProductData
().GetSinceCopyrightYear());
NUnit.Framework.Assert.AreEqual(TSpdfCoreProductData.GetInstance().GetToCopyrightYear(), @event.GetProductData
().GetToCopyrightYear());
}
}
}

View File

@@ -0,0 +1,360 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using TSpdf.Kernel.Exceptions;
using TSpdf.Kernel.Pdf;
using TSpdf.Kernel.Pdf.Colorspace;
using TSpdf.Test;
namespace TSpdf.Kernel.Colors {
[NUnit.Framework.Category("UnitTest")]
public class ColorTest : ExtendedTSpdfTest {
private const float EPS = 1e-4f;
[NUnit.Framework.Test]
public virtual void ConvertCmykToRgbTest() {
DeviceCmyk cmyk = new DeviceCmyk(0, 0, 0, 0);
DeviceRgb rgb = new DeviceRgb(255, 255, 255);
TSpdf.Test.TestUtil.AreEqual(rgb.colorValue, Color.ConvertCmykToRgb(cmyk).colorValue, EPS);
}
[NUnit.Framework.Test]
public virtual void ConvertRgbToCmykTest() {
DeviceCmyk cmyk = new DeviceCmyk(0, 0, 0, 0);
DeviceRgb rgb = new DeviceRgb(255, 255, 255);
TSpdf.Test.TestUtil.AreEqual(cmyk.colorValue, Color.ConvertRgbToCmyk(rgb).colorValue, EPS);
}
[NUnit.Framework.Test]
public virtual void SetColorValueIncorrectComponentsNumberTest() {
float[] colorValues = new float[] { 0.0f, 0.5f, 0.1f };
Color color = Color.MakeColor(PdfColorSpace.MakeColorSpace(PdfName.DeviceRGB), colorValues);
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => color.SetColorValue(new float[] { 0.1f
, 0.2f }));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.INCORRECT_NUMBER_OF_COMPONENTS, e.Message);
}
[NUnit.Framework.Test]
public virtual void EqualsAndHashCodeTest() {
float[] colorValues = new float[] { 0.0f, 0.5f, 0.1f };
Color color1 = Color.MakeColor(PdfColorSpace.MakeColorSpace(PdfName.DeviceRGB), colorValues);
Color color2 = Color.MakeColor(PdfColorSpace.MakeColorSpace(PdfName.DeviceRGB), colorValues);
bool result = color1.Equals(color2);
NUnit.Framework.Assert.IsTrue(result);
NUnit.Framework.Assert.AreEqual(color1.GetHashCode(), color2.GetHashCode());
}
[NUnit.Framework.Test]
public virtual void EqualsAndHashCodeNullColorSpacesTest() {
float[] colorValues = new float[] { 0.0f, 0.5f, 0.1f };
Color color1 = new Color(null, colorValues);
Color color2 = new Color(null, colorValues);
bool result = color1.Equals(color2);
NUnit.Framework.Assert.IsTrue(result);
NUnit.Framework.Assert.AreEqual(color1.GetHashCode(), color2.GetHashCode());
}
[NUnit.Framework.Test]
public virtual void EqualsAndHashCodeNullColorValuesTest() {
Color color1 = new Color(PdfColorSpace.MakeColorSpace(PdfName.DeviceRGB), null);
Color color2 = new Color(PdfColorSpace.MakeColorSpace(PdfName.DeviceRGB), null);
bool result = color1.Equals(color2);
NUnit.Framework.Assert.IsTrue(result);
NUnit.Framework.Assert.AreEqual(color1.GetHashCode(), color2.GetHashCode());
}
[NUnit.Framework.Test]
public virtual void NotEqualsAndHashCodeDifferentColorSpacesTest() {
float[] colorValues = new float[] { 0.0f, 0.5f, 0.1f };
Color color1 = Color.MakeColor(PdfColorSpace.MakeColorSpace(PdfName.DeviceRGB), colorValues);
Color color2 = Color.MakeColor(PdfColorSpace.MakeColorSpace(PdfName.DeviceGray), colorValues);
bool result = color1.Equals(color2);
NUnit.Framework.Assert.IsFalse(result);
NUnit.Framework.Assert.AreNotEqual(color1.GetHashCode(), color2.GetHashCode());
}
[NUnit.Framework.Test]
public virtual void NotEqualsNullObjectTest() {
float[] colorValues = new float[] { 0.0f, 0.5f, 0.1f };
Color color1 = Color.MakeColor(PdfColorSpace.MakeColorSpace(PdfName.DeviceRGB), colorValues);
bool result = color1.Equals(null);
NUnit.Framework.Assert.IsFalse(result);
}
[NUnit.Framework.Test]
public virtual void NotEqualsDifferentClassesTest() {
float[] colorValues = new float[] { 0.0f, 0.5f, 0.1f };
Color color1 = Color.MakeColor(PdfColorSpace.MakeColorSpace(PdfName.DeviceRGB), colorValues);
DeviceCmyk cmyk = new DeviceCmyk(0, 0, 0, 0);
bool result = color1.Equals(cmyk);
NUnit.Framework.Assert.IsFalse(result);
}
[NUnit.Framework.Test]
public virtual void NullColorSpaceTest() {
float[] colorValues = new float[] { 0.0f, 0.5f, 0.1f };
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => Color.MakeColor(null, colorValues));
NUnit.Framework.Assert.AreEqual("Unknown color space.", e.Message);
}
[NUnit.Framework.Test]
public virtual void MakeDeviceGrayNullColorValuesTest() {
PdfColorSpace colorSpace = PdfColorSpace.MakeColorSpace(PdfName.DeviceGray);
Color color = Color.MakeColor(colorSpace);
NUnit.Framework.Assert.IsTrue(color is DeviceGray);
TSpdf.Test.TestUtil.AreEqual(new float[] { 0.0f }, color.GetColorValue(), EPS);
}
[NUnit.Framework.Test]
public virtual void MakeDeviceGrayTest() {
float[] colorValues = new float[] { 0.7f, 0.5f, 0.1f };
PdfColorSpace colorSpace = PdfColorSpace.MakeColorSpace(PdfName.DeviceGray);
Color color = Color.MakeColor(colorSpace, colorValues);
NUnit.Framework.Assert.IsTrue(color is DeviceGray);
TSpdf.Test.TestUtil.AreEqual(new float[] { 0.7f }, color.GetColorValue(), EPS);
}
[NUnit.Framework.Test]
public virtual void MakeDeviceCmykNullColorValuesTest() {
PdfColorSpace colorSpace = PdfColorSpace.MakeColorSpace(PdfName.DeviceCMYK);
Color color = Color.MakeColor(colorSpace);
NUnit.Framework.Assert.IsTrue(color is DeviceCmyk);
TSpdf.Test.TestUtil.AreEqual(new float[] { 0.0f, 0.0f, 0.0f, 1.0f }, color.GetColorValue(), EPS);
}
[NUnit.Framework.Test]
public virtual void MakeDeviceCmykTest() {
float[] colorValues = new float[] { 0.7f, 0.5f, 0.1f, 0.3f };
PdfColorSpace colorSpace = PdfColorSpace.MakeColorSpace(PdfName.DeviceCMYK);
Color color = Color.MakeColor(colorSpace, colorValues);
NUnit.Framework.Assert.IsTrue(color is DeviceCmyk);
TSpdf.Test.TestUtil.AreEqual(colorValues, color.GetColorValue(), EPS);
}
[NUnit.Framework.Test]
public virtual void UnknownDeviceCsTest() {
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => Color.MakeColor(new ColorTest.CustomDeviceCs
(null)));
NUnit.Framework.Assert.AreEqual("Unknown color space.", e.Message);
}
[NUnit.Framework.Test]
public virtual void MakeCalGrayNullColorValuesTest() {
PdfDictionary dictionary = new PdfDictionary();
dictionary.Put(PdfName.Gamma, new PdfNumber(2.2));
PdfArray calGray = new PdfArray();
calGray.Add(PdfName.CalGray);
calGray.Add(dictionary);
PdfColorSpace colorSpace = PdfColorSpace.MakeColorSpace(calGray);
Color color = Color.MakeColor(colorSpace);
NUnit.Framework.Assert.IsTrue(color is CalGray);
TSpdf.Test.TestUtil.AreEqual(new float[] { 0.0f }, color.GetColorValue(), EPS);
}
[NUnit.Framework.Test]
public virtual void MakeCalGrayTest() {
PdfDictionary dictionary = new PdfDictionary();
dictionary.Put(PdfName.Gamma, new PdfNumber(2.2));
PdfArray calGray = new PdfArray();
calGray.Add(PdfName.CalGray);
calGray.Add(dictionary);
PdfColorSpace colorSpace = PdfColorSpace.MakeColorSpace(calGray);
float[] colorValues = new float[] { 0.7f, 0.5f, 0.1f };
Color color = Color.MakeColor(colorSpace, colorValues);
NUnit.Framework.Assert.IsTrue(color is CalGray);
TSpdf.Test.TestUtil.AreEqual(new float[] { 0.7f }, color.GetColorValue(), EPS);
}
[NUnit.Framework.Test]
public virtual void MakeCalRgbNullColorValuesTest() {
PdfDictionary dictionary = new PdfDictionary();
dictionary.Put(PdfName.Gamma, new PdfNumber(2.2));
PdfArray calRgb = new PdfArray();
calRgb.Add(PdfName.CalRGB);
calRgb.Add(dictionary);
PdfColorSpace colorSpace = PdfColorSpace.MakeColorSpace(calRgb);
Color color = Color.MakeColor(colorSpace);
NUnit.Framework.Assert.IsTrue(color is CalRgb);
TSpdf.Test.TestUtil.AreEqual(new float[] { 0.0f, 0.0f, 0.0f }, color.GetColorValue(), EPS);
}
[NUnit.Framework.Test]
public virtual void MakeCalRgbTest() {
PdfDictionary dictionary = new PdfDictionary();
dictionary.Put(PdfName.Gamma, new PdfNumber(2.2));
PdfArray calRgb = new PdfArray();
calRgb.Add(PdfName.CalRGB);
calRgb.Add(dictionary);
PdfColorSpace colorSpace = PdfColorSpace.MakeColorSpace(calRgb);
float[] colorValues = new float[] { 0.7f, 0.5f, 0.1f };
Color color = Color.MakeColor(colorSpace, colorValues);
NUnit.Framework.Assert.IsTrue(color is CalRgb);
TSpdf.Test.TestUtil.AreEqual(colorValues, color.GetColorValue(), EPS);
}
[NUnit.Framework.Test]
public virtual void MakeLabNullColorValuesTest() {
PdfDictionary dictionary = new PdfDictionary();
dictionary.Put(PdfName.Gamma, new PdfNumber(2.2));
PdfArray calLab = new PdfArray();
calLab.Add(PdfName.Lab);
calLab.Add(dictionary);
PdfColorSpace colorSpace = PdfColorSpace.MakeColorSpace(calLab);
Color color = Color.MakeColor(colorSpace);
NUnit.Framework.Assert.IsTrue(color is Lab);
TSpdf.Test.TestUtil.AreEqual(new float[] { 0.0f, 0.0f, 0.0f }, color.GetColorValue(), EPS);
}
[NUnit.Framework.Test]
public virtual void MakeLabTest() {
PdfDictionary dictionary = new PdfDictionary();
dictionary.Put(PdfName.Gamma, new PdfNumber(2.2));
PdfArray calLab = new PdfArray();
calLab.Add(PdfName.Lab);
calLab.Add(dictionary);
PdfColorSpace colorSpace = PdfColorSpace.MakeColorSpace(calLab);
float[] colorValues = new float[] { 0.7f, 0.5f, 0.1f };
Color color = Color.MakeColor(colorSpace, colorValues);
NUnit.Framework.Assert.IsTrue(color is Lab);
TSpdf.Test.TestUtil.AreEqual(colorValues, color.GetColorValue(), EPS);
}
[NUnit.Framework.Test]
public virtual void UnknownCieBasedCsTest() {
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => Color.MakeColor(new ColorTest.CustomPdfCieBasedCs
(new PdfArray())));
NUnit.Framework.Assert.AreEqual("Unknown color space.", e.Message);
}
[NUnit.Framework.Test]
public virtual void MakeDeviceNNullColorValuesTest() {
PdfArray deviceN = new PdfArray();
deviceN.Add(PdfName.DeviceN);
deviceN.Add(new PdfArray());
deviceN.Add(null);
deviceN.Add(null);
PdfColorSpace colorSpace = PdfColorSpace.MakeColorSpace(deviceN);
Color color = Color.MakeColor(colorSpace);
NUnit.Framework.Assert.IsTrue(color is DeviceN);
TSpdf.Test.TestUtil.AreEqual(new float[] { }, color.GetColorValue(), EPS);
}
[NUnit.Framework.Test]
public virtual void MakeDeviceNTest() {
PdfArray deviceN = new PdfArray();
deviceN.Add(PdfName.DeviceN);
deviceN.Add(new PdfArray());
deviceN.Add(null);
deviceN.Add(null);
PdfColorSpace colorSpace = PdfColorSpace.MakeColorSpace(deviceN);
float[] colorValues = new float[] { 0.7f, 0.5f, 0.1f };
Color color = Color.MakeColor(colorSpace, colorValues);
NUnit.Framework.Assert.IsTrue(color is DeviceN);
TSpdf.Test.TestUtil.AreEqual(colorValues, color.GetColorValue(), EPS);
}
[NUnit.Framework.Test]
public virtual void MakeIndexedNullColorValuesTest() {
PdfArray indexed = new PdfArray();
indexed.Add(PdfName.Indexed);
indexed.Add(new PdfArray());
indexed.Add(null);
indexed.Add(null);
PdfColorSpace colorSpace = PdfColorSpace.MakeColorSpace(indexed);
Color color = Color.MakeColor(colorSpace);
NUnit.Framework.Assert.IsTrue(color is Indexed);
TSpdf.Test.TestUtil.AreEqual(new float[] { 0.0f }, color.GetColorValue(), EPS);
}
[NUnit.Framework.Test]
public virtual void MakeIndexedTest() {
PdfArray indexed = new PdfArray();
indexed.Add(PdfName.Indexed);
indexed.Add(new PdfArray());
indexed.Add(null);
indexed.Add(null);
PdfColorSpace colorSpace = PdfColorSpace.MakeColorSpace(indexed);
float[] colorValues = new float[] { 1.0f, 0.5f, 0.1f };
Color color = Color.MakeColor(colorSpace, colorValues);
NUnit.Framework.Assert.IsTrue(color is Indexed);
TSpdf.Test.TestUtil.AreEqual(new float[] { 1f }, color.GetColorValue(), EPS);
}
[NUnit.Framework.Test]
public virtual void UnknownSpecialCsTest() {
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => Color.MakeColor(new ColorTest.CustomPdfSpecialCs
(new PdfArray())));
NUnit.Framework.Assert.AreEqual("Unknown color space.", e.Message);
}
private class CustomDeviceCs : PdfDeviceCs {
public CustomDeviceCs(PdfName pdfObject)
: base(pdfObject) {
}
public override int GetNumberOfComponents() {
return 0;
}
}
private class CustomPdfCieBasedCs : PdfCieBasedCs {
public CustomPdfCieBasedCs(PdfArray pdfObject)
: base(pdfObject) {
}
public override int GetNumberOfComponents() {
return 0;
}
}
private class CustomPdfSpecialCs : PdfSpecialCs {
public CustomPdfSpecialCs(PdfArray pdfObject)
: base(pdfObject) {
}
public override int GetNumberOfComponents() {
return 0;
}
}
}
}

View File

@@ -0,0 +1,134 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.Kernel.Colors {
[NUnit.Framework.Category("UnitTest")]
public class DeviceRgbTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void MakeDarkerTest() {
DeviceRgb rgbColor = new DeviceRgb(50, 100, 150);
DeviceRgb darkerRgbColor = DeviceRgb.MakeDarker(rgbColor);
// check the resultant darkness of RGB items with using this multiplier
float multiplier = Math.Max(0f, (150f / 255 - 0.33f) / (150f / 255));
NUnit.Framework.Assert.AreEqual(multiplier * (50f / 255), darkerRgbColor.GetColorValue()[0], 0.0001);
NUnit.Framework.Assert.AreEqual(multiplier * (100f / 255), darkerRgbColor.GetColorValue()[1], 0.0001);
NUnit.Framework.Assert.AreEqual(multiplier * (150f / 255), darkerRgbColor.GetColorValue()[2], 0.0001);
}
[NUnit.Framework.Test]
public virtual void MakeLighterTest() {
DeviceRgb rgbColor = new DeviceRgb(50, 100, 150);
DeviceRgb darkerRgbColor = DeviceRgb.MakeLighter(rgbColor);
// check the resultant darkness of RGB items with using this multiplier
float multiplier = Math.Min(1f, 150f / 255 + 0.33f) / (150f / 255);
NUnit.Framework.Assert.AreEqual(multiplier * (50f / 255), darkerRgbColor.GetColorValue()[0], 0.0001);
NUnit.Framework.Assert.AreEqual(multiplier * (100f / 255), darkerRgbColor.GetColorValue()[1], 0.0001);
NUnit.Framework.Assert.AreEqual(multiplier * (150f / 255), darkerRgbColor.GetColorValue()[2], 0.0001);
}
// Android-Conversion-Skip-Block-Start (java.awt library isn't available on Android)
[NUnit.Framework.Test]
public virtual void ColorByAWTColorConstantTest() {
// RED
DeviceRgb rgbColor = new DeviceRgb(System.Drawing.Color.Red);
float[] rgbColorValue = rgbColor.GetColorValue();
NUnit.Framework.Assert.AreEqual(1, rgbColorValue[0], 0.0001);
NUnit.Framework.Assert.AreEqual(0, rgbColorValue[1], 0.0001);
NUnit.Framework.Assert.AreEqual(0, rgbColorValue[2], 0.0001);
// GREEN
rgbColor = new DeviceRgb(System.Drawing.Color.Lime);
rgbColorValue = rgbColor.GetColorValue();
NUnit.Framework.Assert.AreEqual(0, rgbColorValue[0], 0.0001);
NUnit.Framework.Assert.AreEqual(1, rgbColorValue[1], 0.0001);
NUnit.Framework.Assert.AreEqual(0, rgbColorValue[2], 0.0001);
// BLUE
rgbColor = new DeviceRgb(System.Drawing.Color.Blue);
rgbColorValue = rgbColor.GetColorValue();
NUnit.Framework.Assert.AreEqual(0, rgbColorValue[0], 0.0001);
NUnit.Framework.Assert.AreEqual(0, rgbColorValue[1], 0.0001);
NUnit.Framework.Assert.AreEqual(1, rgbColorValue[2], 0.0001);
}
[NUnit.Framework.Test]
public virtual void ColorByAWTColorTest() {
System.Drawing.Color color = System.Drawing.Color.FromArgb(50, 100, 150);
DeviceRgb rgbColor = new DeviceRgb(color);
float[] rgbColorValue = rgbColor.GetColorValue();
NUnit.Framework.Assert.AreEqual(50f / 255, rgbColorValue[0], 0.0001);
NUnit.Framework.Assert.AreEqual(100f / 255, rgbColorValue[1], 0.0001);
NUnit.Framework.Assert.AreEqual(150f / 255, rgbColorValue[2], 0.0001);
}
// Android-Conversion-Skip-Block-End
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.COLORANT_INTENSITIES_INVALID, Count = 14)]
public virtual void InvalidConstructorArgumentsTest() {
NUnit.Framework.Assert.AreEqual(0, GetSumOfColorValues(new DeviceRgb(-2f, 0f, 0f)), 0.001f);
NUnit.Framework.Assert.AreEqual(0, GetSumOfColorValues(new DeviceRgb(0f, -2f, 0f)), 0.001f);
NUnit.Framework.Assert.AreEqual(0, GetSumOfColorValues(new DeviceRgb(0f, 0f, -2f)), 0.001f);
NUnit.Framework.Assert.AreEqual(1, GetSumOfColorValues(new DeviceRgb(2f, 0f, 0f)), 0.001f);
NUnit.Framework.Assert.AreEqual(1, GetSumOfColorValues(new DeviceRgb(0f, 2f, 0f)), 0.001f);
NUnit.Framework.Assert.AreEqual(1, GetSumOfColorValues(new DeviceRgb(0f, 0f, 2f)), 0.001f);
NUnit.Framework.Assert.AreEqual(0, GetSumOfColorValues(new DeviceRgb(-2f, -2f, 0f)), 0.001f);
NUnit.Framework.Assert.AreEqual(0, GetSumOfColorValues(new DeviceRgb(-2f, 0f, -2f)), 0.001f);
NUnit.Framework.Assert.AreEqual(0, GetSumOfColorValues(new DeviceRgb(0f, -2f, -2f)), 0.001f);
NUnit.Framework.Assert.AreEqual(2, GetSumOfColorValues(new DeviceRgb(2f, 2f, 0f)), 0.001f);
NUnit.Framework.Assert.AreEqual(2, GetSumOfColorValues(new DeviceRgb(2f, 0f, 2f)), 0.001f);
NUnit.Framework.Assert.AreEqual(2, GetSumOfColorValues(new DeviceRgb(0f, 2f, 2f)), 0.001f);
NUnit.Framework.Assert.AreEqual(0, GetSumOfColorValues(new DeviceRgb(-2f, -2f, -2f)), 0.001f);
NUnit.Framework.Assert.AreEqual(3, GetSumOfColorValues(new DeviceRgb(2f, 2f, 2f)), 0.001f);
}
private float GetSumOfColorValues(DeviceRgb deviceRgb) {
float sum = 0;
float[] values = deviceRgb.GetColorValue();
for (int i = 0; i < values.Length; i++) {
sum += values[i];
}
return sum;
}
}
}

View File

@@ -0,0 +1,218 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using TSpdf.Test;
namespace TSpdf.Kernel.Colors {
[NUnit.Framework.Category("UnitTest")]
public class WebColorsTest : ExtendedTSpdfTest {
private const double RGB_MAX_VAL = 255.0;
[NUnit.Framework.Test]
public virtual void GetRGBColorBySupportedNameTest() {
String colorName = "violet";
DeviceRgb cmpRgb = new DeviceRgb(0xee, 0x82, 0xee);
DeviceRgb resultRgb = WebColors.GetRGBColor(colorName);
NUnit.Framework.Assert.AreEqual(cmpRgb, resultRgb);
}
[NUnit.Framework.Test]
public virtual void GetRGBColorByUnsupportedNameTest() {
String colorName = "tangerine";
DeviceRgb cmpRgb = new DeviceRgb(0, 0, 0);
DeviceRgb resultRgb = WebColors.GetRGBColor(colorName);
NUnit.Framework.Assert.AreEqual(cmpRgb, resultRgb);
}
[NUnit.Framework.Test]
public virtual void GetRGBAColorByNameTest() {
String colorName = "violet";
float[] cmpRgba = new float[] { (float)(238 / RGB_MAX_VAL), (float)(130 / RGB_MAX_VAL), (float)(238 / RGB_MAX_VAL
), (float)(1.0) };
float delta = (float)(0.0001);
float[] resultRgba = WebColors.GetRGBAColor(colorName);
TSpdf.Test.TestUtil.AreEqual(cmpRgba, resultRgba, delta);
}
[NUnit.Framework.Test]
public virtual void GetRGBAColorByCodeWithHashTest() {
//corresponding color name = "violet"
String hashHex = "#EE82EE";
float[] cmpRgba = new float[] { (float)(238 / RGB_MAX_VAL), (float)(130 / RGB_MAX_VAL), (float)(238 / RGB_MAX_VAL
), (float)(1.0) };
float delta = (float)(0.0001);
float[] resultRgba = WebColors.GetRGBAColor(hashHex);
TSpdf.Test.TestUtil.AreEqual(cmpRgba, resultRgba, delta);
}
[NUnit.Framework.Test]
public virtual void GetRGBAColorByCode6DigitsTest() {
//corresponding color name = "violet"
String hexString = "EE82EE";
float[] cmpRgba = new float[] { (float)(238 / RGB_MAX_VAL), (float)(130 / RGB_MAX_VAL), (float)(238 / RGB_MAX_VAL
), (float)(1.0) };
float delta = (float)(0.0001);
float[] resultRgba = WebColors.GetRGBAColor(hexString);
TSpdf.Test.TestUtil.AreEqual(cmpRgba, resultRgba, delta);
}
[NUnit.Framework.Test]
public virtual void GetRGBAColorByCode3DigitsTest() {
//corresponding full hex = #990000, rgb(153,0,0)
String hexString = "900";
float[] cmpRgba = new float[] { (float)(153 / RGB_MAX_VAL), (float)(0.0), (float)(0.0), (float)(1.0) };
float delta = (float)(0.0001);
float[] resultRgba = WebColors.GetRGBAColor(hexString);
TSpdf.Test.TestUtil.AreEqual(cmpRgba, resultRgba, delta);
}
[NUnit.Framework.Test]
public virtual void GetRGBAColorByCodeWrongDigitsNumberTest() {
String hexString = "9000";
float[] resultRgba = WebColors.GetRGBAColor(hexString);
NUnit.Framework.Assert.IsNull(resultRgba);
}
[NUnit.Framework.Test]
public virtual void GetRGBAColorByRgbObjectTest() {
//corresponding color name = "violet"
String rgbString = "rgb(238,130,238)";
float[] cmpRgba = new float[] { (float)(238 / RGB_MAX_VAL), (float)(130 / RGB_MAX_VAL), (float)(238 / RGB_MAX_VAL
), (float)(1.0) };
float delta = (float)(0.0001);
float[] resultRgba = WebColors.GetRGBAColor(rgbString);
TSpdf.Test.TestUtil.AreEqual(cmpRgba, resultRgba, delta);
}
[NUnit.Framework.Test]
public virtual void GetRGBAColorByRgbaObjectTest() {
//corresponding color name = "violet"
String rgbaString = "rgba(238,130,238,255)";
float[] cmpRgba = new float[] { (float)(238 / RGB_MAX_VAL), (float)(130 / RGB_MAX_VAL), (float)(238 / RGB_MAX_VAL
), (float)(1.0) };
float delta = (float)(0.0001);
float[] resultRgba = WebColors.GetRGBAColor(rgbaString);
TSpdf.Test.TestUtil.AreEqual(cmpRgba, resultRgba, delta);
}
[NUnit.Framework.Test]
public virtual void GetCMYKColorByDeviceCmykTest() {
//corresponding color name = "violet"
String cmykString = "device-cmyk(44% 100% 0% 0%)";
float[] cmpCmyk = new float[] { 0.44f, 1f, 0f, 0f, 1f };
float delta = (float)(0.0001);
float[] resultCmyk = WebColors.GetCMYKArray(cmykString);
TSpdf.Test.TestUtil.AreEqual(cmpCmyk, resultCmyk, delta);
}
[NUnit.Framework.Test]
public virtual void GetCMYKColorByDeviceCmykWithOpacityTest() {
//corresponding color name = "violet"
String cmykString = "device-cmyk(44% 100% 0% 0% / .8)";
float[] cmpCmyk = new float[] { 0.44f, 1f, 0f, 0f, 0.8f };
float delta = (float)(0.0001);
float[] resultCmyk = WebColors.GetCMYKArray(cmykString);
TSpdf.Test.TestUtil.AreEqual(cmpCmyk, resultCmyk, delta);
}
[NUnit.Framework.Test]
public virtual void GetCMYKColorByDeviceCmykWithOpacityAndFallbackTest() {
//corresponding color name = "violet"
String cmykString = "device-cmyk(44% 100% 0% 0% / .8 rgb(238,130,238))";
float[] cmpCmyk = new float[] { 0.44f, 1f, 0f, 0f, 0.8f };
float delta = (float)(0.0001);
float[] resultCmyk = WebColors.GetCMYKArray(cmykString);
TSpdf.Test.TestUtil.AreEqual(cmpCmyk, resultCmyk, delta);
}
[NUnit.Framework.Test]
public virtual void GetCMYKColorWithNoBlack() {
String cmykString = "device-cmyk(44% 100% 0%))";
float[] cmpCmyk = new float[] { 0.44f, 1f, 0f, 1f, 1f };
float delta = (float)(0.0001);
float[] resultCmyk = WebColors.GetCMYKArray(cmykString);
TSpdf.Test.TestUtil.AreEqual(cmpCmyk, resultCmyk, delta);
}
[NUnit.Framework.Test]
public virtual void GetCMYKColorWithInvalidDeviceCmykDefinition() {
String cmykString = "cmyk(44% 100% 0% 1%))";
float[] resultCmyk = WebColors.GetCMYKArray(cmykString);
NUnit.Framework.Assert.IsNull(resultCmyk);
}
[NUnit.Framework.Test]
public virtual void GetCMYKColorWithExceptionDuringParsing() {
float[] resultCmyk = WebColors.GetCMYKArray(null);
NUnit.Framework.Assert.IsNull(resultCmyk);
}
[NUnit.Framework.Test]
public virtual void GetCMYKColorTest() {
//corresponding color name = "violet"
String cmykString = "device-cmyk(44% 100% 0% 0%)";
float[] cmpCmyk = new float[] { 0.44f, 1f, 0f, 0f };
float delta = (float)(0.0001);
DeviceCmyk resultCmyk = WebColors.GetCMYKColor(cmykString);
TSpdf.Test.TestUtil.AreEqual(cmpCmyk, resultCmyk.colorValue, delta);
}
[NUnit.Framework.Test]
public virtual void GetCMYKColorFloatTest() {
String cmykString = "device-cmyk(0.44 1 0.2 0.2)";
float[] cmpCmyk = new float[] { 0.44f, 1f, 0.2f, 0.2f };
float delta = (float)(0.0001);
DeviceCmyk resultCmyk = WebColors.GetCMYKColor(cmykString);
TSpdf.Test.TestUtil.AreEqual(cmpCmyk, resultCmyk.colorValue, delta);
}
[NUnit.Framework.Test]
public virtual void GetCMYKColorNullTest() {
String cmykString = "null";
float[] cmpCmyk = new float[] { 0f, 0f, 0f, 1f };
float delta = (float)(0.0001);
DeviceCmyk resultCmyk = WebColors.GetCMYKColor(cmykString);
TSpdf.Test.TestUtil.AreEqual(cmpCmyk, resultCmyk.colorValue, delta);
}
}
}

View File

@@ -0,0 +1,50 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using TSpdf.Test;
namespace TSpdf.Kernel.Colors.Gradients {
[NUnit.Framework.Category("UnitTest")]
public class GradientColorStopTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void NormalizationTest() {
GradientColorStop stopToTest = new GradientColorStop(new float[] { -0.5f, 1.5f, 0.5f, 0.5f }, 1.5, GradientColorStop.OffsetType
.AUTO).SetHint(1.5, GradientColorStop.HintOffsetType.NONE);
TSpdf.Test.TestUtil.AreEqual(new float[] { 0f, 1f, 0.5f }, stopToTest.GetRgbArray(), 1e-10f);
NUnit.Framework.Assert.AreEqual(0, stopToTest.GetOffset(), 1e-10);
NUnit.Framework.Assert.AreEqual(GradientColorStop.OffsetType.AUTO, stopToTest.GetOffsetType());
NUnit.Framework.Assert.AreEqual(0, stopToTest.GetHintOffset(), 1e-10);
NUnit.Framework.Assert.AreEqual(GradientColorStop.HintOffsetType.NONE, stopToTest.GetHintOffsetType());
}
[NUnit.Framework.Test]
public virtual void CornerCasesTest() {
GradientColorStop stopToTest = new GradientColorStop((float[])null, 1.5, GradientColorStop.OffsetType.AUTO
).SetHint(1.5, GradientColorStop.HintOffsetType.NONE);
TSpdf.Test.TestUtil.AreEqual(new float[] { 0f, 0f, 0f }, stopToTest.GetRgbArray(), 1e-10f);
NUnit.Framework.Assert.AreEqual(0, stopToTest.GetOffset(), 1e-10);
NUnit.Framework.Assert.AreEqual(GradientColorStop.OffsetType.AUTO, stopToTest.GetOffsetType());
NUnit.Framework.Assert.AreEqual(0, stopToTest.GetHintOffset(), 1e-10);
NUnit.Framework.Assert.AreEqual(GradientColorStop.HintOffsetType.NONE, stopToTest.GetHintOffsetType());
}
}
}

View File

@@ -0,0 +1,725 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using System.IO;
using TSpdf.Kernel.Colors;
using TSpdf.Kernel.Geom;
using TSpdf.Kernel.Pdf;
using TSpdf.Kernel.Pdf.Canvas;
using TSpdf.Kernel.Utils;
using TSpdf.Test;
namespace TSpdf.Kernel.Colors.Gradients {
[NUnit.Framework.Category("IntegrationTest")]
public class LinearGradientBuilderTest : ExtendedTSpdfTest {
public static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/colors/gradients/LinearGradientBuilderTest/";
public static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/colors/gradients/LinearGradientBuilderTest/";
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
CreateOrClearDestinationFolder(destinationFolder);
}
[NUnit.Framework.Test]
public virtual void BuildWithNullArgumentsAndWithoutSettersTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder();
NUnit.Framework.Assert.IsNull(gradientBuilder.BuildColor(targetBoundingBox, null, null));
}
[NUnit.Framework.Test]
public virtual void BuildWithOneStopTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 100f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 100f, targetBoundingBox
.GetTop() - 100f).SetSpreadMethod(GradientSpreadMethod.PAD).AddColorStop(new GradientColorStop(ColorConstants
.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfs("buildWithOneStopTest.pdf", targetBoundingBox, null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuildWithTwoStopsTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 100f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 100f, targetBoundingBox
.GetTop() - 100f).SetSpreadMethod(GradientSpreadMethod.PAD).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants
.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfs("buildWithTwoStopsTest.pdf", targetBoundingBox, null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuildWithTwoStopsAtTheBeginningTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 100f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 100f, targetBoundingBox
.GetTop() - 100f).SetSpreadMethod(GradientSpreadMethod.PAD).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants
.BLUE.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfs("buildWithTwoStopsAtTheBeginningTest.pdf", targetBoundingBox, null, gradientBuilder
);
}
[NUnit.Framework.Test]
public virtual void BuildWithTwoStopsAtTheEndTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 100f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 100f, targetBoundingBox
.GetTop() - 100f).SetSpreadMethod(GradientSpreadMethod.PAD).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 1d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants
.BLUE.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfs("buildWithTwoStopsAtTheEndTest.pdf", targetBoundingBox, null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuildWithTwoStopsInTheMiddleTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 100f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 100f, targetBoundingBox
.GetTop() - 100f).SetSpreadMethod(GradientSpreadMethod.PAD).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0.5d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.BLUE.GetColorValue(), 0.5d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfs("buildWithTwoStopsInTheMiddleTest.pdf", targetBoundingBox, null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuildWithTwoStopsBeforeTheBeginningTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 100f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 100f, targetBoundingBox
.GetTop() - 100f).SetSpreadMethod(GradientSpreadMethod.PAD).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), -0.1d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.BLUE.GetColorValue(), -0.2d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfs("buildWithTwoStopsBeforeTheBeginningTest.pdf", targetBoundingBox, null, gradientBuilder
);
}
[NUnit.Framework.Test]
public virtual void BuildWithTwoStopsAfterTheEndTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 100f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 100f, targetBoundingBox
.GetTop() - 100f).SetSpreadMethod(GradientSpreadMethod.PAD).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 1.2d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.BLUE.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfs("buildWithTwoStopsAfterTheEndTest.pdf", targetBoundingBox, null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void PadCaseWithVeryCloseCornerStopsTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 100f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 100f, targetBoundingBox
.GetTop() - 100f).SetSpreadMethod(GradientSpreadMethod.PAD).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants
.GREEN.GetColorValue(), 0.01d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.GREEN.GetColorValue(), 0.99d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new
GradientColorStop(ColorConstants.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfs("padCaseWithVeryCloseCornerStopsTest.pdf", targetBoundingBox, null, gradientBuilder
);
}
[NUnit.Framework.Test]
public virtual void BuildWithDoublingStopsAtEndsAndPadTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 100f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 100f, targetBoundingBox
.GetTop() - 100f).SetSpreadMethod(GradientSpreadMethod.PAD).AddColorStop(new GradientColorStop(ColorConstants
.MAGENTA.GetColorValue(), -0.2, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.ORANGE.GetColorValue(), -0.2, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new
GradientColorStop(ColorConstants.RED.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop
(new GradientColorStop(ColorConstants.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType.RELATIVE)
).AddColorStop(new GradientColorStop(ColorConstants.ORANGE.GetColorValue(), 1.2, GradientColorStop.OffsetType
.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants.MAGENTA.GetColorValue(), 1.2, GradientColorStop.OffsetType
.RELATIVE));
GenerateAndComparePdfs("buildWithDoublingStopsAtEndsAndPadTest.pdf", targetBoundingBox, null, gradientBuilder
);
}
[NUnit.Framework.Test]
public virtual void BuildWithDoublingStopsAtEndsAndEndsOfCoordinatesAndPadTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 100f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 100f, targetBoundingBox
.GetTop() - 100f).SetSpreadMethod(GradientSpreadMethod.PAD).AddColorStop(new GradientColorStop(ColorConstants
.MAGENTA.GetColorValue(), -0.2, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.ORANGE.GetColorValue(), -0.2, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new
GradientColorStop(ColorConstants.RED.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop
(new GradientColorStop(ColorConstants.MAGENTA.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE
)).AddColorStop(new GradientColorStop(ColorConstants.ORANGE.GetColorValue(), 1d, GradientColorStop.OffsetType
.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType
.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants.ORANGE.GetColorValue(), 1.2, GradientColorStop.OffsetType
.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants.MAGENTA.GetColorValue(), 1.2, GradientColorStop.OffsetType
.RELATIVE));
GenerateAndComparePdfs("buildWithDoublingStopsAtEndsAndEndsOfCoordinatesAndPadTest.pdf", targetBoundingBox
, null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuildWithoutCoordinatesTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetSpreadMethod(GradientSpreadMethod
.PAD).AddColorStop(new GradientColorStop(ColorConstants.RED.GetColorValue(), 0d, GradientColorStop.OffsetType
.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants.GREEN.GetColorValue(), 0.5, GradientColorStop.OffsetType
.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType
.RELATIVE));
GenerateAndComparePdfs("buildWithoutCoordinatesTest.pdf", targetBoundingBox, null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuildWithZeroVectorTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 100f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetLeft() + 100f, targetBoundingBox
.GetBottom() + 100f).SetSpreadMethod(GradientSpreadMethod.PAD).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants
.GREEN.GetColorValue(), 0.5, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfs("buildWithZeroVectorTest.pdf", targetBoundingBox, null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuildWithNullArgumentsAndWithoutStopsTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 100f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 100f, targetBoundingBox
.GetTop() - 100f).SetSpreadMethod(GradientSpreadMethod.PAD);
NUnit.Framework.Assert.IsNull(gradientBuilder.BuildColor(null, null, null));
}
[NUnit.Framework.Test]
public virtual void BuildWithNullArgumentsAndNoneSpreadingTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 100f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 100f, targetBoundingBox
.GetTop() - 100f).SetSpreadMethod(GradientSpreadMethod.NONE).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants
.GREEN.GetColorValue(), 0.5, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfsWithoutArgumentToBuild("buildWithNullArgumentsAndNoneSpreadingTest.pdf", targetBoundingBox
, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuildWithNullArgumentsAndPadSpreadingTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 100f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 100f, targetBoundingBox
.GetTop() - 100f).SetSpreadMethod(GradientSpreadMethod.PAD).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants
.GREEN.GetColorValue(), 0.5, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfsWithoutArgumentToBuild("buildWithNullArgumentsAndPadSpreadingTest.pdf", targetBoundingBox
, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuildWithNullArgumentsAndReflectSpreadingTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 100f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 100f, targetBoundingBox
.GetTop() - 100f).SetSpreadMethod(GradientSpreadMethod.REFLECT).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants
.GREEN.GetColorValue(), 0.5, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfsWithoutArgumentToBuild("buildWithNullArgumentsAndReflectSpreadingTest.pdf", targetBoundingBox
, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuildWithNullArgumentsAndRepeatSpreadingTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 100f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 100f, targetBoundingBox
.GetTop() - 100f).SetSpreadMethod(GradientSpreadMethod.REPEAT).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants
.GREEN.GetColorValue(), 0.5, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfsWithoutArgumentToBuild("buildWithNullArgumentsAndRepeatSpreadingTest.pdf", targetBoundingBox
, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuilderWithNoneSpreadingTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 100f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 100f, targetBoundingBox
.GetTop() - 100f).SetSpreadMethod(GradientSpreadMethod.NONE).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants
.GREEN.GetColorValue(), 0.5, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfs("builderWithNoneSpreadingTest.pdf", targetBoundingBox, null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuilderWithNoneSpreadingAndCanvasTransformTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 100f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 100f, targetBoundingBox
.GetTop() - 100f).SetSpreadMethod(GradientSpreadMethod.NONE).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants
.GREEN.GetColorValue(), 0.5, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType.RELATIVE));
AffineTransform canvasTransform = AffineTransform.GetTranslateInstance(50, -50);
canvasTransform.Scale(0.8, 1.1);
canvasTransform.Rotate(Math.PI / 3, 400f, 550f);
GenerateAndComparePdfs("builderWithNoneSpreadingAndCanvasTransformTest.pdf", targetBoundingBox, canvasTransform
, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuilderWithNoneSpreadingAndAllTransformsTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AffineTransform gradientTransform = AffineTransform.GetTranslateInstance(150, -50);
gradientTransform.Scale(0.5, 1.5);
gradientTransform.Rotate(Math.PI / 3, 400f, 550f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 100f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 100f, targetBoundingBox
.GetTop() - 100f).SetCurrentSpaceToGradientVectorSpaceTransformation(gradientTransform).SetSpreadMethod
(GradientSpreadMethod.NONE).AddColorStop(new GradientColorStop(ColorConstants.RED.GetColorValue(), 0d,
GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants.GREEN.GetColorValue
(), 0.5, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants.BLUE
.GetColorValue(), 1d, GradientColorStop.OffsetType.RELATIVE));
AffineTransform canvasTransform = AffineTransform.GetTranslateInstance(50, -50);
canvasTransform.Scale(0.8, 1.1);
canvasTransform.Rotate(Math.PI / 3, 400f, 550f);
GenerateAndComparePdfs("builderWithNoneSpreadingAndAllTransformsTest.pdf", targetBoundingBox, canvasTransform
, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuilderWithPadSpreadingTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 100f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 100f, targetBoundingBox
.GetTop() - 100f).SetSpreadMethod(GradientSpreadMethod.PAD).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants
.GREEN.GetColorValue(), 0.5, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfs("builderWithPadSpreadingTest.pdf", targetBoundingBox, null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuilderWithReflectSpreadingTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 100f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 100f, targetBoundingBox
.GetTop() - 100f).SetSpreadMethod(GradientSpreadMethod.REFLECT).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants
.GREEN.GetColorValue(), 0.5, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfs("builderWithReflectSpreadingTest.pdf", targetBoundingBox, null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuilderWithRepeatSpreadingTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 100f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 100f, targetBoundingBox
.GetTop() - 100f).SetSpreadMethod(GradientSpreadMethod.REPEAT).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants
.GREEN.GetColorValue(), 0.5, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfs("builderWithRepeatSpreadingTest.pdf", targetBoundingBox, null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuilderWithRepeatSpreadingAndAllTransformsTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AffineTransform gradientTransform = AffineTransform.GetTranslateInstance(150, -50);
gradientTransform.Scale(0.5, 1.5);
gradientTransform.Rotate(Math.PI / 3, 400f, 550f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 100f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 100f, targetBoundingBox
.GetTop() - 100f).SetCurrentSpaceToGradientVectorSpaceTransformation(gradientTransform).SetSpreadMethod
(GradientSpreadMethod.REPEAT).AddColorStop(new GradientColorStop(ColorConstants.RED.GetColorValue(), 0d
, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants.GREEN.GetColorValue
(), 0.5, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants.BLUE
.GetColorValue(), 1d, GradientColorStop.OffsetType.RELATIVE));
AffineTransform canvasTransform = AffineTransform.GetTranslateInstance(50, -50);
canvasTransform.Scale(0.8, 1.1);
canvasTransform.Rotate(Math.PI / 3, 400f, 550f);
GenerateAndComparePdfs("builderWithRepeatSpreadingAndAllTransformsTest.pdf", targetBoundingBox, canvasTransform
, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuilderWithRepeatSpreadingAndToRightVectorTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetRight() + 100f, 0f, targetBoundingBox.GetRight() + 300f, 0f).SetSpreadMethod(GradientSpreadMethod.
REPEAT).AddColorStop(new GradientColorStop(ColorConstants.RED.GetColorValue())).AddColorStop(new GradientColorStop
(ColorConstants.GREEN.GetColorValue())).AddColorStop(new GradientColorStop(ColorConstants.BLUE.GetColorValue
()));
GenerateAndComparePdfs("builderWithRepeatSpreadingAndToRightVectorTest.pdf", targetBoundingBox, null, gradientBuilder
);
}
[NUnit.Framework.Test]
public virtual void BuilderWithRepeatSpreadingAndToLeftVectorTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetRight() + 300f, 0f, targetBoundingBox.GetRight() + 100f, 0f).SetSpreadMethod(GradientSpreadMethod.
REPEAT).AddColorStop(new GradientColorStop(ColorConstants.RED.GetColorValue())).AddColorStop(new GradientColorStop
(ColorConstants.GREEN.GetColorValue())).AddColorStop(new GradientColorStop(ColorConstants.BLUE.GetColorValue
()));
GenerateAndComparePdfs("builderWithRepeatSpreadingAndToLeftVectorTest.pdf", targetBoundingBox, null, gradientBuilder
);
}
[NUnit.Framework.Test]
public virtual void BuilderWithRepeatSpreadingAndToTopVectorTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(0f, targetBoundingBox
.GetBottom() - 300f, 0f, targetBoundingBox.GetBottom() - 100f).SetSpreadMethod(GradientSpreadMethod.REPEAT
).AddColorStop(new GradientColorStop(ColorConstants.RED.GetColorValue())).AddColorStop(new GradientColorStop
(ColorConstants.GREEN.GetColorValue())).AddColorStop(new GradientColorStop(ColorConstants.BLUE.GetColorValue
()));
GenerateAndComparePdfs("builderWithRepeatSpreadingAndToTopVectorTest.pdf", targetBoundingBox, null, gradientBuilder
);
}
[NUnit.Framework.Test]
public virtual void BuilderWithRepeatSpreadingAndToBottomVectorTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(0f, targetBoundingBox
.GetBottom() - 100f, 0f, targetBoundingBox.GetBottom() - 300f).SetSpreadMethod(GradientSpreadMethod.REPEAT
).AddColorStop(new GradientColorStop(ColorConstants.RED.GetColorValue())).AddColorStop(new GradientColorStop
(ColorConstants.GREEN.GetColorValue())).AddColorStop(new GradientColorStop(ColorConstants.BLUE.GetColorValue
()));
GenerateAndComparePdfs("builderWithRepeatSpreadingAndToBottomVectorTest.pdf", targetBoundingBox, null, gradientBuilder
);
}
[NUnit.Framework.Test]
public virtual void BuildWithAutoStopAndAbsoluteOnCoordinatesHintTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft(), targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight(), targetBoundingBox.GetBottom
() + 100f).SetSpreadMethod(GradientSpreadMethod.NONE).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0.1d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.GREEN.GetColorValue()).SetHint(100f, GradientColorStop.HintOffsetType.ABSOLUTE_ON_GRADIENT
)).AddColorStop(new GradientColorStop(ColorConstants.BLUE.GetColorValue(), 0.9d, GradientColorStop.OffsetType
.RELATIVE));
GenerateAndComparePdfs("buildWithAutoStopAndAbsoluteOnCoordinatesHintTest.pdf", targetBoundingBox, null, gradientBuilder
);
}
[NUnit.Framework.Test]
public virtual void BuildWithAutoStopAndRelativeOnCoordinatesHintTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft(), targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight(), targetBoundingBox.GetBottom
() + 100f).SetSpreadMethod(GradientSpreadMethod.NONE).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0.1d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.GREEN.GetColorValue()).SetHint(0.2f, GradientColorStop.HintOffsetType.RELATIVE_ON_GRADIENT
)).AddColorStop(new GradientColorStop(ColorConstants.BLUE.GetColorValue(), 0.9d, GradientColorStop.OffsetType
.RELATIVE));
GenerateAndComparePdfs("buildWithAutoStopAndRelativeOnCoordinatesHintTest.pdf", targetBoundingBox, null, gradientBuilder
);
}
[NUnit.Framework.Test]
public virtual void BuildWithAutoStopAndRelativeBetweenColorsHintTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft(), targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight(), targetBoundingBox.GetBottom
() + 100f).SetSpreadMethod(GradientSpreadMethod.NONE).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0.1d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.GREEN.GetColorValue()).SetHint(0.2f, GradientColorStop.HintOffsetType.RELATIVE_BETWEEN_COLORS
)).AddColorStop(new GradientColorStop(ColorConstants.BLUE.GetColorValue(), 0.9d, GradientColorStop.OffsetType
.RELATIVE));
GenerateAndComparePdfs("buildWithAutoStopAndRelativeBetweenColorsHintTest.pdf", targetBoundingBox, null, gradientBuilder
);
}
[NUnit.Framework.Test]
public virtual void BuildWithAutoStopAndRelativeBetweenColorsZeroHintTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft(), targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight(), targetBoundingBox.GetBottom
() + 100f).SetSpreadMethod(GradientSpreadMethod.NONE).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0.1d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.GREEN.GetColorValue()).SetHint(0f, GradientColorStop.HintOffsetType.RELATIVE_BETWEEN_COLORS
)).AddColorStop(new GradientColorStop(ColorConstants.BLUE.GetColorValue(), 0.9d, GradientColorStop.OffsetType
.RELATIVE));
GenerateAndComparePdfs("buildWithAutoStopAndRelativeBetweenColorsZeroHintTest.pdf", targetBoundingBox, null
, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuildWithAutoStopAndRelativeBetweenColorsOneHintTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft(), targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight(), targetBoundingBox.GetBottom
() + 100f).SetSpreadMethod(GradientSpreadMethod.NONE).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0.1d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.GREEN.GetColorValue()).SetHint(1f, GradientColorStop.HintOffsetType.RELATIVE_BETWEEN_COLORS
)).AddColorStop(new GradientColorStop(ColorConstants.BLUE.GetColorValue(), 0.9d, GradientColorStop.OffsetType
.RELATIVE));
GenerateAndComparePdfs("buildWithAutoStopAndRelativeBetweenColorsOneHintTest.pdf", targetBoundingBox, null
, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuildWithPadSpreadingAndRelativeBetweenColorsZeroHintTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft(), targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight(), targetBoundingBox.GetBottom
() + 100f).SetSpreadMethod(GradientSpreadMethod.PAD).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0.1d, GradientColorStop.OffsetType.RELATIVE).SetHint(0f, GradientColorStop.HintOffsetType
.RELATIVE_BETWEEN_COLORS)).AddColorStop(new GradientColorStop(ColorConstants.BLUE.GetColorValue(), 0.9d
, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfs("buildWithPadSpreadingAndRelativeBetweenColorsZeroHintTest.pdf", targetBoundingBox,
null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuildWithPadSpreadingAndRelativeBetweenColorsOneHintTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft(), targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight(), targetBoundingBox.GetBottom
() + 100f).SetSpreadMethod(GradientSpreadMethod.PAD).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0.1d, GradientColorStop.OffsetType.RELATIVE).SetHint(1f, GradientColorStop.HintOffsetType
.RELATIVE_BETWEEN_COLORS)).AddColorStop(new GradientColorStop(ColorConstants.BLUE.GetColorValue(), 0.9d
, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfs("buildWithPadSpreadingAndRelativeBetweenColorsOneHintTest.pdf", targetBoundingBox,
null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuildWithAutoStopAndNoneHintTypeTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft(), targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight(), targetBoundingBox.GetBottom
() + 100f).SetSpreadMethod(GradientSpreadMethod.NONE).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0.1d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.GREEN.GetColorValue()).SetHint(0.2f, GradientColorStop.HintOffsetType.NONE)).AddColorStop
(new GradientColorStop(ColorConstants.BLUE.GetColorValue(), 0.9d, GradientColorStop.OffsetType.RELATIVE
));
GenerateAndComparePdfs("buildWithAutoStopAndNoneHintTypeTest.pdf", targetBoundingBox, null, gradientBuilder
);
}
[NUnit.Framework.Test]
public virtual void BuildWithReflectSpreadingAndStopsOutsideCoordinatesTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 100f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 100f, targetBoundingBox
.GetBottom() + 100f).SetSpreadMethod(GradientSpreadMethod.REFLECT).AddColorStop(new GradientColorStop(
ColorConstants.RED.GetColorValue(), -0.5d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.BLUE.GetColorValue(), 1.5d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfs("buildWithReflectSpreadingAndStopsOutsideCoordinatesTest.pdf", targetBoundingBox, null
, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuildWithSingleAutoStopsAtStartAndEndTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 10f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 10f, targetBoundingBox
.GetBottom() + 100f).SetSpreadMethod(GradientSpreadMethod.NONE).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue()).SetHint(0.1, GradientColorStop.HintOffsetType.RELATIVE_BETWEEN_COLORS)).AddColorStop
(new GradientColorStop(ColorConstants.BLUE.GetColorValue(), 0.5d, GradientColorStop.OffsetType.RELATIVE
)).AddColorStop(new GradientColorStop(ColorConstants.GREEN.GetColorValue(), 200d, GradientColorStop.OffsetType
.ABSOLUTE)).AddColorStop(new GradientColorStop(ColorConstants.RED.GetColorValue()).SetHint(0.1, GradientColorStop.HintOffsetType
.RELATIVE_BETWEEN_COLORS));
GenerateAndComparePdfs("buildWithSingleAutoStopsAtStartAndEndTest.pdf", targetBoundingBox, null, gradientBuilder
);
}
[NUnit.Framework.Test]
public virtual void BuildWithSingleAutoStopsAtStartAndEndWithHintsTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 10f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 10f, targetBoundingBox
.GetBottom() + 100f).SetSpreadMethod(GradientSpreadMethod.NONE).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue()).SetHint(0.1, GradientColorStop.HintOffsetType.RELATIVE_ON_GRADIENT)).AddColorStop
(new GradientColorStop(ColorConstants.BLUE.GetColorValue(), 0.5d, GradientColorStop.OffsetType.RELATIVE
)).AddColorStop(new GradientColorStop(ColorConstants.GREEN.GetColorValue(), 200d, GradientColorStop.OffsetType
.ABSOLUTE)).AddColorStop(new GradientColorStop(ColorConstants.RED.GetColorValue()).SetHint(0.9, GradientColorStop.HintOffsetType
.RELATIVE_ON_GRADIENT));
GenerateAndComparePdfs("buildWithSingleAutoStopsAtStartAndEndWithHintsTest.pdf", targetBoundingBox, null,
gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuildWithMultipleAutoStopsAtStartAndEndWithHintsTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 10f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 10f, targetBoundingBox
.GetBottom() + 100f).SetSpreadMethod(GradientSpreadMethod.NONE).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue())).AddColorStop(new GradientColorStop(ColorConstants.GREEN.GetColorValue())).AddColorStop
(new GradientColorStop(ColorConstants.BLUE.GetColorValue(), 0.5d, GradientColorStop.OffsetType.RELATIVE
)).AddColorStop(new GradientColorStop(ColorConstants.GREEN.GetColorValue(), 200d, GradientColorStop.OffsetType
.ABSOLUTE)).AddColorStop(new GradientColorStop(ColorConstants.RED.GetColorValue())).AddColorStop(new GradientColorStop
(ColorConstants.GREEN.GetColorValue()));
GenerateAndComparePdfs("buildWithMultipleAutoStopsAtStartAndEndWithHintsTest.pdf", targetBoundingBox, null
, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuildWithAutoStopsInTheMiddleTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 10f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 10f, targetBoundingBox
.GetBottom() + 100f).SetSpreadMethod(GradientSpreadMethod.NONE).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE).SetHint(0.3d, GradientColorStop.HintOffsetType
.RELATIVE_BETWEEN_COLORS)).AddColorStop(new GradientColorStop(ColorConstants.BLUE.GetColorValue()).SetHint
(0.3d, GradientColorStop.HintOffsetType.RELATIVE_BETWEEN_COLORS)).AddColorStop(new GradientColorStop(ColorConstants
.GREEN.GetColorValue()).SetHint(0.3d, GradientColorStop.HintOffsetType.RELATIVE_BETWEEN_COLORS)).AddColorStop
(new GradientColorStop(ColorConstants.RED.GetColorValue(), 1d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfs("buildWithAutoStopsInTheMiddleTest.pdf", targetBoundingBox, null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuildWithAutoStopsInTheMiddleWithHintsTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 10f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 10f, targetBoundingBox
.GetBottom() + 100f).SetSpreadMethod(GradientSpreadMethod.NONE).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE).SetHint(0.2d, GradientColorStop.HintOffsetType
.RELATIVE_ON_GRADIENT)).AddColorStop(new GradientColorStop(ColorConstants.BLUE.GetColorValue())).AddColorStop
(new GradientColorStop(ColorConstants.GREEN.GetColorValue()).SetHint(0.7d, GradientColorStop.HintOffsetType
.RELATIVE_ON_GRADIENT)).AddColorStop(new GradientColorStop(ColorConstants.RED.GetColorValue(), 1d, GradientColorStop.OffsetType
.RELATIVE));
GenerateAndComparePdfs("buildWithAutoStopsInTheMiddleWithHintsTest.pdf", targetBoundingBox, null, gradientBuilder
);
}
[NUnit.Framework.Test]
public virtual void BuildWithDecreasingOffsetsTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 10f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 10f, targetBoundingBox
.GetBottom() + 100f).SetSpreadMethod(GradientSpreadMethod.PAD).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0.5d, GradientColorStop.OffsetType.RELATIVE).SetHint(0.4d, GradientColorStop.HintOffsetType
.RELATIVE_ON_GRADIENT)).AddColorStop(new GradientColorStop(ColorConstants.BLUE.GetColorValue(), 0.6d,
GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants.GREEN.GetColorValue
(), 100d, GradientColorStop.OffsetType.ABSOLUTE).SetHint(0.3d, GradientColorStop.HintOffsetType.RELATIVE_BETWEEN_COLORS
)).AddColorStop(new GradientColorStop(ColorConstants.RED.GetColorValue(), 0.9d, GradientColorStop.OffsetType
.RELATIVE).SetHint(120d, GradientColorStop.HintOffsetType.ABSOLUTE_ON_GRADIENT)).AddColorStop(new GradientColorStop
(ColorConstants.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfs("buildWithDecreasingOffsetsTest.pdf", targetBoundingBox, null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuilderWithZeroColorsLengthAndReflect() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 10f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 10f, targetBoundingBox
.GetBottom() + 100f).SetSpreadMethod(GradientSpreadMethod.REFLECT).AddColorStop(new GradientColorStop(
ColorConstants.RED.GetColorValue(), 0.8d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.BLUE.GetColorValue(), 0.5d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.GREEN.GetColorValue(), 0.2d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfs("builderWithZeroColorsLengthAndReflect.pdf", targetBoundingBox, null, gradientBuilder
);
}
[NUnit.Framework.Test]
public virtual void BuildWithTwoStopsBeforeTheBeginningAndNoneTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 100f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 100f, targetBoundingBox
.GetTop() - 100f).SetSpreadMethod(GradientSpreadMethod.NONE).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), -10d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.BLUE.GetColorValue(), -5d, GradientColorStop.OffsetType.RELATIVE));
NUnit.Framework.Assert.IsNull(gradientBuilder.BuildColor(targetBoundingBox, null, null));
}
[NUnit.Framework.Test]
public virtual void BuildWithTwoStopsAfterEndAndNoneTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 100f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 100f, targetBoundingBox
.GetTop() - 100f).SetSpreadMethod(GradientSpreadMethod.NONE).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 5d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants
.BLUE.GetColorValue(), 10d, GradientColorStop.OffsetType.RELATIVE));
NUnit.Framework.Assert.IsNull(gradientBuilder.BuildColor(targetBoundingBox, null, null));
}
[NUnit.Framework.Test]
public virtual void BuildWithTwoEqualOffsetsStopsAndNoneTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 100f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 100f, targetBoundingBox
.GetTop() - 100f).SetSpreadMethod(GradientSpreadMethod.NONE).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0.5d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.BLUE.GetColorValue(), 0.5d, GradientColorStop.OffsetType.RELATIVE));
NUnit.Framework.Assert.IsNull(gradientBuilder.BuildColor(targetBoundingBox, null, null));
}
[NUnit.Framework.Test]
public virtual void BuildWithTwoStopsInCenterAndNoneTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 100f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 100f, targetBoundingBox
.GetTop() - 100f).SetSpreadMethod(GradientSpreadMethod.NONE).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0.2d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.BLUE.GetColorValue(), 0.8d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfs("buildWithTwoEqualOffsetsStopsTest.pdf", targetBoundingBox, null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuildWithTwoStopsOutsideAndNoneTest() {
Rectangle targetBoundingBox = new Rectangle(50f, 450f, 300f, 300f);
AbstractLinearGradientBuilder gradientBuilder = new LinearGradientBuilder().SetGradientVector(targetBoundingBox
.GetLeft() + 100f, targetBoundingBox.GetBottom() + 100f, targetBoundingBox.GetRight() - 100f, targetBoundingBox
.GetTop() - 100f).SetSpreadMethod(GradientSpreadMethod.NONE).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), -1.5d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.BLUE.GetColorValue(), 2.5d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfs("buildWithTwoStopsOutsideAndNoneTest.pdf", targetBoundingBox, null, gradientBuilder
);
}
private void GenerateAndComparePdfs(String fileName, Rectangle toDraw, AffineTransform transform, AbstractLinearGradientBuilder
gradientBuilder) {
String outPdfPath = destinationFolder + fileName;
using (PdfDocument pdfDoc = new PdfDocument(new PdfWriter(new FileInfo(outPdfPath)))) {
PdfCanvas canvas = new PdfCanvas(pdfDoc.AddNewPage());
if (transform != null) {
canvas.ConcatMatrix(transform);
}
canvas.SetFillColor(gradientBuilder.BuildColor(toDraw, transform, pdfDoc)).SetStrokeColor(ColorConstants.BLACK
).Rectangle(toDraw).FillStroke();
}
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdfPath, sourceFolder + "cmp_" + fileName
, destinationFolder, "diff"));
}
private void GenerateAndComparePdfsWithoutArgumentToBuild(String fileName, Rectangle toDraw, AbstractLinearGradientBuilder
gradientBuilder) {
String outPdfPath = destinationFolder + fileName;
using (PdfDocument pdfDoc = new PdfDocument(new PdfWriter(new FileInfo(outPdfPath)))) {
PdfCanvas canvas = new PdfCanvas(pdfDoc.AddNewPage());
canvas.SetFillColor(gradientBuilder.BuildColor(null, null, pdfDoc)).SetStrokeColor(ColorConstants.BLACK).Rectangle
(toDraw).FillStroke();
}
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdfPath, sourceFolder + "cmp_" + fileName
, destinationFolder, "diff"));
}
}
}

View File

@@ -0,0 +1,264 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using System.IO;
using TSpdf.Kernel.Colors;
using TSpdf.Kernel.Geom;
using TSpdf.Kernel.Pdf;
using TSpdf.Kernel.Pdf.Canvas;
using TSpdf.Kernel.Utils;
using TSpdf.Test;
namespace TSpdf.Kernel.Colors.Gradients {
/// <summary>This test class focuses on different types of linear gradient coordinates vector strategies.</summary>
/// <remarks>
/// This test class focuses on different types of linear gradient coordinates vector strategies.
/// Tests related to stop colors work omitted here as they would be equivalent to tests in
/// <see cref="LinearGradientBuilderTest"/>
/// </remarks>
[NUnit.Framework.Category("IntegrationTest")]
public class StrategyBasedLinearGradientBuilderTest : ExtendedTSpdfTest {
public static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/colors/gradients/StrategyBasedLinearGradientBuilderTest/";
public static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/colors/gradients/StrategyBasedLinearGradientBuilderTest/";
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
CreateOrClearDestinationFolder(destinationFolder);
}
[NUnit.Framework.Test]
public virtual void NoSettersTest() {
NUnit.Framework.Assert.IsNull(new StrategyBasedLinearGradientBuilder().BuildColor(new Rectangle(50f, 450f,
500f, 300f), null, null));
}
[NUnit.Framework.Test]
public virtual void NoRectangleTest() {
NUnit.Framework.Assert.IsNull(new StrategyBasedLinearGradientBuilder().AddColorStop(new GradientColorStop(
ColorConstants.RED.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.GREEN.GetColorValue(), 0.5, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType.RELATIVE)).BuildColor(null, null
, null));
}
[NUnit.Framework.Test]
public virtual void NoStrategyProvidedTest() {
AbstractLinearGradientBuilder gradientBuilder = new StrategyBasedLinearGradientBuilder().AddColorStop(new
GradientColorStop(ColorConstants.RED.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop
(new GradientColorStop(ColorConstants.GREEN.GetColorValue(), 0.5, GradientColorStop.OffsetType.RELATIVE
)).AddColorStop(new GradientColorStop(ColorConstants.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType
.RELATIVE));
GenerateAndComparePdfs("noStrategyProvidedTest.pdf", null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuilderToRightTest() {
AbstractLinearGradientBuilder gradientBuilder = new StrategyBasedLinearGradientBuilder().SetGradientDirectionAsStrategy
(StrategyBasedLinearGradientBuilder.GradientStrategy.TO_RIGHT).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants
.GREEN.GetColorValue(), 0.5, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfs("builderToRightTest.pdf", null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuilderToLeftTest() {
AbstractLinearGradientBuilder gradientBuilder = new StrategyBasedLinearGradientBuilder().SetGradientDirectionAsStrategy
(StrategyBasedLinearGradientBuilder.GradientStrategy.TO_LEFT).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants
.GREEN.GetColorValue(), 0.5, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfs("builderToLeftTest.pdf", null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuilderToBottomTest() {
AbstractLinearGradientBuilder gradientBuilder = new StrategyBasedLinearGradientBuilder().SetGradientDirectionAsStrategy
(StrategyBasedLinearGradientBuilder.GradientStrategy.TO_BOTTOM).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants
.GREEN.GetColorValue(), 0.5, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfs("builderToBottomTest.pdf", null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuilderToBottomRightTest() {
AbstractLinearGradientBuilder gradientBuilder = new StrategyBasedLinearGradientBuilder().SetGradientDirectionAsStrategy
(StrategyBasedLinearGradientBuilder.GradientStrategy.TO_BOTTOM_RIGHT).AddColorStop(new GradientColorStop
(ColorConstants.RED.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.GREEN.GetColorValue(), 0.5, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfs("builderToBottomRightTest.pdf", null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuilderToBottomLeftTest() {
AbstractLinearGradientBuilder gradientBuilder = new StrategyBasedLinearGradientBuilder().SetGradientDirectionAsStrategy
(StrategyBasedLinearGradientBuilder.GradientStrategy.TO_BOTTOM_LEFT).AddColorStop(new GradientColorStop
(ColorConstants.RED.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.GREEN.GetColorValue(), 0.5, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfs("builderToBottomLeftTest.pdf", null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuilderToTopTest() {
AbstractLinearGradientBuilder gradientBuilder = new StrategyBasedLinearGradientBuilder().SetGradientDirectionAsStrategy
(StrategyBasedLinearGradientBuilder.GradientStrategy.TO_TOP).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants
.GREEN.GetColorValue(), 0.5, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfs("builderToTopTest.pdf", null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuilderToTopRightTest() {
AbstractLinearGradientBuilder gradientBuilder = new StrategyBasedLinearGradientBuilder().SetGradientDirectionAsStrategy
(StrategyBasedLinearGradientBuilder.GradientStrategy.TO_TOP_RIGHT).AddColorStop(new GradientColorStop(
ColorConstants.RED.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.GREEN.GetColorValue(), 0.5, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfs("builderToTopRightTest.pdf", null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuilderToTopLeftTest() {
AbstractLinearGradientBuilder gradientBuilder = new StrategyBasedLinearGradientBuilder().SetGradientDirectionAsStrategy
(StrategyBasedLinearGradientBuilder.GradientStrategy.TO_TOP_LEFT).AddColorStop(new GradientColorStop(ColorConstants
.RED.GetColorValue(), 0d, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants
.GREEN.GetColorValue(), 0.5, GradientColorStop.OffsetType.RELATIVE)).AddColorStop(new GradientColorStop
(ColorConstants.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType.RELATIVE));
GenerateAndComparePdfs("builderToTopLeftTest.pdf", null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuilderZeroAngleTest() {
AbstractLinearGradientBuilder gradientBuilder = new StrategyBasedLinearGradientBuilder().SetGradientDirectionAsCentralRotationAngle
(0d).AddColorStop(new GradientColorStop(ColorConstants.RED.GetColorValue(), 0d, GradientColorStop.OffsetType
.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants.GREEN.GetColorValue(), 0.5, GradientColorStop.OffsetType
.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType
.RELATIVE));
GenerateAndComparePdfs("builderZeroAngleTest.pdf", null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuilderPositiveAngleTest() {
AbstractLinearGradientBuilder gradientBuilder = new StrategyBasedLinearGradientBuilder().SetGradientDirectionAsCentralRotationAngle
(Math.PI / 3).AddColorStop(new GradientColorStop(ColorConstants.RED.GetColorValue(), 0d, GradientColorStop.OffsetType
.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants.GREEN.GetColorValue(), 0.5, GradientColorStop.OffsetType
.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType
.RELATIVE));
GenerateAndComparePdfs("builderPositiveAngleTest.pdf", null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuilderNegativeAngleTest() {
AbstractLinearGradientBuilder gradientBuilder = new StrategyBasedLinearGradientBuilder().SetGradientDirectionAsCentralRotationAngle
(-Math.PI / 3).AddColorStop(new GradientColorStop(ColorConstants.RED.GetColorValue(), 0d, GradientColorStop.OffsetType
.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants.GREEN.GetColorValue(), 0.5, GradientColorStop.OffsetType
.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType
.RELATIVE));
GenerateAndComparePdfs("builderNegativeAngleTest.pdf", null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuilderWithNoneSpreadingAndCanvasTransformTest() {
AbstractLinearGradientBuilder gradientBuilder = new StrategyBasedLinearGradientBuilder().SetGradientDirectionAsStrategy
(StrategyBasedLinearGradientBuilder.GradientStrategy.TO_RIGHT).SetSpreadMethod(GradientSpreadMethod.NONE
).AddColorStop(new GradientColorStop(ColorConstants.RED.GetColorValue(), 0d, GradientColorStop.OffsetType
.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants.GREEN.GetColorValue(), 0.5, GradientColorStop.OffsetType
.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants.BLUE.GetColorValue(), 1d, GradientColorStop.OffsetType
.RELATIVE));
AffineTransform canvasTransform = AffineTransform.GetTranslateInstance(50, -50);
canvasTransform.Scale(0.8, 1.1);
canvasTransform.Rotate(Math.PI / 3, 400f, 550f);
GenerateAndComparePdfs("builderWithNoneSpreadingAndCanvasTransformTest.pdf", canvasTransform, gradientBuilder
);
}
[NUnit.Framework.Test]
public virtual void BuilderWithToCornerAndInnerStopsAndNoneSpreadingTest() {
AbstractLinearGradientBuilder gradientBuilder = new StrategyBasedLinearGradientBuilder().SetGradientDirectionAsStrategy
(StrategyBasedLinearGradientBuilder.GradientStrategy.TO_TOP_RIGHT).SetSpreadMethod(GradientSpreadMethod
.NONE).AddColorStop(new GradientColorStop(ColorConstants.RED.GetColorValue(), 0.3d, GradientColorStop.OffsetType
.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants.GREEN.GetColorValue(), 0.4, GradientColorStop.OffsetType
.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants.BLUE.GetColorValue(), 0.5d, GradientColorStop.OffsetType
.RELATIVE));
GenerateAndComparePdfs("builderWithToCornerAndInnerStopsAndNoneSpreadingTest.pdf", null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuilderWithToCornerAndInnerStopsAndPadSpreadingTest() {
AbstractLinearGradientBuilder gradientBuilder = new StrategyBasedLinearGradientBuilder().SetGradientDirectionAsStrategy
(StrategyBasedLinearGradientBuilder.GradientStrategy.TO_TOP_RIGHT).SetSpreadMethod(GradientSpreadMethod
.PAD).AddColorStop(new GradientColorStop(ColorConstants.RED.GetColorValue(), 0.3d, GradientColorStop.OffsetType
.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants.GREEN.GetColorValue(), 0.4, GradientColorStop.OffsetType
.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants.BLUE.GetColorValue(), 0.5d, GradientColorStop.OffsetType
.RELATIVE));
GenerateAndComparePdfs("builderWithToCornerAndInnerStopsAndPadSpreadingTest.pdf", null, gradientBuilder);
}
[NUnit.Framework.Test]
public virtual void BuilderWithToCornerAndInnerStopsAndReflectSpreadingTest() {
AbstractLinearGradientBuilder gradientBuilder = new StrategyBasedLinearGradientBuilder().SetGradientDirectionAsStrategy
(StrategyBasedLinearGradientBuilder.GradientStrategy.TO_TOP_RIGHT).SetSpreadMethod(GradientSpreadMethod
.REFLECT).AddColorStop(new GradientColorStop(ColorConstants.RED.GetColorValue(), 0.3d, GradientColorStop.OffsetType
.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants.GREEN.GetColorValue(), 0.4, GradientColorStop.OffsetType
.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants.BLUE.GetColorValue(), 0.5d, GradientColorStop.OffsetType
.RELATIVE));
GenerateAndComparePdfs("builderWithToCornerAndInnerStopsAndReflectSpreadingTest.pdf", null, gradientBuilder
);
}
[NUnit.Framework.Test]
public virtual void BuilderWithToCornerAndInnerStopsAndRepeatSpreadingTest() {
AbstractLinearGradientBuilder gradientBuilder = new StrategyBasedLinearGradientBuilder().SetGradientDirectionAsStrategy
(StrategyBasedLinearGradientBuilder.GradientStrategy.TO_TOP_RIGHT).SetSpreadMethod(GradientSpreadMethod
.REPEAT).AddColorStop(new GradientColorStop(ColorConstants.RED.GetColorValue(), 0.3d, GradientColorStop.OffsetType
.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants.GREEN.GetColorValue(), 0.4, GradientColorStop.OffsetType
.RELATIVE)).AddColorStop(new GradientColorStop(ColorConstants.BLUE.GetColorValue(), 0.5d, GradientColorStop.OffsetType
.RELATIVE));
GenerateAndComparePdfs("builderWithToCornerAndInnerStopsAndRepeatSpreadingTest.pdf", null, gradientBuilder
);
}
private void GenerateAndComparePdfs(String fileName, AffineTransform transform, AbstractLinearGradientBuilder
gradientBuilder) {
String outPdfPath = destinationFolder + fileName;
using (PdfDocument pdfDoc = new PdfDocument(new PdfWriter(new FileInfo(outPdfPath)))) {
PdfCanvas canvas = new PdfCanvas(pdfDoc.AddNewPage());
if (transform != null) {
canvas.ConcatMatrix(transform);
}
Rectangle toDraw = new Rectangle(50f, 450f, 500f, 300f);
canvas.SetFillColor(gradientBuilder.BuildColor(toDraw, transform, pdfDoc)).SetStrokeColor(ColorConstants.BLACK
).Rectangle(toDraw).FillStroke();
}
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdfPath, sourceFolder + "cmp_" + fileName
, destinationFolder, "diff"));
}
}
}

View File

@@ -0,0 +1,60 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.Bouncycastleconnector;
using TSpdf.Commons.Bouncycastle;
using TSpdf.Commons.Bouncycastle.Asn1;
using TSpdf.Commons.Utils;
using TSpdf.IO.Source;
using TSpdf.Kernel.Exceptions;
using TSpdf.Test;
namespace TSpdf.Kernel.Crypto {
[NUnit.Framework.Category("BouncyCastleUnitTest")]
public class CryptoUtilTest : ExtendedTSpdfTest {
private static readonly IBouncyCastleFactory FACTORY = BouncyCastleFactoryCreator.GetFactory();
[NUnit.Framework.Test]
public virtual void CreateBerStreamTest() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IASN1OutputStream stream = CryptoUtil.CreateAsn1OutputStream(baos, FACTORY.CreateASN1Encoding().GetBer());
NUnit.Framework.Assert.IsNotNull(stream);
}
[NUnit.Framework.Test]
public virtual void CreateDerStreamTest() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IASN1OutputStream stream = CryptoUtil.CreateAsn1OutputStream(baos, FACTORY.CreateASN1Encoding().GetDer());
NUnit.Framework.Assert.IsNotNull(stream);
}
[NUnit.Framework.Test]
public virtual void CreateUnsupportedEncodingStreamTest() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Exception e = NUnit.Framework.Assert.Catch(typeof(NotSupportedException), () => CryptoUtil.CreateAsn1OutputStream
(baos, "DL"));
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(KernelExceptionMessageConstant.UNSUPPORTED_ASN1_ENCODING
, "DL"), e.Message);
}
}
}

View File

@@ -0,0 +1,108 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using NUnit.Framework;
using TSpdf.Bouncycastleconnector;
using TSpdf.Commons.Bouncycastle;
using TSpdf.Kernel.Logs;
using TSpdf.Kernel.Pdf;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.Kernel.Crypto {
[NUnit.Framework.Category("BouncyCastleIntegrationTest")]
public class EncryptionInApprovedModeTest : ExtendedTSpdfTest {
private static readonly IBouncyCastleFactory FACTORY = BouncyCastleFactoryCreator.GetFactory();
public static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/crypto" + "/EncryptionInApprovedModeTest/";
public static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/crypto" + "/EncryptionInApprovedModeTest/";
/// <summary>User password.</summary>
public static byte[] USER = "Hello".GetBytes(TSpdf.Commons.Utils.EncodingUtil.ISO_8859_1);
/// <summary>Owner password.</summary>
public static byte[] OWNER = "World".GetBytes(TSpdf.Commons.Utils.EncodingUtil.ISO_8859_1);
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
NUnit.Framework.Assume.That(FACTORY.IsInApprovedOnlyMode());
CreateOrClearDestinationFolder(destinationFolder);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT)]
public virtual void CheckMD5LogMessageWhileReadingPdfTest() {
String fileName = "checkMD5LogMessageWhileReadingPdf.pdf";
using (PdfDocument document = new PdfDocument(new PdfReader(sourceFolder + fileName))) {
}
}
// this test checks log message
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT)]
public virtual void CheckMD5LogMessageWhileCreatingPdfTest() {
String fileName = "checkMD5LogMessageWhileCreatingPdf.pdf";
using (PdfDocument document = new PdfDocument(new PdfWriter(destinationFolder + fileName, new WriterProperties
().SetStandardEncryption(USER, OWNER, EncryptionConstants.ALLOW_SCREENREADERS, EncryptionConstants.ENCRYPTION_AES_256
).AddXmpMetadata()))) {
}
}
// this test checks log message
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Count = 3)]
public virtual void CheckMD5LogMessageForEachPdfTest() {
String fileName = "checkMD5LogMessageForEachPdf.pdf";
for (int i = 0; i < 3; ++i) {
using (PdfDocument document = new PdfDocument(new PdfWriter(destinationFolder + fileName, new WriterProperties
().SetStandardEncryption(USER, OWNER, EncryptionConstants.ALLOW_SCREENREADERS, EncryptionConstants.ENCRYPTION_AES_256
).AddXmpMetadata()))) {
}
}
}
// this test checks log message
}
}

View File

@@ -0,0 +1,777 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.IO;
using NUnit.Framework;
using TSpdf.Bouncycastleconnector;
using TSpdf.Commons.Bouncycastle;
using TSpdf.Commons.Bouncycastle.Cert;
using TSpdf.Commons.Bouncycastle.Crypto;
using TSpdf.IO.Font.Constants;
using TSpdf.Kernel.Exceptions;
using TSpdf.Kernel.Font;
using TSpdf.Kernel.Logs;
using TSpdf.Kernel.Pdf;
using TSpdf.Kernel.Pdf.Filespec;
using TSpdf.Kernel.Utils;
using TSpdf.Kernel.XMP;
using TSpdf.Kernel.XMP.Properties;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.Kernel.Crypto {
/// <summary>
/// Due to import control restrictions by the governments of a few countries,
/// the encryption libraries shipped by default with the Java SDK restrict the
/// length, and as a result the strength, of encryption keys.
/// </summary>
/// <remarks>
/// Due to import control restrictions by the governments of a few countries,
/// the encryption libraries shipped by default with the Java SDK restrict the
/// length, and as a result the strength, of encryption keys. Be aware that in
/// this test by using
/// <see cref="TSpdf.Test.TSpdfTest.RemoveCryptographyRestrictions()"/>
/// we
/// remove cryptography restrictions via reflection for testing purposes.
/// <br/>
/// For more conventional way of solving this problem you need to replace the
/// default security JARs in your Java installation with the Java Cryptography
/// Extension (JCE) Unlimited Strength Jurisdiction Policy Files. These JARs
/// are available for download from http://java.oracle.com/ in eligible countries.
/// </remarks>
[NUnit.Framework.Category("BouncyCastleIntegrationTest")]
public class PdfEncryptionTest : ExtendedTSpdfTest {
private static readonly IBouncyCastleFactory FACTORY = BouncyCastleFactoryCreator.GetFactory();
public static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/crypto/PdfEncryptionTest/";
public static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/crypto/PdfEncryptionTest/";
public static readonly char[] PRIVATE_KEY_PASS = "testpassphrase".ToCharArray();
public static readonly String CERT = sourceFolder + "test.cer";
public static readonly String PRIVATE_KEY = sourceFolder + "test.pem";
internal const String pageTextContent = "Hello world!";
// Custom entry in Info dictionary is used because standard entried are gone into metadata in PDF 2.0
internal const String customInfoEntryKey = "Custom";
internal const String customInfoEntryValue = "String";
/// <summary>User password.</summary>
public static byte[] USER = "Hello".GetBytes(TSpdf.Commons.Utils.EncodingUtil.ISO_8859_1);
/// <summary>Owner password.</summary>
public static byte[] OWNER = "World".GetBytes(TSpdf.Commons.Utils.EncodingUtil.ISO_8859_1);
private IPrivateKey privateKey;
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
CreateOrClearDestinationFolder(destinationFolder);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void EncryptWithPasswordStandard128() {
String filename = "encryptWithPasswordStandard128.pdf";
int encryptionType = EncryptionConstants.STANDARD_ENCRYPTION_128;
EncryptWithPassword2(filename, encryptionType, CompressionConstants.DEFAULT_COMPRESSION);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void EncryptWithPasswordStandard40() {
String filename = "encryptWithPasswordStandard40.pdf";
int encryptionType = EncryptionConstants.STANDARD_ENCRYPTION_40;
EncryptWithPassword2(filename, encryptionType, CompressionConstants.DEFAULT_COMPRESSION);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void EncryptWithPasswordStandard128NoCompression() {
String filename = "encryptWithPasswordStandard128NoCompression.pdf";
int encryptionType = EncryptionConstants.STANDARD_ENCRYPTION_128;
EncryptWithPassword2(filename, encryptionType, CompressionConstants.NO_COMPRESSION);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void EncryptWithPasswordStandard40NoCompression() {
String filename = "encryptWithPasswordStandard40NoCompression.pdf";
int encryptionType = EncryptionConstants.STANDARD_ENCRYPTION_40;
EncryptWithPassword2(filename, encryptionType, CompressionConstants.NO_COMPRESSION);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void EncryptWithPasswordAes128() {
String filename = "encryptWithPasswordAes128.pdf";
int encryptionType = EncryptionConstants.ENCRYPTION_AES_128;
EncryptWithPassword2(filename, encryptionType, CompressionConstants.DEFAULT_COMPRESSION);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void EncryptWithPasswordAes256() {
String filename = "encryptWithPasswordAes256.pdf";
int encryptionType = EncryptionConstants.ENCRYPTION_AES_256;
EncryptWithPassword2(filename, encryptionType, CompressionConstants.DEFAULT_COMPRESSION);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void EncryptWithPasswordAes128NoCompression() {
String filename = "encryptWithPasswordAes128NoCompression.pdf";
int encryptionType = EncryptionConstants.ENCRYPTION_AES_128;
EncryptWithPassword2(filename, encryptionType, CompressionConstants.NO_COMPRESSION);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void EncryptWithPasswordAes256NoCompression() {
String filename = "encryptWithPasswordAes256NoCompression.pdf";
int encryptionType = EncryptionConstants.ENCRYPTION_AES_256;
EncryptWithPassword2(filename, encryptionType, CompressionConstants.NO_COMPRESSION);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void EncryptWithCertificateStandard128() {
String filename = "encryptWithCertificateStandard128.pdf";
int encryptionType = EncryptionConstants.STANDARD_ENCRYPTION_128;
EncryptWithCertificate(filename, encryptionType, CompressionConstants.DEFAULT_COMPRESSION);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void EncryptWithCertificateStandard40() {
String filename = "encryptWithCertificateStandard40.pdf";
int encryptionType = EncryptionConstants.STANDARD_ENCRYPTION_40;
EncryptWithCertificate(filename, encryptionType, CompressionConstants.DEFAULT_COMPRESSION);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void EncryptWithCertificateStandard128NoCompression() {
String filename = "encryptWithCertificateStandard128NoCompression.pdf";
int encryptionType = EncryptionConstants.STANDARD_ENCRYPTION_128;
EncryptWithCertificate(filename, encryptionType, CompressionConstants.NO_COMPRESSION);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void EncryptWithCertificateStandard40NoCompression() {
String filename = "encryptWithCertificateStandard40NoCompression.pdf";
int encryptionType = EncryptionConstants.STANDARD_ENCRYPTION_40;
EncryptWithCertificate(filename, encryptionType, CompressionConstants.NO_COMPRESSION);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void EncryptWithCertificateAes128() {
String filename = "encryptWithCertificateAes128.pdf";
int encryptionType = EncryptionConstants.ENCRYPTION_AES_128;
EncryptWithCertificate(filename, encryptionType, CompressionConstants.DEFAULT_COMPRESSION);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void EncryptWithCertificateAes256() {
String filename = "encryptWithCertificateAes256.pdf";
int encryptionType = EncryptionConstants.ENCRYPTION_AES_256;
EncryptWithCertificate(filename, encryptionType, CompressionConstants.DEFAULT_COMPRESSION);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void EncryptWithCertificateAes128NoCompression() {
String filename = "encryptWithCertificateAes128NoCompression.pdf";
int encryptionType = EncryptionConstants.ENCRYPTION_AES_128;
EncryptWithCertificate(filename, encryptionType, CompressionConstants.NO_COMPRESSION);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void EncryptWithCertificateAes256NoCompression() {
String filename = "encryptWithCertificateAes256NoCompression.pdf";
int encryptionType = EncryptionConstants.ENCRYPTION_AES_256;
EncryptWithCertificate(filename, encryptionType, CompressionConstants.NO_COMPRESSION);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void OpenEncryptedDocWithoutPassword() {
using (PdfReader reader = new PdfReader(sourceFolder + "encryptedWithPasswordStandard40.pdf")) {
Exception e = NUnit.Framework.Assert.Catch(typeof(BadPasswordException), () => new PdfDocument(reader));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.BAD_USER_PASSWORD, e.Message);
}
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void OpenEncryptedDocWithWrongPassword() {
using (PdfReader reader = new PdfReader(sourceFolder + "encryptedWithPasswordStandard40.pdf", new ReaderProperties
().SetPassword("wrong_password".GetBytes(TSpdf.Commons.Utils.EncodingUtil.ISO_8859_1)))) {
Exception e = NUnit.Framework.Assert.Catch(typeof(BadPasswordException), () => new PdfDocument(reader));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.BAD_USER_PASSWORD, e.Message);
}
}
[NUnit.Framework.Test]
public virtual void OpenEncryptedDocWithoutCertificate() {
using (PdfReader reader = new PdfReader(sourceFolder + "encryptedWithCertificateAes128.pdf")) {
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => new PdfDocument(reader));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.CERTIFICATE_IS_NOT_PROVIDED_DOCUMENT_IS_ENCRYPTED_WITH_PUBLIC_KEY_CERTIFICATE
, e.Message);
}
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void OpenEncryptedDocWithoutPrivateKey() {
using (PdfReader reader = new PdfReader(sourceFolder + "encryptedWithCertificateAes128.pdf", new ReaderProperties
().SetPublicKeySecurityParams(GetPublicCertificate(sourceFolder + "wrong.cer"), null))) {
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => new PdfDocument(reader));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.BAD_CERTIFICATE_AND_KEY, e.Message);
}
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void OpenEncryptedDocWithWrongCertificate() {
using (PdfReader reader = new PdfReader(sourceFolder + "encryptedWithCertificateAes128.pdf", new ReaderProperties
().SetPublicKeySecurityParams(GetPublicCertificate(sourceFolder + "wrong.cer"), GetPrivateKey()))) {
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => new PdfDocument(reader));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.BAD_CERTIFICATE_AND_KEY, e.Message);
}
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void OpenEncryptedDocWithWrongPrivateKey() {
using (PdfReader reader = new PdfReader(sourceFolder + "encryptedWithCertificateAes128.pdf", new ReaderProperties
().SetPublicKeySecurityParams(GetPublicCertificate(CERT), PemFileHelper.ReadPrivateKeyFromPemFile(new
FileStream(sourceFolder + "wrong.pem", FileMode.Open, FileAccess.Read), PRIVATE_KEY_PASS)))) {
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => new PdfDocument(reader));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.PDF_DECRYPTION, e.Message);
}
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void OpenEncryptedDocWithWrongCertificateAndPrivateKey() {
using (PdfReader reader = new PdfReader(sourceFolder + "encryptedWithCertificateAes128.pdf", new ReaderProperties
().SetPublicKeySecurityParams(GetPublicCertificate(sourceFolder + "wrong.cer"), PemFileHelper.ReadPrivateKeyFromPemFile
(new FileStream(sourceFolder + "wrong.pem", FileMode.Open, FileAccess.Read), PRIVATE_KEY_PASS)))) {
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => new PdfDocument(reader));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.BAD_CERTIFICATE_AND_KEY, e.Message);
}
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void MetadataReadingInEncryptedDoc() {
PdfReader reader = new PdfReader(sourceFolder + "encryptedWithPlainMetadata.pdf", new ReaderProperties().SetPassword
(OWNER));
PdfDocument doc = new PdfDocument(reader);
XMPMeta xmpMeta = XMPMetaFactory.ParseFromBuffer(doc.GetXmpMetadata());
XMPProperty creatorToolXmp = xmpMeta.GetProperty(XMPConst.NS_XMP, "CreatorTool");
doc.Close();
NUnit.Framework.Assert.IsNotNull(creatorToolXmp);
NUnit.Framework.Assert.AreEqual("TSpdf 7", creatorToolXmp.GetValue());
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void CopyEncryptedDocument() {
PdfDocument srcDoc = new PdfDocument(new PdfReader(sourceFolder + "encryptedWithCertificateAes128.pdf", new
ReaderProperties().SetPublicKeySecurityParams(GetPublicCertificate(CERT), GetPrivateKey())));
String fileName = "copiedEncryptedDoc.pdf";
PdfDocument destDoc = new PdfDocument(new PdfWriter(destinationFolder + fileName));
srcDoc.CopyPagesTo(1, 1, destDoc);
PdfDictionary srcInfo = srcDoc.GetTrailer().GetAsDictionary(PdfName.Info);
PdfDictionary destInfo = destDoc.GetTrailer().GetAsDictionary(PdfName.Info);
foreach (PdfName srcInfoKey in srcInfo.KeySet()) {
destInfo.Put((PdfName)srcInfoKey.CopyTo(destDoc), srcInfo.Get(srcInfoKey).CopyTo(destDoc));
}
srcDoc.Close();
destDoc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + fileName, sourceFolder
+ "cmp_" + fileName, destinationFolder, "diff_"));
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void OpenDocNoUserPassword() {
String fileName = "noUserPassword.pdf";
PdfDocument document = new PdfDocument(new PdfReader(sourceFolder + fileName));
document.Close();
CheckDecryptedWithPasswordContent(sourceFolder + fileName, null, pageTextContent);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void StampDocNoUserPassword() {
String fileName = "stampedNoPassword.pdf";
using (PdfReader reader = new PdfReader(sourceFolder + "noUserPassword.pdf")) {
using (PdfWriter writer = new PdfWriter(destinationFolder + fileName)) {
Exception e = NUnit.Framework.Assert.Catch(typeof(BadPasswordException), () => new PdfDocument(reader, writer
));
NUnit.Framework.Assert.AreEqual(BadPasswordException.PdfReaderNotOpenedWithOwnerPassword, e.Message);
}
}
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void EncryptWithPasswordAes128EmbeddedFilesOnly() {
String filename = "encryptWithPasswordAes128EmbeddedFilesOnly.pdf";
int encryptionType = EncryptionConstants.ENCRYPTION_AES_128 | EncryptionConstants.EMBEDDED_FILES_ONLY;
String outFileName = destinationFolder + filename;
int permissions = EncryptionConstants.ALLOW_SCREENREADERS;
PdfWriter writer = new PdfWriter(outFileName, new WriterProperties().SetStandardEncryption(USER, OWNER, permissions
, encryptionType).AddXmpMetadata());
PdfDocument document = new PdfDocument(writer);
document.GetDocumentInfo().SetMoreInfo(customInfoEntryKey, customInfoEntryValue);
PdfPage page = document.AddNewPage();
String textContent = "Hello world!";
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;
CheckDecryptedWithPasswordContent(destinationFolder + filename, OWNER, textContent, ERROR_IS_EXPECTED);
CheckDecryptedWithPasswordContent(destinationFolder + filename, USER, textContent, ERROR_IS_EXPECTED);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void EncryptAes256Pdf2NotEncryptMetadata() {
String filename = "encryptAes256Pdf2NotEncryptMetadata.pdf";
int encryptionType = EncryptionConstants.ENCRYPTION_AES_256 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA;
EncryptWithPassword2(filename, encryptionType, CompressionConstants.DEFAULT_COMPRESSION);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void EncryptAes256Pdf2NotEncryptMetadata02() {
String filename = "encryptAes256Pdf2NotEncryptMetadata02.pdf";
int encryptionType = EncryptionConstants.ENCRYPTION_AES_256 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA;
EncryptWithPassword(filename, encryptionType, CompressionConstants.DEFAULT_COMPRESSION, true);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void EncryptAes256EncryptedStampingPreserve() {
String filename = "encryptAes256EncryptedStampingPreserve.pdf";
String src = sourceFolder + "encryptedWithPlainMetadata.pdf";
String @out = destinationFolder + filename;
PdfDocument pdfDoc = new PdfDocument(new PdfReader(src, new ReaderProperties().SetPassword(OWNER)), new PdfWriter
(@out, new WriterProperties()), new StampingProperties().PreserveEncryption());
pdfDoc.Close();
CompareTool compareTool = new CompareTool().EnableEncryptionCompare();
String compareResult = compareTool.CompareByContent(@out, sourceFolder + "cmp_" + filename, destinationFolder
, "diff_", USER, USER);
if (compareResult != null) {
NUnit.Framework.Assert.Fail(compareResult);
}
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void EncryptAes256EncryptedStampingUpdate() {
String filename = "encryptAes256EncryptedStampingUpdate.pdf";
String src = sourceFolder + "encryptedWithPlainMetadata.pdf";
String @out = destinationFolder + filename;
PdfDocument pdfDoc = new PdfDocument(new PdfReader(src, new ReaderProperties().SetPassword(OWNER)), new PdfWriter
(@out, new WriterProperties().SetStandardEncryption(USER, OWNER, EncryptionConstants.ALLOW_PRINTING, EncryptionConstants
.STANDARD_ENCRYPTION_40)), new StampingProperties());
pdfDoc.Close();
CompareTool compareTool = new CompareTool().EnableEncryptionCompare();
String compareResult = compareTool.CompareByContent(@out, sourceFolder + "cmp_" + filename, destinationFolder
, "diff_", USER, USER);
if (compareResult != null) {
NUnit.Framework.Assert.Fail(compareResult);
}
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void EncryptAes256FullCompression() {
String filename = "encryptAes256FullCompression.pdf";
int encryptionType = EncryptionConstants.ENCRYPTION_AES_256;
EncryptWithPassword2(filename, encryptionType, CompressionConstants.DEFAULT_COMPRESSION, true);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void EncryptWithPasswordAes256Pdf2() {
String filename = "encryptWithPasswordAes256Pdf2.pdf";
int encryptionType = EncryptionConstants.ENCRYPTION_AES_256;
EncryptWithPassword2(filename, encryptionType, CompressionConstants.DEFAULT_COMPRESSION, true);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
[LogMessage(VersionConforming.DEPRECATED_ENCRYPTION_ALGORITHMS)]
public virtual void EncryptWithPasswordAes128Pdf2() {
String filename = "encryptWithPasswordAes128Pdf2.pdf";
int encryptionType = EncryptionConstants.ENCRYPTION_AES_128;
EncryptWithPassword2(filename, encryptionType, CompressionConstants.DEFAULT_COMPRESSION, true);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
[LogMessage(VersionConforming.DEPRECATED_ENCRYPTION_ALGORITHMS)]
public virtual void StampAndUpdateVersionPreserveStandard40() {
String filename = "stampAndUpdateVersionPreserveStandard40.pdf";
PdfDocument doc = new PdfDocument(new PdfReader(sourceFolder + "encryptedWithPasswordStandard40.pdf", new
ReaderProperties().SetPassword(OWNER)), new PdfWriter(destinationFolder + filename, new WriterProperties
().SetPdfVersion(PdfVersion.PDF_2_0)), new StampingProperties().PreserveEncryption());
doc.Close();
CompareEncryptedPdf(filename);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
[LogMessage(VersionConforming.DEPRECATED_AES256_REVISION)]
public virtual void StampAndUpdateVersionPreserveAes256() {
String filename = "stampAndUpdateVersionPreserveAes256.pdf";
PdfDocument doc = new PdfDocument(new PdfReader(sourceFolder + "encryptedWithPasswordAes256.pdf", new ReaderProperties
().SetPassword(OWNER)), new PdfWriter(destinationFolder + filename, new WriterProperties().SetPdfVersion
(PdfVersion.PDF_2_0)), new StampingProperties().PreserveEncryption());
doc.Close();
CompareEncryptedPdf(filename);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void StampAndUpdateVersionNewAes256() {
String filename = "stampAndUpdateVersionNewAes256.pdf";
PdfDocument doc = new PdfDocument(new PdfReader(sourceFolder + "encryptedWithPasswordAes256.pdf", new ReaderProperties
().SetPassword(OWNER)), new PdfWriter(destinationFolder + filename, new WriterProperties().SetPdfVersion
(PdfVersion.PDF_2_0).SetStandardEncryption(USER, OWNER, 0, EncryptionConstants.ENCRYPTION_AES_256)));
doc.Close();
CompareEncryptedPdf(filename);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void EncryptAes256Pdf2Permissions() {
String filename = "encryptAes256Pdf2Permissions.pdf";
int permissions = EncryptionConstants.ALLOW_FILL_IN | EncryptionConstants.ALLOW_SCREENREADERS | EncryptionConstants
.ALLOW_DEGRADED_PRINTING;
PdfDocument doc = new PdfDocument(new PdfWriter(destinationFolder + filename, new WriterProperties().SetPdfVersion
(PdfVersion.PDF_2_0).SetStandardEncryption(USER, OWNER, permissions, EncryptionConstants.ENCRYPTION_AES_256
)));
doc.GetDocumentInfo().SetMoreInfo(customInfoEntryKey, customInfoEntryValue);
WriteTextBytesOnPageContent(doc.AddNewPage(), pageTextContent);
doc.Close();
CompareEncryptedPdf(filename);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void EncryptWithPasswordAes128NoMetadataCompression() {
String srcFilename = "srcEncryptWithPasswordAes128NoMetadataCompression.pdf";
PdfReader reader = new PdfReader(sourceFolder + srcFilename, new ReaderProperties());
WriterProperties props = new WriterProperties().SetStandardEncryption("superuser".GetBytes(), "superowner"
.GetBytes(), EncryptionConstants.ALLOW_PRINTING, EncryptionConstants.ENCRYPTION_AES_128 | EncryptionConstants
.DO_NOT_ENCRYPT_METADATA);
String outFilename = "encryptWithPasswordAes128NoMetadataCompression.pdf";
PdfWriter writer = new PdfWriter(destinationFolder + outFilename, props);
PdfDocument pdfDoc = new PdfDocument(reader, writer);
pdfDoc.Close();
CompareTool compareTool = new CompareTool();
compareTool.EnableEncryptionCompare();
compareTool.GetOutReaderProperties().SetPassword("superowner".GetBytes());
compareTool.GetCmpReaderProperties().SetPassword("superowner".GetBytes());
String outPdf = destinationFolder + outFilename;
String cmpPdf = sourceFolder + "cmp_" + outFilename;
NUnit.Framework.Assert.IsNull(compareTool.CompareByContent(outPdf, cmpPdf, destinationFolder, "diff_"));
}
[NUnit.Framework.Test]
public virtual void CheckMD5LogAbsenceInUnapprovedMode() {
NUnit.Framework.Assume.That(!FACTORY.IsInApprovedOnlyMode());
String fileName = "noUserPassword.pdf";
using (PdfDocument document = new PdfDocument(new PdfReader(sourceFolder + fileName))) {
}
}
// this test checks log message absence
public virtual void EncryptWithPassword2(String filename, int encryptionType, int compression) {
EncryptWithPassword2(filename, encryptionType, compression, false);
}
public virtual void EncryptWithPassword2(String filename, int encryptionType, int compression, bool isPdf2
) {
int permissions = EncryptionConstants.ALLOW_SCREENREADERS;
WriterProperties writerProperties = new WriterProperties().SetStandardEncryption(USER, OWNER, permissions,
encryptionType);
if (isPdf2) {
writerProperties.SetPdfVersion(PdfVersion.PDF_2_0);
}
PdfWriter writer = new PdfWriter(destinationFolder + filename, writerProperties.AddXmpMetadata());
writer.SetCompressionLevel(compression);
PdfDocument document = new PdfDocument(writer);
document.GetDocumentInfo().SetMoreInfo(customInfoEntryKey, customInfoEntryValue);
PdfPage page = document.AddNewPage();
WriteTextBytesOnPageContent(page, pageTextContent);
page.Flush();
document.Close();
CompareEncryptedPdf(filename);
CheckEncryptedWithPasswordDocumentStamping(filename, OWNER);
CheckEncryptedWithPasswordDocumentAppending(filename, OWNER);
}
public virtual void EncryptWithPassword(String filename, int encryptionType, int compression) {
EncryptWithPassword(filename, encryptionType, compression, false);
}
public virtual void EncryptWithPassword(String filename, int encryptionType, int compression, bool fullCompression
) {
String outFileName = destinationFolder + filename;
int permissions = EncryptionConstants.ALLOW_SCREENREADERS;
PdfWriter writer = new PdfWriter(outFileName, new WriterProperties().SetStandardEncryption(USER, OWNER, permissions
, encryptionType).AddXmpMetadata().SetFullCompressionMode(fullCompression));
writer.SetCompressionLevel(compression);
PdfDocument document = new PdfDocument(writer);
document.GetDocumentInfo().SetMoreInfo(customInfoEntryKey, customInfoEntryValue);
PdfPage page = document.AddNewPage();
WriteTextBytesOnPageContent(page, pageTextContent);
page.Flush();
document.Close();
CompareEncryptedPdf(filename);
CheckEncryptedWithPasswordDocumentStamping(filename, OWNER);
CheckEncryptedWithPasswordDocumentAppending(filename, OWNER);
}
public virtual void EncryptWithCertificate(String filename, int encryptionType, int compression) {
String outFileName = destinationFolder + filename;
int permissions = EncryptionConstants.ALLOW_SCREENREADERS;
IX509Certificate cert = GetPublicCertificate(CERT);
PdfWriter writer = new PdfWriter(outFileName, new WriterProperties().SetPublicKeyEncryption(new IX509Certificate
[] { cert }, new int[] { permissions }, encryptionType).AddXmpMetadata());
writer.SetCompressionLevel(compression);
PdfDocument document = new PdfDocument(writer);
document.GetDocumentInfo().SetMoreInfo(customInfoEntryKey, customInfoEntryValue);
PdfPage page = document.AddNewPage();
WriteTextBytesOnPageContent(page, pageTextContent);
page.Flush();
document.Close();
CheckDecryptedWithCertificateContent(filename, cert, pageTextContent);
CompareTool compareTool = new CompareTool().EnableEncryptionCompare();
compareTool.GetOutReaderProperties().SetPublicKeySecurityParams(cert, GetPrivateKey());
compareTool.GetCmpReaderProperties().SetPublicKeySecurityParams(cert, GetPrivateKey());
String compareResult = compareTool.CompareByContent(outFileName, sourceFolder + "cmp_" + filename, destinationFolder
, "diff_");
if (compareResult != null) {
NUnit.Framework.Assert.Fail(compareResult);
}
CheckEncryptedWithCertificateDocumentStamping(filename, cert);
CheckEncryptedWithCertificateDocumentAppending(filename, cert);
}
public virtual IX509Certificate GetPublicCertificate(String path) {
FileStream @is = new FileStream(path, FileMode.Open, FileAccess.Read);
return CryptoUtil.ReadPublicCertificate(@is);
}
public virtual IPrivateKey GetPrivateKey() {
if (privateKey == null) {
privateKey = PemFileHelper.ReadPrivateKeyFromPemFile(new FileStream(PRIVATE_KEY, FileMode.Open, FileAccess.Read
), PRIVATE_KEY_PASS);
}
return privateKey;
}
public static void CheckDecryptedWithPasswordContent(String src, byte[] password, String pageContent) {
CheckDecryptedWithPasswordContent(src, password, pageContent, false);
}
private static void CheckDecryptedWithPasswordContent(String src, byte[] password, String pageContent, bool
expectError) {
PdfReader reader = new PdfReader(src, new ReaderProperties().SetPassword(password));
PdfDocument document = new PdfDocument(reader);
PdfPage page = document.GetPage(1);
bool expectedContentFound = TSpdf.Commons.Utils.JavaUtil.GetStringForBytes(page.GetStreamBytes(0)).Contains
(pageContent);
String actualCustomInfoEntry = document.GetTrailer().GetAsDictionary(PdfName.Info).GetAsString(new PdfName
(customInfoEntryKey)).ToUnicodeString();
if (!expectError) {
NUnit.Framework.Assert.IsTrue(expectedContentFound, "Expected content: \n" + pageContent);
NUnit.Framework.Assert.AreEqual(customInfoEntryValue, actualCustomInfoEntry, "Encrypted custom");
}
else {
NUnit.Framework.Assert.IsFalse(expectedContentFound, "Expected content: \n" + pageContent);
NUnit.Framework.Assert.AreNotEqual(customInfoEntryValue, actualCustomInfoEntry, "Encrypted custom");
}
document.Close();
}
public virtual void CheckDecryptedWithCertificateContent(String filename, IX509Certificate certificate, String
pageContent) {
String src = destinationFolder + filename;
PdfReader reader = new PdfReader(src, new ReaderProperties().SetPublicKeySecurityParams(certificate, GetPrivateKey
()));
PdfDocument document = new PdfDocument(reader);
PdfPage page = document.GetPage(1);
String s = TSpdf.Commons.Utils.JavaUtil.GetStringForBytes(page.GetStreamBytes(0));
NUnit.Framework.Assert.IsTrue(s.Contains(pageContent), "Expected content: \n" + pageContent);
NUnit.Framework.Assert.AreEqual(customInfoEntryValue, document.GetTrailer().GetAsDictionary(PdfName.Info).
GetAsString(new PdfName(customInfoEntryKey)).ToUnicodeString(), "Encrypted custom");
document.Close();
}
// basically this is comparing content of decrypted by TSpdf document with content of encrypted document
public virtual void CheckEncryptedWithPasswordDocumentStamping(String filename, byte[] password) {
String srcFileName = destinationFolder + filename;
String outFileName = destinationFolder + "stamped_" + filename;
PdfReader reader = new PdfReader(srcFileName, new ReaderProperties().SetPassword(password));
PdfDocument document = new PdfDocument(reader, new PdfWriter(outFileName));
document.Close();
CompareTool compareTool = new CompareTool();
String compareResult = compareTool.CompareByContent(outFileName, sourceFolder + "cmp_" + filename, destinationFolder
, "diff_", USER, USER);
if (compareResult != null) {
NUnit.Framework.Assert.Fail(compareResult);
}
}
// basically this is comparing content of decrypted by TSpdf document with content of encrypted document
public virtual void CheckEncryptedWithCertificateDocumentStamping(String filename, IX509Certificate certificate
) {
String srcFileName = destinationFolder + filename;
String outFileName = destinationFolder + "stamped_" + filename;
PdfReader reader = new PdfReader(srcFileName, new ReaderProperties().SetPublicKeySecurityParams(certificate
, GetPrivateKey()));
PdfDocument document = new PdfDocument(reader, new PdfWriter(outFileName));
document.Close();
CompareTool compareTool = new CompareTool();
compareTool.GetCmpReaderProperties().SetPublicKeySecurityParams(certificate, GetPrivateKey());
String compareResult = compareTool.CompareByContent(outFileName, sourceFolder + "cmp_" + filename, destinationFolder
, "diff_");
if (compareResult != null) {
NUnit.Framework.Assert.Fail(compareResult);
}
}
public virtual void CheckEncryptedWithPasswordDocumentAppending(String filename, byte[] password) {
String srcFileName = destinationFolder + filename;
String outFileName = destinationFolder + "appended_" + filename;
PdfReader reader = new PdfReader(srcFileName, new ReaderProperties().SetPassword(password));
PdfDocument document = new PdfDocument(reader, new PdfWriter(outFileName), new StampingProperties().UseAppendMode
());
PdfPage newPage = document.AddNewPage();
newPage.Put(PdfName.Default, new PdfString("Hello world string"));
WriteTextBytesOnPageContent(newPage, "Hello world page_2!");
document.Close();
CompareTool compareTool = new CompareTool().EnableEncryptionCompare();
String compareResult = compareTool.CompareByContent(outFileName, sourceFolder + "cmp_appended_" + filename
, destinationFolder, "diff_", USER, USER);
if (compareResult != null) {
NUnit.Framework.Assert.Fail(compareResult);
}
}
public virtual void CheckEncryptedWithCertificateDocumentAppending(String filename, IX509Certificate certificate
) {
String srcFileName = destinationFolder + filename;
String outFileName = destinationFolder + "appended_" + filename;
PdfReader reader = new PdfReader(srcFileName, new ReaderProperties().SetPublicKeySecurityParams(certificate
, GetPrivateKey()));
PdfDocument document = new PdfDocument(reader, new PdfWriter(outFileName), new StampingProperties().UseAppendMode
());
PdfPage newPage = document.AddNewPage();
String helloWorldStringValue = "Hello world string";
newPage.Put(PdfName.Default, new PdfString(helloWorldStringValue));
WriteTextBytesOnPageContent(newPage, "Hello world page_2!");
document.Close();
PdfReader appendedDocReader = new PdfReader(outFileName, new ReaderProperties().SetPublicKeySecurityParams
(certificate, GetPrivateKey()));
PdfDocument appendedDoc = new PdfDocument(appendedDocReader);
PdfPage secondPage = appendedDoc.GetPage(2);
PdfString helloWorldPdfString = secondPage.GetPdfObject().GetAsString(PdfName.Default);
String actualHelloWorldStringValue = helloWorldPdfString != null ? helloWorldPdfString.GetValue() : null;
NUnit.Framework.Assert.AreEqual(actualHelloWorldStringValue, helloWorldStringValue);
appendedDoc.Close();
CompareTool compareTool = new CompareTool().EnableEncryptionCompare();
compareTool.GetOutReaderProperties().SetPublicKeySecurityParams(certificate, GetPrivateKey());
compareTool.GetCmpReaderProperties().SetPublicKeySecurityParams(certificate, GetPrivateKey());
String compareResult = compareTool.CompareByContent(outFileName, sourceFolder + "cmp_appended_" + filename
, destinationFolder, "diff_");
if (compareResult != null) {
NUnit.Framework.Assert.Fail(compareResult);
}
}
internal static void WriteTextBytesOnPageContent(PdfPage page, String text) {
page.GetFirstContentStream().GetOutputStream().WriteBytes(("q\n" + "BT\n" + "36 706 Td\n" + "0 0 Td\n" + "/F1 24 Tf\n"
+ "(" + text + ")Tj\n" + "0 0 Td\n" + "ET\n" + "Q ").GetBytes(TSpdf.Commons.Utils.EncodingUtil.ISO_8859_1
));
page.GetResources().AddFont(page.GetDocument(), PdfFontFactory.CreateFont(StandardFonts.HELVETICA));
}
internal static void CompareEncryptedPdf(String filename) {
CheckDecryptedWithPasswordContent(destinationFolder + filename, OWNER, pageTextContent);
CheckDecryptedWithPasswordContent(destinationFolder + filename, USER, pageTextContent);
CompareTool compareTool = new CompareTool().EnableEncryptionCompare();
String compareResult = compareTool.CompareByContent(destinationFolder + filename, sourceFolder + "cmp_" +
filename, destinationFolder, "diff_", USER, USER);
if (compareResult != null) {
NUnit.Framework.Assert.Fail(compareResult);
}
}
}
}

View File

@@ -0,0 +1,45 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.Commons.Utils;
using TSpdf.Kernel.Crypto.Securityhandler;
using TSpdf.Kernel.Pdf;
using TSpdf.Test;
namespace TSpdf.Kernel.Crypto {
[NUnit.Framework.Category("IntegrationTest")]
public class PdfReaderCustomFilterTest : ExtendedTSpdfTest {
public static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/crypto/PdfReaderCustomFilterTest/";
[NUnit.Framework.Test]
public virtual void EncryptedDocumentCustomFilterStandartTest() {
using (PdfReader reader = new PdfReader(sourceFolder + "customSecurityHandler.pdf")) {
Exception e = NUnit.Framework.Assert.Catch(typeof(UnsupportedSecurityHandlerException), () => new PdfDocument
(reader));
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(UnsupportedSecurityHandlerException.UnsupportedSecurityHandler
, "/Standart"), e.Message);
}
}
}
}

View File

@@ -0,0 +1,140 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.IO;
using TSpdf.IO.Source;
using TSpdf.Kernel.Font;
using TSpdf.Kernel.Logs;
using TSpdf.Kernel.Pdf;
using TSpdf.Kernel.Pdf.Canvas;
using TSpdf.Kernel.Pdf.Filespec;
using TSpdf.Kernel.Utils;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.Kernel.Crypto {
[NUnit.Framework.Category("BouncyCastleIntegrationTest")]
public class UnencryptedWrapperTest : ExtendedTSpdfTest {
public static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/crypto/UnencryptedWrapperTest/";
public static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/crypto/UnencryptedWrapperTest/";
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
CreateOrClearDestinationFolder(destinationFolder);
}
[NUnit.Framework.Test]
public virtual void CreateSimpleWrapperDocumentTest() {
CreateWrapper("customEncryptedDocument.pdf", "simpleUnencryptedWrapper.pdf", "TSpdf");
}
[NUnit.Framework.Test]
public virtual void ExtractCustomEncryptedDocumentTest() {
ExtractEncrypted("customEncryptedDocument.pdf", "simpleUnencryptedWrapper.pdf", null);
}
[NUnit.Framework.Test]
public virtual void CreateWrapperForStandardEncryptedTest() {
CreateWrapper("standardEncryptedDocument.pdf", "standardUnencryptedWrapper.pdf", "Standard");
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void ExtractStandardEncryptedDocumentTest() {
ExtractEncrypted("standardEncryptedDocument.pdf", "standardUnencryptedWrapper.pdf", "World".GetBytes(TSpdf.Commons.Utils.EncodingUtil.ISO_8859_1
));
}
private void CreateWrapper(String encryptedName, String wrapperName, String cryptoFilter) {
String inPath = sourceFolder + "cmp_" + encryptedName;
String cmpPath = sourceFolder + "cmp_" + wrapperName;
String outPath = destinationFolder + wrapperName;
String diff = "diff_" + wrapperName + "_";
PdfDocument document = new PdfDocument(new PdfWriter(outPath, new WriterProperties().SetPdfVersion(PdfVersion
.PDF_2_0)));
PdfFileSpec fs = PdfEncryptedPayloadFileSpecFactory.Create(document, inPath, new PdfEncryptedPayload(cryptoFilter
));
document.SetEncryptedPayload(fs);
PdfFont font = PdfFontFactory.CreateFont();
PdfCanvas canvas = new PdfCanvas(document.AddNewPage());
canvas.SaveState().BeginText().MoveText(36, 750).SetFontAndSize(font, 30).ShowText("Hi! I'm wrapper document."
).EndText().RestoreState();
canvas.Release();
document.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPath, cmpPath, destinationFolder, diff
));
}
private void ExtractEncrypted(String encryptedName, String wrapperName, byte[] password) {
String inPath = sourceFolder + "cmp_" + wrapperName;
String cmpPath = sourceFolder + "cmp_" + encryptedName;
String outPath = destinationFolder + encryptedName;
String diff = "diff_" + encryptedName + "_";
PdfDocument document = new PdfDocument(new PdfReader(inPath));
PdfEncryptedPayloadDocument encryptedDocument = document.GetEncryptedPayloadDocument();
byte[] encryptedDocumentBytes = encryptedDocument.GetDocumentBytes();
FileStream fos = new FileStream(outPath, FileMode.Create);
fos.Write(encryptedDocumentBytes);
fos.Dispose();
document.Close();
PdfEncryptedPayload ep = encryptedDocument.GetEncryptedPayload();
NUnit.Framework.Assert.AreEqual(PdfEncryptedPayloadFileSpecFactory.GenerateFileDisplay(ep), encryptedDocument
.GetName());
if (password != null) {
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPath, cmpPath, destinationFolder, diff
, password, password));
}
else {
RandomAccessFileOrArray raf = new RandomAccessFileOrArray(new RandomAccessSourceFactory().CreateBestSource
(cmpPath));
byte[] cmpBytes = new byte[(int)raf.Length()];
raf.ReadFully(cmpBytes);
raf.Close();
NUnit.Framework.Assert.AreEqual(cmpBytes, encryptedDocumentBytes);
}
}
}
}

View File

@@ -0,0 +1,198 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.Collections.Generic;
using TSpdf.Commons.Utils;
using TSpdf.Kernel.Logs;
using TSpdf.Kernel.Pdf;
using TSpdf.Kernel.Utils;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.Kernel.Crypto {
[NUnit.Framework.Category("BouncyCastleIntegrationTest")]
public class UnicodeBasedPasswordEncryptionTest : ExtendedTSpdfTest {
public static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/crypto/UnicodeBasedPasswordEncryptionTest/";
public static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/crypto/UnicodeBasedPasswordEncryptionTest/";
private static IDictionary<String, UnicodeBasedPasswordEncryptionTest.SaslPreparedString> nameToSaslPrepared;
static UnicodeBasedPasswordEncryptionTest() {
// values are calculated with com.ibm.icu.text.StringPrep class in icu4j v58.2 lib
nameToSaslPrepared = new LinkedDictionary<String, UnicodeBasedPasswordEncryptionTest.SaslPreparedString>();
//الرحيم
nameToSaslPrepared.Put("arabic01", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u0627\u0644\u0631\u062D\u064A\u0645"
, "\u0627\u0644\u0631\u062D\u064A\u0645"));
//ال,ر11حيم
nameToSaslPrepared.Put("arabic02", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u0627\u0644,\u063111\u062D\u064A\u0645"
, "\u0627\u0644,\u063111\u062D\u064A\u0645"));
// لـه
nameToSaslPrepared.Put("arabic03", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u0644\u0640\u0647"
, "\u0644\u0640\u0647"));
// ﻻ
nameToSaslPrepared.Put("arabic04", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\ufefb", "\u0644\u0627"
));
// لا
nameToSaslPrepared.Put("arabic05", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u0644\u0627"
, "\u0644\u0627"));
// शांति देवनागरी
nameToSaslPrepared.Put("devanagari01", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u0936\u093e\u0902\u0924\u093f \u0926\u0947\u0935\u0928\u093E\u0917\u0930\u0940"
, "\u0936\u093E\u0902\u0924\u093F \u0926\u0947\u0935\u0928\u093E\u0917\u0930\u0940"));
// की प्राचीनतम
nameToSaslPrepared.Put("devanagari02", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u0915\u0940 \u092A\u094D\u0930\u093E\u091A\u0940\u0928\u0924\u092E"
, "\u0915\u0940 \u092A\u094D\u0930\u093E\u091A\u0940\u0928\u0924\u092E"));
// ਗ੍ਰੰਥ ਸਾਹਿਬ
nameToSaslPrepared.Put("gurmukhi01", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u0A17\u0A4D\u0A30\u0A70\u0A25 \u0A38\u0A3E\u0A39\u0A3F\u0A2C"
, "\u0A17\u0A4D\u0A30\u0A70\u0A25 \u0A38\u0A3E\u0A39\u0A3F\u0A2C"));
// ញ្ចូ
nameToSaslPrepared.Put("khmer01", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u1789\u17D2\u1785\u17BC"
, "\u1789\u17D2\u1785\u17BC"));
//இலக்கிய நடை கூட மக்களால்
nameToSaslPrepared.Put("tamil01", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u0B87\u0BB2\u0B95\u0BCD\u0B95\u0BBF\u0BAF \u0BA8\u0B9F\u0BC8 \u0B95\u0BC2\u0B9F \u0BAE\u0B95\u0BCD\u0B95\u0BB3\u0BBE\u0BB2\u0BCD"
, "\u0B87\u0BB2\u0B95\u0BCD\u0B95\u0BBF\u0BAF \u0BA8\u0B9F\u0BC8 \u0B95\u0BC2\u0B9F \u0BAE\u0B95\u0BCD\u0B95\u0BB3\u0BBE\u0BB2\u0BCD"
));
// ประเทศไทย
nameToSaslPrepared.Put("thai01", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28\u0E44\u0E17\u0E22"
, "\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28\u0E44\u0E17\u0E22"));
nameToSaslPrepared.Put("unicodeBom01", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\uFEFFab\uFEFFc"
, "abc"));
nameToSaslPrepared.Put("emoji01", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u267B", "\u267B"
));
nameToSaslPrepared.Put("rfc4013Example01", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("I\u00ADX"
, "IX"));
nameToSaslPrepared.Put("rfc4013Example02", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("user"
, "user"));
nameToSaslPrepared.Put("rfc4013Example03", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u00AA"
, "a"));
// match rfc4013Example01
nameToSaslPrepared.Put("rfc4013Example04", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u2168"
, "IX"));
nameToSaslPrepared.Put("nonAsciiSpace01", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u2008 \u2009 \u200A \u200B"
, " "));
// normalization tests
nameToSaslPrepared.Put("nfkcNormalization01", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u09C7\u09BE"
, "\u09CB"));
nameToSaslPrepared.Put("nfkcNormalization02", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u30AD\u3099\u30AB\u3099"
, "\u30AE\u30AC"));
nameToSaslPrepared.Put("nfkcNormalization03", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u3310"
, "\u30AE\u30AC"));
nameToSaslPrepared.Put("nfkcNormalization04", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u1100\u1161\u11A8"
, "\uAC01"));
nameToSaslPrepared.Put("nfkcNormalization05", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\uF951"
, "\u964B"));
}
/*
// Arabic
bidirectional check fail: "\u0627\u0644\u0631\u0651\u064E\u200C\u062D\u0652\u0645\u064E\u0640\u0670\u0646\u0650"
bidirectional check fail: "1\u0627\u0644\u0631\u062D\u064A\u06452"
// RFC4013 examples
bidirectional check fail: "\u0627\u0031"
prohibited character fail: "\u0007"
// unassigned code point for Unicode 3.2
"\uD83E\uDD14"
"\u038Ba\u038Db\u03A2c\u03CF"
*/
private class SaslPreparedString {
internal String unicodeInputString;
internal String preparedString;
internal SaslPreparedString(String unicodeInputString, String preparedString) {
this.unicodeInputString = unicodeInputString;
this.preparedString = preparedString;
}
}
[NUnit.Framework.OneTimeSetUp]
public static void Before() {
CreateOrClearDestinationFolder(destinationFolder);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void Aes256EncryptedPdfWithUnicodeBasedPassword() {
String fileNameTemplate = "unicodePassword_";
foreach (KeyValuePair<String, UnicodeBasedPasswordEncryptionTest.SaslPreparedString> entry in nameToSaslPrepared
) {
String filename = fileNameTemplate + entry.Key + ".pdf";
byte[] ownerPassword = entry.Value.preparedString.GetBytes(System.Text.Encoding.UTF8);
EncryptAes256AndCheck(filename, ownerPassword);
}
}
// TODO after DEVSIX-1220 finished:
// 1. Create with both inputString and prepareString.
// 1.1 Check opening both of these documents with both strings.
// 2. Try encrypt document with invalid input string.
// 3. Try open encrypted document with password that contains unassigned code points and ensure error is due to wrong password instead of the invalid input string.
private void EncryptAes256AndCheck(String filename, byte[] ownerPassword) {
int permissions = EncryptionConstants.ALLOW_SCREENREADERS;
WriterProperties writerProperties = new WriterProperties().SetStandardEncryption(PdfEncryptionTest.USER, ownerPassword
, permissions, EncryptionConstants.ENCRYPTION_AES_256).SetPdfVersion(PdfVersion.PDF_2_0);
PdfWriter writer = new PdfWriter(destinationFolder + filename, writerProperties.AddXmpMetadata());
PdfDocument document = new PdfDocument(writer);
document.GetDocumentInfo().SetMoreInfo(PdfEncryptionTest.customInfoEntryKey, PdfEncryptionTest.customInfoEntryValue
);
PdfPage page = document.AddNewPage();
PdfEncryptionTest.WriteTextBytesOnPageContent(page, PdfEncryptionTest.pageTextContent);
page.Flush();
document.Close();
PdfEncryptionTest.CheckDecryptedWithPasswordContent(destinationFolder + filename, ownerPassword, PdfEncryptionTest
.pageTextContent);
CompareTool compareTool = new CompareTool().EnableEncryptionCompare();
String compareResult = compareTool.CompareByContent(destinationFolder + filename, sourceFolder + "cmp_" +
filename, destinationFolder, "diff_", ownerPassword, ownerPassword);
if (compareResult != null) {
NUnit.Framework.Assert.Fail(compareResult);
}
}
}
}

View File

@@ -0,0 +1,64 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using System.IO;
using TSpdf.Kernel.Crypto;
using TSpdf.Kernel.Logs;
using TSpdf.Kernel.Pdf;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.Kernel.Crypto.Securityhandler {
[NUnit.Framework.Category("BouncyCastleUnitTest")]
public class PubKeySecurityHandlerTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void ComputeGlobalKeyDecryptTest() {
PubKeySecurityHandler securityHandler = new PubKeySecurityHandlerTest.TestSecurityHandler();
NUnit.Framework.Assert.AreEqual(20, securityHandler.ComputeGlobalKey("SHA1", false).Length);
}
private class TestSecurityHandler : PubKeySecurityHandler {
public override OutputStreamEncryption GetEncryptionStream(Stream os) {
throw new NotSupportedException();
}
public override IDecryptor GetDecryptor() {
throw new NotSupportedException();
}
protected internal override void SetPubSecSpecificHandlerDicEntries(PdfDictionary encryptionDictionary, bool
encryptMetadata, bool embeddedFilesOnly) {
throw new NotSupportedException();
}
protected internal override String GetDigestAlgorithm() {
throw new NotSupportedException();
}
protected internal override void InitKey(byte[] globalKey, int keyLength) {
throw new NotSupportedException();
}
}
}
}

View File

@@ -0,0 +1,301 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.Commons.Utils;
using TSpdf.IO.Font;
using TSpdf.IO.Font.Constants;
using TSpdf.Kernel.Exceptions;
using TSpdf.Kernel.Pdf;
using TSpdf.Test;
namespace TSpdf.Kernel.Font {
[NUnit.Framework.Category("UnitTest")]
public class PdfFontFactoryTest : ExtendedTSpdfTest {
public static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/font/";
[NUnit.Framework.Test]
public virtual void StandardFontForceEmbeddedTest() {
Type1Font fontProgram = (Type1Font)FontProgramFactory.CreateFont(StandardFonts.HELVETICA);
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => PdfFontFactory.CreateFont(fontProgram
, PdfEncodings.UTF8, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.CANNOT_EMBED_STANDARD_FONT, e.Message);
}
[NUnit.Framework.Test]
public virtual void StandardFontPreferEmbeddedTest() {
Type1Font fontProgram = (Type1Font)FontProgramFactory.CreateFont(StandardFonts.HELVETICA);
PdfType1Font font = (PdfType1Font)PdfFontFactory.CreateFont(fontProgram, PdfEncodings.UTF8, PdfFontFactory.EmbeddingStrategy
.PREFER_EMBEDDED);
NUnit.Framework.Assert.IsNotNull(font);
NUnit.Framework.Assert.IsFalse(font.IsEmbedded());
}
[NUnit.Framework.Test]
public virtual void StandardFontPreferNotEmbeddedTest() {
Type1Font fontProgram = (Type1Font)FontProgramFactory.CreateFont(StandardFonts.HELVETICA);
PdfType1Font font = (PdfType1Font)PdfFontFactory.CreateFont(fontProgram, PdfEncodings.UTF8, PdfFontFactory.EmbeddingStrategy
.PREFER_NOT_EMBEDDED);
NUnit.Framework.Assert.IsNotNull(font);
NUnit.Framework.Assert.IsFalse(font.IsEmbedded());
}
[NUnit.Framework.Test]
public virtual void StandardFontForceNotEmbeddedTest() {
Type1Font fontProgram = (Type1Font)FontProgramFactory.CreateFont(StandardFonts.HELVETICA);
PdfType1Font font = (PdfType1Font)PdfFontFactory.CreateFont(fontProgram, PdfEncodings.UTF8, PdfFontFactory.EmbeddingStrategy
.FORCE_NOT_EMBEDDED);
NUnit.Framework.Assert.IsNotNull(font);
NUnit.Framework.Assert.IsFalse(font.IsEmbedded());
}
[NUnit.Framework.Test]
public virtual void CustomType1FontForceEmbeddedTest() {
Type1Font fontProgram = new PdfFontFactoryTest.CustomType1FontProgram();
PdfType1Font font = (PdfType1Font)PdfFontFactory.CreateFont(fontProgram, PdfEncodings.UTF8, PdfFontFactory.EmbeddingStrategy
.FORCE_EMBEDDED);
NUnit.Framework.Assert.IsNotNull(font);
NUnit.Framework.Assert.IsTrue(font.IsEmbedded());
}
[NUnit.Framework.Test]
public virtual void CustomType1FontPreferEmbeddedTest() {
Type1Font fontProgram = new PdfFontFactoryTest.CustomType1FontProgram();
PdfType1Font font = (PdfType1Font)PdfFontFactory.CreateFont(fontProgram, PdfEncodings.UTF8, PdfFontFactory.EmbeddingStrategy
.PREFER_EMBEDDED);
NUnit.Framework.Assert.IsNotNull(font);
NUnit.Framework.Assert.IsTrue(font.IsEmbedded());
}
[NUnit.Framework.Test]
public virtual void CustomType1FontPreferNotEmbeddedTest() {
Type1Font fontProgram = new PdfFontFactoryTest.CustomType1FontProgram();
PdfType1Font font = (PdfType1Font)PdfFontFactory.CreateFont(fontProgram, PdfEncodings.UTF8, PdfFontFactory.EmbeddingStrategy
.PREFER_NOT_EMBEDDED);
NUnit.Framework.Assert.IsNotNull(font);
NUnit.Framework.Assert.IsFalse(font.IsEmbedded());
}
[NUnit.Framework.Test]
public virtual void CustomType1FontForceNotEmbeddedTest() {
Type1Font fontProgram = new PdfFontFactoryTest.CustomType1FontProgram();
PdfType1Font font = (PdfType1Font)PdfFontFactory.CreateFont(fontProgram, PdfEncodings.UTF8, PdfFontFactory.EmbeddingStrategy
.FORCE_NOT_EMBEDDED);
NUnit.Framework.Assert.IsNotNull(font);
NUnit.Framework.Assert.IsFalse(font.IsEmbedded());
}
[NUnit.Framework.Test]
public virtual void TrueTypeFontProgramUTF8AllowEmbeddingEncodingForceEmbeddedTest() {
TrueTypeFont fontProgram = new PdfFontFactoryTest.CustomTrueTypeFontProgram(true);
PdfTrueTypeFont font = (PdfTrueTypeFont)PdfFontFactory.CreateFont(fontProgram, PdfEncodings.UTF8, PdfFontFactory.EmbeddingStrategy
.FORCE_EMBEDDED);
NUnit.Framework.Assert.IsNotNull(font);
NUnit.Framework.Assert.IsTrue(font.IsEmbedded());
}
[NUnit.Framework.Test]
public virtual void TrueTypeFontProgramUTF8AllowEmbeddingEncodingPreferEmbeddedTest() {
TrueTypeFont fontProgram = new PdfFontFactoryTest.CustomTrueTypeFontProgram(true);
PdfTrueTypeFont font = (PdfTrueTypeFont)PdfFontFactory.CreateFont(fontProgram, PdfEncodings.UTF8, PdfFontFactory.EmbeddingStrategy
.PREFER_EMBEDDED);
NUnit.Framework.Assert.IsNotNull(font);
NUnit.Framework.Assert.IsTrue(font.IsEmbedded());
}
[NUnit.Framework.Test]
public virtual void TrueTypeFontProgramUTF8AllowEmbeddingEncodingPreferNotEmbeddedTest() {
TrueTypeFont fontProgram = new PdfFontFactoryTest.CustomTrueTypeFontProgram(true);
PdfTrueTypeFont font = (PdfTrueTypeFont)PdfFontFactory.CreateFont(fontProgram, PdfEncodings.UTF8, PdfFontFactory.EmbeddingStrategy
.PREFER_NOT_EMBEDDED);
NUnit.Framework.Assert.IsNotNull(font);
NUnit.Framework.Assert.IsFalse(font.IsEmbedded());
}
[NUnit.Framework.Test]
public virtual void TrueTypeFontProgramUTF8AllowEmbeddingEncodingForceNotEmbeddedTest() {
TrueTypeFont fontProgram = new PdfFontFactoryTest.CustomTrueTypeFontProgram(true);
PdfTrueTypeFont font = (PdfTrueTypeFont)PdfFontFactory.CreateFont(fontProgram, PdfEncodings.UTF8, PdfFontFactory.EmbeddingStrategy
.FORCE_NOT_EMBEDDED);
NUnit.Framework.Assert.IsNotNull(font);
NUnit.Framework.Assert.IsFalse(font.IsEmbedded());
}
[NUnit.Framework.Test]
public virtual void TrueTypeFontProgramUTF8NotAllowEmbeddingEncodingForceEmbeddedTest() {
TrueTypeFont fontProgram = new PdfFontFactoryTest.CustomTrueTypeFontProgram(false);
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => PdfFontFactory.CreateFont(fontProgram
, PdfEncodings.UTF8, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED));
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(KernelExceptionMessageConstant.CANNOT_BE_EMBEDDED_DUE_TO_LICENSING_RESTRICTIONS
, "CustomNameCustomStyle"), e.Message);
}
[NUnit.Framework.Test]
public virtual void TrueTypeFontProgramUTF8NotAllowEmbeddingEncodingPreferEmbeddedTest() {
TrueTypeFont fontProgram = new PdfFontFactoryTest.CustomTrueTypeFontProgram(false);
PdfTrueTypeFont font = (PdfTrueTypeFont)PdfFontFactory.CreateFont(fontProgram, PdfEncodings.UTF8, PdfFontFactory.EmbeddingStrategy
.PREFER_EMBEDDED);
NUnit.Framework.Assert.IsNotNull(font);
NUnit.Framework.Assert.IsFalse(font.IsEmbedded());
}
[NUnit.Framework.Test]
public virtual void TrueTypeFontProgramUTF8NotAllowEmbeddingEncodingPreferNotEmbeddedTest() {
TrueTypeFont fontProgram = new PdfFontFactoryTest.CustomTrueTypeFontProgram(false);
PdfTrueTypeFont font = (PdfTrueTypeFont)PdfFontFactory.CreateFont(fontProgram, PdfEncodings.UTF8, PdfFontFactory.EmbeddingStrategy
.PREFER_NOT_EMBEDDED);
NUnit.Framework.Assert.IsNotNull(font);
NUnit.Framework.Assert.IsFalse(font.IsEmbedded());
}
[NUnit.Framework.Test]
public virtual void TrueTypeFontProgramUTF8NotAllowEmbeddingEncodingForceNotEmbeddedTest() {
TrueTypeFont fontProgram = new PdfFontFactoryTest.CustomTrueTypeFontProgram(false);
PdfTrueTypeFont font = (PdfTrueTypeFont)PdfFontFactory.CreateFont(fontProgram, PdfEncodings.UTF8, PdfFontFactory.EmbeddingStrategy
.FORCE_NOT_EMBEDDED);
NUnit.Framework.Assert.IsNotNull(font);
NUnit.Framework.Assert.IsFalse(font.IsEmbedded());
}
[NUnit.Framework.Test]
public virtual void TrueTypeFontProgramIdentityHAllowEmbeddingEncodingForceEmbeddedTest() {
TrueTypeFont fontProgram = new PdfFontFactoryTest.CustomTrueTypeFontProgram(true);
PdfType0Font font = (PdfType0Font)PdfFontFactory.CreateFont(fontProgram, PdfEncodings.IDENTITY_H, PdfFontFactory.EmbeddingStrategy
.FORCE_EMBEDDED);
NUnit.Framework.Assert.IsNotNull(font);
NUnit.Framework.Assert.IsTrue(font.IsEmbedded());
}
[NUnit.Framework.Test]
public virtual void TrueTypeFontProgramIdentityHAllowEmbeddingEncodingPreferEmbeddedTest() {
TrueTypeFont fontProgram = new PdfFontFactoryTest.CustomTrueTypeFontProgram(true);
PdfType0Font font = (PdfType0Font)PdfFontFactory.CreateFont(fontProgram, PdfEncodings.IDENTITY_H, PdfFontFactory.EmbeddingStrategy
.PREFER_EMBEDDED);
NUnit.Framework.Assert.IsNotNull(font);
NUnit.Framework.Assert.IsTrue(font.IsEmbedded());
}
[NUnit.Framework.Test]
public virtual void TrueTypeFontProgramIdentityHAllowEmbeddingEncodingPreferNotEmbeddedTest() {
TrueTypeFont fontProgram = new PdfFontFactoryTest.CustomTrueTypeFontProgram(true);
PdfType0Font font = (PdfType0Font)PdfFontFactory.CreateFont(fontProgram, PdfEncodings.IDENTITY_H, PdfFontFactory.EmbeddingStrategy
.PREFER_NOT_EMBEDDED);
NUnit.Framework.Assert.IsNotNull(font);
NUnit.Framework.Assert.IsTrue(font.IsEmbedded());
}
[NUnit.Framework.Test]
public virtual void TrueTypeFontProgramIdentityHAllowEmbeddingEncodingForceNotEmbeddedTest() {
TrueTypeFont fontProgram = new PdfFontFactoryTest.CustomTrueTypeFontProgram(true);
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => PdfFontFactory.CreateFont(fontProgram
, PdfEncodings.IDENTITY_H, PdfFontFactory.EmbeddingStrategy.FORCE_NOT_EMBEDDED));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.CANNOT_CREATE_TYPE_0_FONT_WITH_TRUE_TYPE_FONT_PROGRAM_WITHOUT_EMBEDDING_IT
, e.Message);
}
[NUnit.Framework.Test]
public virtual void TrueTypeFontProgramIdentityHNotAllowEmbeddingEncodingForceEmbeddedTest() {
TrueTypeFont fontProgram = new PdfFontFactoryTest.CustomTrueTypeFontProgram(false);
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => PdfFontFactory.CreateFont(fontProgram
, PdfEncodings.IDENTITY_H, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED));
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(KernelExceptionMessageConstant.CANNOT_BE_EMBEDDED_DUE_TO_LICENSING_RESTRICTIONS
, "CustomNameCustomStyle"), e.Message);
}
[NUnit.Framework.Test]
public virtual void TrueTypeFontProgramIdentityHNotAllowEmbeddingEncodingPreferEmbeddedTest() {
TrueTypeFont fontProgram = new PdfFontFactoryTest.CustomTrueTypeFontProgram(false);
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => PdfFontFactory.CreateFont(fontProgram
, PdfEncodings.IDENTITY_H, PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED));
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(KernelExceptionMessageConstant.CANNOT_BE_EMBEDDED_DUE_TO_LICENSING_RESTRICTIONS
, "CustomNameCustomStyle"), e.Message);
}
[NUnit.Framework.Test]
public virtual void TrueTypeFontProgramIdentityHNotAllowEmbeddingEncodingPreferNotEmbeddedTest() {
TrueTypeFont fontProgram = new PdfFontFactoryTest.CustomTrueTypeFontProgram(false);
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => PdfFontFactory.CreateFont(fontProgram
, PdfEncodings.IDENTITY_H, PdfFontFactory.EmbeddingStrategy.PREFER_NOT_EMBEDDED));
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(KernelExceptionMessageConstant.CANNOT_BE_EMBEDDED_DUE_TO_LICENSING_RESTRICTIONS
, "CustomNameCustomStyle"), e.Message);
}
[NUnit.Framework.Test]
public virtual void TrueTypeFontProgramIdentityHNotAllowEmbeddingEncodingForceNotEmbeddedTest() {
TrueTypeFont fontProgram = new PdfFontFactoryTest.CustomTrueTypeFontProgram(false);
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => PdfFontFactory.CreateFont(fontProgram
, PdfEncodings.IDENTITY_H, PdfFontFactory.EmbeddingStrategy.FORCE_NOT_EMBEDDED));
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(KernelExceptionMessageConstant.CANNOT_BE_EMBEDDED_DUE_TO_LICENSING_RESTRICTIONS
, "CustomNameCustomStyle"), e.Message);
}
[NUnit.Framework.Test]
public virtual void StandardFontCachedWithoutDocumentTest() {
// this test ensures that method which allows caching into the document does not fail
// if the document is null
PdfDocument cacheTo = null;
PdfType1Font font = (PdfType1Font)PdfFontFactory.CreateFont(StandardFonts.HELVETICA, PdfEncodings.UTF8, cacheTo
);
NUnit.Framework.Assert.IsNotNull(font);
NUnit.Framework.Assert.IsFalse(font.IsEmbedded());
}
[NUnit.Framework.Test]
public virtual void CreateFontFromNullDictionaryTest() {
PdfDictionary dictionary = null;
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => PdfFontFactory.CreateFont(dictionary
));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.CANNOT_CREATE_FONT_FROM_NULL_PDF_DICTIONARY
, e.Message);
}
[NUnit.Framework.Test]
public virtual void CreateFontFromEmptyDictionaryTest() {
PdfDictionary dictionary = new PdfDictionary();
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => PdfFontFactory.CreateFont(dictionary
));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.DICTIONARY_DOES_NOT_HAVE_SUPPORTED_FONT_DATA
, e.Message);
}
private class CustomType1FontProgram : Type1Font {
public override bool IsBuiltInFont() {
return false;
}
}
private class CustomTrueTypeFontProgram : TrueTypeFont {
public CustomTrueTypeFontProgram(bool allowEmbedding) {
this.fontNames = new PdfFontFactoryTest.CustomFontNames(allowEmbedding);
}
}
private class CustomFontNames : FontNames {
public CustomFontNames(bool allowEmbedding) {
this.SetAllowEmbedding(allowEmbedding);
this.SetFontName("CustomName");
this.SetStyle("CustomStyle");
}
}
}
}

View File

@@ -0,0 +1,593 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using TSpdf.IO.Font;
using TSpdf.IO.Font.Otf;
using TSpdf.Kernel.Exceptions;
using TSpdf.Kernel.Pdf;
using TSpdf.Test;
namespace TSpdf.Kernel.Font {
[NUnit.Framework.Category("UnitTest")]
public class PdfFontUnitTest : ExtendedTSpdfTest {
public const int FONT_METRICS_DESCENT = -40;
public const int FONT_METRICS_ASCENT = 700;
public const int FONT_SIZE = 50;
public class TestFont : PdfFont {
public const int SIMPLE_GLYPH = 97;
public const int SIMPLE_GLYPH_WITHOUT_BBOX = 98;
public const int SIMPLE_GLYPH_WITH_POSITIVE_DESCENT = 99;
public const int COMPLEX_GLYPH = 119070;
public const int ZERO_CODE_GLYPH = 0;
// these are two parts of G-clef glyph
public static readonly char[] COMPLEX_GLYPH_AS_CHARS = new char[] { '\ud834', '\udd1e' };
public const int SIMPLE_GLYPH_WIDTH = 100;
public const int COMPLEX_GLYPH_WIDTH = 200;
public TestFont()
: base() {
}
public TestFont(PdfDictionary dictionary)
: base(dictionary) {
}
public virtual void SetFontProgram(FontProgram fontProgram) {
this.fontProgram = fontProgram;
}
public override Glyph GetGlyph(int unicode) {
if (unicode == SIMPLE_GLYPH) {
return new Glyph(1, SIMPLE_GLYPH_WIDTH, SIMPLE_GLYPH, new int[] { 10, -20, 200, 600 });
}
else {
if (unicode == SIMPLE_GLYPH_WITHOUT_BBOX) {
return new Glyph(2, SIMPLE_GLYPH_WIDTH, SIMPLE_GLYPH);
}
else {
if (unicode == SIMPLE_GLYPH_WITH_POSITIVE_DESCENT) {
return new Glyph(3, SIMPLE_GLYPH_WIDTH, SIMPLE_GLYPH, new int[] { 10, 10, 200, 600 });
}
else {
if (unicode == COMPLEX_GLYPH) {
return new Glyph(4, COMPLEX_GLYPH_WIDTH, COMPLEX_GLYPH, new int[] { 20, -100, 400, 800 });
}
else {
if (unicode == ZERO_CODE_GLYPH) {
return new Glyph(0, 0, 0);
}
}
}
}
}
return null;
}
public override GlyphLine CreateGlyphLine(String content) {
return null;
}
public override int AppendGlyphs(String text, int from, int to, IList<Glyph> glyphs) {
return 0;
}
public override int AppendAnyGlyph(String text, int from, IList<Glyph> glyphs) {
return 0;
}
public override byte[] ConvertToBytes(String text) {
return new byte[0];
}
public override byte[] ConvertToBytes(GlyphLine glyphLine) {
return new byte[0];
}
public override String Decode(PdfString content) {
return null;
}
public override GlyphLine DecodeIntoGlyphLine(PdfString content) {
return null;
}
public override float GetContentWidth(PdfString content) {
return 0;
}
public override byte[] ConvertToBytes(Glyph glyph) {
return new byte[0];
}
public override void WriteText(GlyphLine text, int from, int to, PdfOutputStream stream) {
}
public override void WriteText(String text, PdfOutputStream stream) {
}
protected internal override PdfDictionary GetFontDescriptor(String fontName) {
return null;
}
}
public class TestFontProgram : FontProgram {
public override int GetPdfFontFlags() {
return 0;
}
public override int GetKerning(Glyph first, Glyph second) {
return 0;
}
public override FontMetrics GetFontMetrics() {
return new PdfFontUnitTest.TestFontMetrics();
}
public override bool IsFontSpecific() {
return true;
}
}
public class TestFontMetrics : FontMetrics {
public TestFontMetrics() {
SetTypoDescender(FONT_METRICS_DESCENT);
SetTypoAscender(FONT_METRICS_ASCENT);
}
}
[NUnit.Framework.Test]
public virtual void ConstructorWithoutParamsTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
NUnit.Framework.Assert.AreEqual(PdfName.Font, font.GetPdfObject().Get(PdfName.Type));
}
[NUnit.Framework.Test]
public virtual void ConstructorWithDictionaryTest() {
PdfDictionary dictionary = new PdfDictionary();
dictionary.Put(PdfName.A, PdfName.B);
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont(dictionary);
NUnit.Framework.Assert.AreEqual(PdfName.Font, font.GetPdfObject().Get(PdfName.Type));
NUnit.Framework.Assert.AreEqual(PdfName.B, font.GetPdfObject().Get(PdfName.A));
}
[NUnit.Framework.Test]
public virtual void ContainsGlyphTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
NUnit.Framework.Assert.IsTrue(font.ContainsGlyph(PdfFontUnitTest.TestFont.SIMPLE_GLYPH));
NUnit.Framework.Assert.IsFalse(font.ContainsGlyph(111));
}
[NUnit.Framework.Test]
public virtual void ZeroGlyphIsAllowedOnlyIfFontIsSymbolicTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
NUnit.Framework.Assert.IsFalse(font.ContainsGlyph(PdfFontUnitTest.TestFont.ZERO_CODE_GLYPH));
font.SetFontProgram(new PdfFontUnitTest.TestFontProgram());
NUnit.Framework.Assert.IsTrue(font.ContainsGlyph(PdfFontUnitTest.TestFont.ZERO_CODE_GLYPH));
}
[NUnit.Framework.Test]
public virtual void GetWidthUnicodeTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
NUnit.Framework.Assert.AreEqual(PdfFontUnitTest.TestFont.SIMPLE_GLYPH_WIDTH, font.GetWidth(PdfFontUnitTest.TestFont
.SIMPLE_GLYPH));
NUnit.Framework.Assert.AreEqual(0, font.GetWidth(111));
}
[NUnit.Framework.Test]
public virtual void GetWidthFontSizeTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
double expectedValue = PdfFontUnitTest.TestFont.SIMPLE_GLYPH_WIDTH * FONT_SIZE / (double)FontProgram.UNITS_NORMALIZATION;
NUnit.Framework.Assert.AreEqual(expectedValue, font.GetWidth(PdfFontUnitTest.TestFont.SIMPLE_GLYPH, FONT_SIZE
), 0.1);
NUnit.Framework.Assert.AreEqual(0, font.GetWidth(111));
}
[NUnit.Framework.Test]
public virtual void GetWidthOfStringTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
char[] text = GetSentence(3);
String textAsString = new String(text);
NUnit.Framework.Assert.AreEqual(3 * PdfFontUnitTest.TestFont.SIMPLE_GLYPH_WIDTH, font.GetWidth(textAsString
));
}
[NUnit.Framework.Test]
public virtual void GetWidthOfSurrogatePairTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
char[] text = new char[] { PdfFontUnitTest.TestFont.COMPLEX_GLYPH_AS_CHARS[0], PdfFontUnitTest.TestFont.COMPLEX_GLYPH_AS_CHARS
[1], (char)PdfFontUnitTest.TestFont.SIMPLE_GLYPH };
String textAsString = new String(text);
NUnit.Framework.Assert.AreEqual(PdfFontUnitTest.TestFont.COMPLEX_GLYPH_WIDTH + PdfFontUnitTest.TestFont.SIMPLE_GLYPH_WIDTH
, font.GetWidth(textAsString));
}
[NUnit.Framework.Test]
public virtual void GetWidthOfUnknownGlyphsTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
char[] text = new char[] { (char)111, (char)222, (char)333 };
String textAsString = new String(text);
NUnit.Framework.Assert.AreEqual(0, font.GetWidth(textAsString));
}
[NUnit.Framework.Test]
public virtual void GetWidthOfStringWithFontSizeTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
char[] text = GetSentence(3);
String textAsString = new String(text);
double expectedValue = 3 * PdfFontUnitTest.TestFont.SIMPLE_GLYPH_WIDTH * FONT_SIZE / (double)FontProgram.UNITS_NORMALIZATION;
NUnit.Framework.Assert.AreEqual(expectedValue, font.GetWidth(textAsString, FONT_SIZE), 0.1);
}
[NUnit.Framework.Test]
public virtual void GetDescentOfGlyphTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
int expectedDescent = font.GetGlyph(PdfFontUnitTest.TestFont.SIMPLE_GLYPH).GetBbox()[1];
int expectedValue = (int)(expectedDescent * FONT_SIZE / (double)FontProgram.UNITS_NORMALIZATION);
NUnit.Framework.Assert.AreEqual(expectedValue, font.GetDescent(PdfFontUnitTest.TestFont.SIMPLE_GLYPH, FONT_SIZE
));
}
[NUnit.Framework.Test]
public virtual void DescentCannotBePositiveTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
NUnit.Framework.Assert.AreEqual(0, font.GetDescent(PdfFontUnitTest.TestFont.SIMPLE_GLYPH_WITH_POSITIVE_DESCENT
, 50));
}
[NUnit.Framework.Test]
public virtual void GetDescentOfUnknownGlyphTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
NUnit.Framework.Assert.AreEqual(0, font.GetDescent(111, 50));
}
[NUnit.Framework.Test]
public virtual void GetDescentOfGlyphWithoutBBoxTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
font.SetFontProgram(new PdfFontUnitTest.TestFontProgram());
int expectedValue = (int)(FONT_METRICS_DESCENT * FONT_SIZE / (double)FontProgram.UNITS_NORMALIZATION);
NUnit.Framework.Assert.AreEqual(expectedValue, font.GetDescent(PdfFontUnitTest.TestFont.SIMPLE_GLYPH_WITHOUT_BBOX
, FONT_SIZE));
}
[NUnit.Framework.Test]
public virtual void GetDescentOfTextTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
char[] text = new char[] { (char)PdfFontUnitTest.TestFont.SIMPLE_GLYPH, PdfFontUnitTest.TestFont.COMPLEX_GLYPH_AS_CHARS
[0], PdfFontUnitTest.TestFont.COMPLEX_GLYPH_AS_CHARS[1] };
String textAsString = new String(text);
int expectedMinDescent = Math.Min(font.GetGlyph(PdfFontUnitTest.TestFont.SIMPLE_GLYPH).GetBbox()[1], font.
GetGlyph(PdfFontUnitTest.TestFont.COMPLEX_GLYPH).GetBbox()[1]);
int expectedValue = (int)(expectedMinDescent * FONT_SIZE / (double)FontProgram.UNITS_NORMALIZATION);
NUnit.Framework.Assert.AreEqual(expectedValue, font.GetDescent(textAsString, FONT_SIZE));
}
[NUnit.Framework.Test]
public virtual void GetDescentOfTextWithGlyphWithoutBBoxTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
font.SetFontProgram(new PdfFontUnitTest.TestFontProgram());
char[] text = new char[] { (char)PdfFontUnitTest.TestFont.SIMPLE_GLYPH, (char)PdfFontUnitTest.TestFont.SIMPLE_GLYPH_WITHOUT_BBOX
};
String textAsString = new String(text);
int expectedMinDescent = Math.Min(font.GetGlyph(PdfFontUnitTest.TestFont.SIMPLE_GLYPH).GetBbox()[1], FONT_METRICS_DESCENT
);
int expectedValue = (int)(expectedMinDescent * FONT_SIZE / (double)FontProgram.UNITS_NORMALIZATION);
NUnit.Framework.Assert.AreEqual(expectedValue, font.GetDescent(textAsString, FONT_SIZE));
}
[NUnit.Framework.Test]
public virtual void GetAscentOfGlyphTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
int expectedAscent = font.GetGlyph(PdfFontUnitTest.TestFont.SIMPLE_GLYPH).GetBbox()[3];
int expectedValue = (int)(expectedAscent * FONT_SIZE / (double)FontProgram.UNITS_NORMALIZATION);
NUnit.Framework.Assert.AreEqual(expectedValue, font.GetAscent(PdfFontUnitTest.TestFont.SIMPLE_GLYPH, FONT_SIZE
));
}
[NUnit.Framework.Test]
public virtual void GetAscentOfGlyphWithoutBBoxTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
font.SetFontProgram(new PdfFontUnitTest.TestFontProgram());
int expectedValue = (int)(FONT_METRICS_ASCENT * FONT_SIZE / (double)FontProgram.UNITS_NORMALIZATION);
NUnit.Framework.Assert.AreEqual(expectedValue, font.GetAscent(PdfFontUnitTest.TestFont.SIMPLE_GLYPH_WITHOUT_BBOX
, FONT_SIZE));
}
[NUnit.Framework.Test]
public virtual void GetAscentOfTextTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
char[] text = new char[] { (char)PdfFontUnitTest.TestFont.SIMPLE_GLYPH, PdfFontUnitTest.TestFont.COMPLEX_GLYPH_AS_CHARS
[0], PdfFontUnitTest.TestFont.COMPLEX_GLYPH_AS_CHARS[1] };
String textAsString = new String(text);
int expectedMaxAscent = Math.Max(font.GetGlyph(PdfFontUnitTest.TestFont.SIMPLE_GLYPH).GetBbox()[3], font.GetGlyph
(PdfFontUnitTest.TestFont.COMPLEX_GLYPH).GetBbox()[3]);
int expectedValue = (int)(expectedMaxAscent * FONT_SIZE / (double)FontProgram.UNITS_NORMALIZATION);
NUnit.Framework.Assert.AreEqual(expectedValue, font.GetAscent(textAsString, FONT_SIZE));
}
[NUnit.Framework.Test]
public virtual void GetAscentOfTextWithGlyphWithoutBBoxTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
font.SetFontProgram(new PdfFontUnitTest.TestFontProgram());
char[] text = new char[] { (char)PdfFontUnitTest.TestFont.SIMPLE_GLYPH, (char)PdfFontUnitTest.TestFont.SIMPLE_GLYPH_WITHOUT_BBOX
};
String textAsString = new String(text);
int expectedMaxAscent = Math.Max(font.GetGlyph(PdfFontUnitTest.TestFont.SIMPLE_GLYPH).GetBbox()[3], FONT_METRICS_ASCENT
);
int expectedValue = (int)(expectedMaxAscent * FONT_SIZE / (double)FontProgram.UNITS_NORMALIZATION);
NUnit.Framework.Assert.AreEqual(expectedValue, font.GetAscent(textAsString, FONT_SIZE));
}
[NUnit.Framework.Test]
public virtual void IsEmbeddedTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
NUnit.Framework.Assert.IsFalse(font.IsEmbedded());
font.embedded = true;
NUnit.Framework.Assert.IsTrue(font.IsEmbedded());
}
[NUnit.Framework.Test]
public virtual void IsSubsetTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
NUnit.Framework.Assert.IsTrue(font.IsSubset());
font.SetSubset(false);
NUnit.Framework.Assert.IsFalse(font.IsSubset());
}
[NUnit.Framework.Test]
public virtual void AddSubsetRangeTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
font.SetSubset(false);
int[] range1 = new int[] { 1, 2 };
int[] range2 = new int[] { 10, 20 };
font.AddSubsetRange(range1);
font.AddSubsetRange(range2);
NUnit.Framework.Assert.IsTrue(font.IsSubset());
NUnit.Framework.Assert.AreEqual(2, font.subsetRanges.Count);
NUnit.Framework.Assert.AreEqual(range1, font.subsetRanges[0]);
NUnit.Framework.Assert.AreEqual(range2, font.subsetRanges[1]);
}
[NUnit.Framework.Test]
public virtual void SplitSentenceFitMaxWidthTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
char[] words = GetSentence(3, 3);
String wordsAsString = new String(words);
double width = 6 * font.GetWidth(PdfFontUnitTest.TestFont.SIMPLE_GLYPH, FONT_SIZE);
IList<String> result = font.SplitString(wordsAsString, FONT_SIZE, (float)width + 0.01f);
NUnit.Framework.Assert.AreEqual(1, result.Count);
NUnit.Framework.Assert.AreEqual(wordsAsString, result[0]);
}
[NUnit.Framework.Test]
public virtual void SplitSentenceWordFitMaxWidthTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
char[] words = GetSentence(3, 4, 2);
String wordsAsString = new String(words);
double width = 4 * font.GetWidth(PdfFontUnitTest.TestFont.SIMPLE_GLYPH, FONT_SIZE);
IList<String> result = font.SplitString(wordsAsString, FONT_SIZE, (float)width + 0.01f);
NUnit.Framework.Assert.AreEqual(3, result.Count);
NUnit.Framework.Assert.AreEqual(new String(GetSentence(3)), result[0]);
NUnit.Framework.Assert.AreEqual(new String(GetSentence(4)), result[1]);
NUnit.Framework.Assert.AreEqual(new String(GetSentence(2)), result[2]);
}
[NUnit.Framework.Test]
public virtual void SplitSentenceWordDoesNotFitMaxWidthCase_PartIsCombinedWithTheFollowingWordTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
char[] words = GetSentence(3, 4, 2);
String wordsAsString = new String(words);
double width = 3 * font.GetWidth(PdfFontUnitTest.TestFont.SIMPLE_GLYPH, FONT_SIZE);
IList<String> result = font.SplitString(wordsAsString, FONT_SIZE, (float)width + 0.01f);
NUnit.Framework.Assert.AreEqual(3, result.Count);
NUnit.Framework.Assert.AreEqual(new String(GetSentence(3)), result[0]);
NUnit.Framework.Assert.AreEqual(new String(GetSentence(3)), result[1]);
NUnit.Framework.Assert.AreEqual(new String(GetSentence(1, 2)), result[2]);
}
[NUnit.Framework.Test]
public virtual void SplitSentenceWordDoesNotFitMaxWidthCase_PartIsOnTheSeparateLineTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
char[] words = GetSentence(2, 4, 3);
String wordsAsString = new String(words);
double width = 3 * font.GetWidth(PdfFontUnitTest.TestFont.SIMPLE_GLYPH, FONT_SIZE);
IList<String> result = font.SplitString(wordsAsString, FONT_SIZE, (float)width + 0.01f);
NUnit.Framework.Assert.AreEqual(4, result.Count);
NUnit.Framework.Assert.AreEqual(new String(GetSentence(2)), result[0]);
NUnit.Framework.Assert.AreEqual(new String(GetSentence(3)), result[1]);
NUnit.Framework.Assert.AreEqual(new String(GetSentence(1)), result[2]);
NUnit.Framework.Assert.AreEqual(new String(GetSentence(3)), result[3]);
}
[NUnit.Framework.Test]
public virtual void SplitSentenceSymbolDoesNotFitLineTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
char[] words = GetSentence(3);
String wordsAsString = new String(words);
double width = font.GetWidth(PdfFontUnitTest.TestFont.SIMPLE_GLYPH, FONT_SIZE) / 2.0;
IList<String> result = font.SplitString(wordsAsString, FONT_SIZE, (float)width + 0.01f);
NUnit.Framework.Assert.AreEqual(4, result.Count);
NUnit.Framework.Assert.AreEqual(new String(GetSentence(1)), result[0]);
NUnit.Framework.Assert.AreEqual(new String(GetSentence(1)), result[1]);
NUnit.Framework.Assert.AreEqual(new String(GetSentence(1)), result[2]);
NUnit.Framework.Assert.AreEqual(new String(GetSentence(0)), result[3]);
}
[NUnit.Framework.Test]
public virtual void SplitSentenceWithLineBreakTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
char[] words = new char[] { (char)PdfFontUnitTest.TestFont.SIMPLE_GLYPH, '\n', (char)PdfFontUnitTest.TestFont
.SIMPLE_GLYPH };
String wordsAsString = new String(words);
double width = 10 * font.GetWidth(PdfFontUnitTest.TestFont.SIMPLE_GLYPH, FONT_SIZE);
IList<String> result = font.SplitString(wordsAsString, FONT_SIZE, (float)width + 0.01f);
NUnit.Framework.Assert.AreEqual(2, result.Count);
NUnit.Framework.Assert.AreEqual(new String(GetSentence(1)), result[0]);
NUnit.Framework.Assert.AreEqual(new String(GetSentence(1)), result[1]);
}
[NUnit.Framework.Test]
public virtual void IsBuiltWithTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
NUnit.Framework.Assert.IsFalse(font.IsBuiltWith("Any String Here", "Any Encoding"));
}
[NUnit.Framework.Test]
public virtual void IsWrappedObjectMustBeIndirectTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
NUnit.Framework.Assert.IsTrue(font.IsWrappedObjectMustBeIndirect());
}
[NUnit.Framework.Test]
public virtual void UpdateEmbeddedSubsetPrefixTest() {
String fontName = "FontTest";
String embeddedSubsetFontName = PdfFontUnitTest.TestFont.UpdateSubsetPrefix(fontName, true, true);
String onlySubsetFontName = PdfFontUnitTest.TestFont.UpdateSubsetPrefix(fontName, true, false);
String onlyEmbeddedFontName = PdfFontUnitTest.TestFont.UpdateSubsetPrefix(fontName, false, true);
String justFontName = PdfFontUnitTest.TestFont.UpdateSubsetPrefix(fontName, false, false);
NUnit.Framework.Assert.AreEqual(fontName, onlySubsetFontName);
NUnit.Framework.Assert.AreEqual(fontName, onlyEmbeddedFontName);
NUnit.Framework.Assert.AreEqual(fontName, justFontName);
Regex prefixPattern = TSpdf.Commons.Utils.StringUtil.RegexCompile("^[A-Z]{6}\\+FontTest$");
NUnit.Framework.Assert.IsTrue(TSpdf.Commons.Utils.Matcher.Match(prefixPattern, embeddedSubsetFontName).Matches
());
}
[NUnit.Framework.Test]
public virtual void GetEmptyPdfStreamTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => font.GetPdfFontStream(null, null));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.FONT_EMBEDDING_ISSUE, e.Message);
}
[NUnit.Framework.Test]
public virtual void GetPdfStreamTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
byte[] data = new byte[10];
for (int i = 0; i < 10; i++) {
data[i] = (byte)i;
}
int[] fontStreamLength = new int[] { 10, 20, 30 };
PdfStream stream = font.GetPdfFontStream(data, fontStreamLength);
NUnit.Framework.Assert.AreEqual(data, stream.GetBytes());
NUnit.Framework.Assert.AreEqual(10, stream.GetAsNumber(new PdfName("Length1")).IntValue());
NUnit.Framework.Assert.AreEqual(20, stream.GetAsNumber(new PdfName("Length2")).IntValue());
NUnit.Framework.Assert.AreEqual(30, stream.GetAsNumber(new PdfName("Length3")).IntValue());
}
[NUnit.Framework.Test]
public virtual void GetFontProgramTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
PdfFontUnitTest.TestFontProgram program = new PdfFontUnitTest.TestFontProgram();
NUnit.Framework.Assert.IsNull(font.GetFontProgram());
font.SetFontProgram(program);
NUnit.Framework.Assert.AreEqual(program, font.GetFontProgram());
}
[NUnit.Framework.Test]
public virtual void ToStringTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
NUnit.Framework.Assert.AreEqual("PdfFont{fontProgram=" + font.fontProgram + "}", font.ToString());
}
[NUnit.Framework.Test]
public virtual void MakeObjectIndirectWhileFontIsIndirectTest() {
using (PdfDocument document = new PdfDocument(new PdfWriter(new MemoryStream()))) {
// to avoid an exception
document.AddNewPage();
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
font.GetPdfObject().MakeIndirect(document);
PdfDictionary dictionary = new PdfDictionary();
NUnit.Framework.Assert.IsTrue(font.MakeObjectIndirect(dictionary));
NUnit.Framework.Assert.IsNotNull(dictionary.GetIndirectReference());
NUnit.Framework.Assert.AreEqual(document, dictionary.GetIndirectReference().GetDocument());
}
}
[NUnit.Framework.Test]
public virtual void MakeObjectIndirectWhileFontIsDirectTest() {
PdfFontUnitTest.TestFont font = new PdfFontUnitTest.TestFont();
PdfDictionary dictionary = new PdfDictionary();
NUnit.Framework.Assert.IsFalse(font.MakeObjectIndirect(dictionary));
NUnit.Framework.Assert.IsNull(dictionary.GetIndirectReference());
}
private char[] GetSentence(params int[] lengthsOfWords) {
int length = 0;
foreach (int lengthOfWord in lengthsOfWords) {
length += lengthOfWord;
}
int numberOfSpaces = lengthsOfWords.Length - 1;
length += numberOfSpaces;
char[] sentence = new char[length];
int index = 0;
foreach (int lengthOfWord in lengthsOfWords) {
for (int i = 0; i < lengthOfWord; i++) {
sentence[index] = (char)PdfFontUnitTest.TestFont.SIMPLE_GLYPH;
index++;
}
if (index < length) {
sentence[index] = ' ';
index++;
}
}
return sentence;
}
[NUnit.Framework.Test]
public virtual void CannotGetFontStreamForNullBytesTest() {
PdfFont pdfFont = PdfFontFactory.CreateFont();
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfFont.GetPdfFontStream(null
, new int[] { 1 }));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.FONT_EMBEDDING_ISSUE, exception.Message);
}
[NUnit.Framework.Test]
public virtual void CannotGetFontStreamForNullLengthsTest() {
PdfFont pdfFont = PdfFontFactory.CreateFont();
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfFont.GetPdfFontStream(new
byte[] { 1 }, null));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.FONT_EMBEDDING_ISSUE, exception.Message);
}
[NUnit.Framework.Test]
public virtual void CannotGetFontStreamForNullBytesAndLengthsTest() {
PdfFont pdfFont = PdfFontFactory.CreateFont();
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfFont.GetPdfFontStream(null
, null));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.FONT_EMBEDDING_ISSUE, exception.Message);
}
}
}

View File

@@ -0,0 +1,255 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System.Collections.Generic;
using System.IO;
using TSpdf.IO.Font;
using TSpdf.IO.Font.Constants;
using TSpdf.IO.Font.Otf;
using TSpdf.Kernel.Pdf;
using TSpdf.Test;
namespace TSpdf.Kernel.Font {
[NUnit.Framework.Category("UnitTest")]
public class PdfSimpleFontTest : ExtendedTSpdfTest {
private const byte T_CODE = 116;
private const byte E_CODE = 101;
private const byte E_CUSTOM_CODE = 103;
private const byte OPEN_BRACKET_CODE = 40;
private const byte CLOSE_BRACKET_CODE = 41;
private static Glyph E_GLYPH_FONT_SPECIFIC;
private static Glyph T_GLYPH_FONT_SPECIFIC;
private static Glyph E_GLYPH_CUSTOM_MAPPED;
[NUnit.Framework.OneTimeSetUp]
public static void Init() {
T_GLYPH_FONT_SPECIFIC = new Glyph(T_CODE, 278, 116, new int[] { 14, -7, 257, 669 });
T_GLYPH_FONT_SPECIFIC.SetChars(new char[] { 't' });
E_GLYPH_FONT_SPECIFIC = new Glyph(E_CODE, 556, 101, new int[] { 40, -15, 516, 538 });
E_GLYPH_FONT_SPECIFIC.SetChars(new char[] { 'e' });
E_GLYPH_CUSTOM_MAPPED = new Glyph(E_CUSTOM_CODE, 44, 103);
E_GLYPH_CUSTOM_MAPPED.SetChars(new char[] { 'e' });
}
[NUnit.Framework.Test]
public virtual void CreateGlyphLineWithSpecificEncodingTest() {
PdfSimpleFont<FontProgram> fontToTest = new PdfSimpleFontTest.TestSimpleFont(FontEncoding.CreateFontSpecificEncoding
());
GlyphLine glyphLine = fontToTest.CreateGlyphLine("te");
IList<Glyph> glyphs = new List<Glyph>();
glyphs.Add(T_GLYPH_FONT_SPECIFIC);
glyphs.Add(E_GLYPH_FONT_SPECIFIC);
GlyphLine expected = new GlyphLine(glyphs, 0, 2);
NUnit.Framework.Assert.AreEqual(expected, glyphLine);
}
[NUnit.Framework.Test]
public virtual void CreateGlyphLineWithEmptyEncodingTest() {
PdfSimpleFont<FontProgram> fontToTest = new PdfSimpleFontTest.TestSimpleFont(FontEncoding.CreateEmptyFontEncoding
());
GlyphLine glyphLine = fontToTest.CreateGlyphLine("te");
IList<Glyph> glyphs = new List<Glyph>();
glyphs.Add(E_GLYPH_CUSTOM_MAPPED);
GlyphLine expected = new GlyphLine(glyphs, 0, 1);
NUnit.Framework.Assert.AreEqual(expected, glyphLine);
}
[NUnit.Framework.Test]
public virtual void AppendGlyphsWithSpecificEncodingTest() {
PdfSimpleFont<FontProgram> fontToTest = new PdfSimpleFontTest.TestSimpleFont(FontEncoding.CreateFontSpecificEncoding
());
IList<Glyph> toAppend = new List<Glyph>();
int processed = fontToTest.AppendGlyphs("te", 0, 1, toAppend);
NUnit.Framework.Assert.AreEqual(2, processed);
IList<Glyph> glyphs = new List<Glyph>();
glyphs.Add(T_GLYPH_FONT_SPECIFIC);
glyphs.Add(E_GLYPH_FONT_SPECIFIC);
NUnit.Framework.Assert.AreEqual(glyphs, toAppend);
}
[NUnit.Framework.Test]
public virtual void AppendGlyphsWithEmptyEncodingTest() {
PdfSimpleFont<FontProgram> fontToTest = new PdfSimpleFontTest.TestSimpleFont(FontEncoding.CreateEmptyFontEncoding
());
IList<Glyph> toAppend = new List<Glyph>();
int processed = fontToTest.AppendGlyphs("e ete", 0, 4, toAppend);
NUnit.Framework.Assert.AreEqual(3, processed);
IList<Glyph> glyphs = new List<Glyph>();
glyphs.Add(E_GLYPH_CUSTOM_MAPPED);
glyphs.Add(E_GLYPH_CUSTOM_MAPPED);
NUnit.Framework.Assert.AreEqual(glyphs, toAppend);
}
[NUnit.Framework.Test]
public virtual void AppendAnyGlyphWithSpecificEncodingTest() {
PdfSimpleFont<FontProgram> fontToTest = new PdfSimpleFontTest.TestSimpleFont(FontEncoding.CreateFontSpecificEncoding
());
IList<Glyph> toAppend = new List<Glyph>();
int processed = fontToTest.AppendAnyGlyph("te", 0, toAppend);
NUnit.Framework.Assert.AreEqual(1, processed);
IList<Glyph> glyphs = new List<Glyph>();
glyphs.Add(T_GLYPH_FONT_SPECIFIC);
NUnit.Framework.Assert.AreEqual(glyphs, toAppend);
}
[NUnit.Framework.Test]
public virtual void AppendAnyGlyphWithEmptyEncodingTest() {
PdfSimpleFont<FontProgram> fontToTest = new PdfSimpleFontTest.TestSimpleFont(FontEncoding.CreateEmptyFontEncoding
());
IList<Glyph> toAppend = new List<Glyph>();
int processed = fontToTest.AppendAnyGlyph("e ete", 0, toAppend);
NUnit.Framework.Assert.AreEqual(1, processed);
IList<Glyph> glyphs = new List<Glyph>();
glyphs.Add(E_GLYPH_CUSTOM_MAPPED);
NUnit.Framework.Assert.AreEqual(glyphs, toAppend);
}
[NUnit.Framework.Test]
public virtual void ConvertGlyphLineToBytesWithSpecificEncodingTest() {
PdfSimpleFont<FontProgram> fontToTest = new PdfSimpleFontTest.TestSimpleFont(FontEncoding.CreateFontSpecificEncoding
());
IList<Glyph> glyphs = new List<Glyph>();
glyphs.Add(T_GLYPH_FONT_SPECIFIC);
glyphs.Add(E_GLYPH_FONT_SPECIFIC);
GlyphLine glyphLine = new GlyphLine(glyphs, 0, 2);
byte[] bytes = fontToTest.ConvertToBytes(glyphLine);
NUnit.Framework.Assert.AreEqual(new byte[] { T_CODE, E_CODE }, bytes);
}
[NUnit.Framework.Test]
public virtual void ConvertGlyphLineToBytesWithEmptyEncodingTest() {
PdfSimpleFont<FontProgram> fontToTest = new PdfSimpleFontTest.TestSimpleFont(FontEncoding.CreateEmptyFontEncoding
());
IList<Glyph> glyphs = new List<Glyph>();
glyphs.Add(T_GLYPH_FONT_SPECIFIC);
glyphs.Add(E_GLYPH_FONT_SPECIFIC);
GlyphLine glyphLine = new GlyphLine(glyphs, 0, 2);
byte[] bytes = fontToTest.ConvertToBytes(glyphLine);
NUnit.Framework.Assert.AreEqual(new byte[0], bytes);
}
[NUnit.Framework.Test]
public virtual void ConvertToBytesWithNullEntry() {
PdfSimpleFont<FontProgram> fontToTest = new PdfSimpleFontTest.TestSimpleFont(FontEncoding.CreateEmptyFontEncoding
());
byte[] bytes = fontToTest.ConvertToBytes((GlyphLine)null);
NUnit.Framework.Assert.AreEqual(new byte[0], bytes);
}
[NUnit.Framework.Test]
public virtual void ConvertGlyphToBytesWithSpecificEncodingTest() {
PdfSimpleFont<FontProgram> fontToTest = new PdfSimpleFontTest.TestSimpleFont(FontEncoding.CreateFontSpecificEncoding
());
byte[] bytes = fontToTest.ConvertToBytes(E_GLYPH_FONT_SPECIFIC);
NUnit.Framework.Assert.AreEqual(new byte[] { E_CODE }, bytes);
}
[NUnit.Framework.Test]
public virtual void ConvertGlyphToBytesWithCustomEncodingTest() {
FontEncoding emptyFontEncoding = FontEncoding.CreateEmptyFontEncoding();
emptyFontEncoding.AddSymbol(E_CUSTOM_CODE, E_CODE);
PdfSimpleFont<FontProgram> fontToTest = new PdfSimpleFontTest.TestSimpleFont(emptyFontEncoding);
byte[] bytes = fontToTest.ConvertToBytes(E_GLYPH_FONT_SPECIFIC);
NUnit.Framework.Assert.AreEqual(new byte[] { E_CUSTOM_CODE }, bytes);
}
[NUnit.Framework.Test]
public virtual void ConvertGlyphToBytesWithEmptyEncodingTest() {
PdfSimpleFont<FontProgram> fontToTest = new PdfSimpleFontTest.TestSimpleFont(FontEncoding.CreateEmptyFontEncoding
());
byte[] bytes = fontToTest.ConvertToBytes(E_GLYPH_FONT_SPECIFIC);
NUnit.Framework.Assert.AreEqual(new byte[0], bytes);
}
[NUnit.Framework.Test]
public virtual void WriteTextGlyphLineWithSpecificEncodingTest() {
PdfSimpleFont<FontProgram> fontToTest = new PdfSimpleFontTest.TestSimpleFont(FontEncoding.CreateFontSpecificEncoding
());
IList<Glyph> glyphs = new List<Glyph>();
glyphs.Add(T_GLYPH_FONT_SPECIFIC);
glyphs.Add(E_GLYPH_FONT_SPECIFIC);
GlyphLine glyphLine = new GlyphLine(glyphs, 0, 2);
MemoryStream bos = new MemoryStream();
using (PdfOutputStream pos = new PdfOutputStream(bos)) {
fontToTest.WriteText(glyphLine, 0, 1, pos);
}
NUnit.Framework.Assert.AreEqual(new byte[] { OPEN_BRACKET_CODE, T_CODE, E_CODE, CLOSE_BRACKET_CODE }, bos.
ToArray());
}
[NUnit.Framework.Test]
public virtual void WriteTextGlyphLineWithCustomEncodingTest() {
FontEncoding fontEncoding = FontEncoding.CreateEmptyFontEncoding();
fontEncoding.AddSymbol(E_CUSTOM_CODE, E_CODE);
PdfSimpleFont<FontProgram> fontToTest = new PdfSimpleFontTest.TestSimpleFont(fontEncoding);
IList<Glyph> glyphs = new List<Glyph>();
glyphs.Add(E_GLYPH_FONT_SPECIFIC);
glyphs.Add(T_GLYPH_FONT_SPECIFIC);
GlyphLine glyphLine = new GlyphLine(glyphs, 0, 2);
MemoryStream bos = new MemoryStream();
using (PdfOutputStream pos = new PdfOutputStream(bos)) {
fontToTest.WriteText(glyphLine, 0, 1, pos);
}
NUnit.Framework.Assert.AreEqual(new byte[] { OPEN_BRACKET_CODE, E_CUSTOM_CODE, CLOSE_BRACKET_CODE }, bos.ToArray
());
}
[NUnit.Framework.Test]
public virtual void WriteTextGlyphLineWithEmptyEncodingTest() {
PdfSimpleFont<FontProgram> fontToTest = new PdfSimpleFontTest.TestSimpleFont(FontEncoding.CreateEmptyFontEncoding
());
IList<Glyph> glyphs = new List<Glyph>();
glyphs.Add(E_GLYPH_FONT_SPECIFIC);
glyphs.Add(T_GLYPH_FONT_SPECIFIC);
GlyphLine glyphLine = new GlyphLine(glyphs, 0, 2);
MemoryStream bos = new MemoryStream();
using (PdfOutputStream pos = new PdfOutputStream(bos)) {
fontToTest.WriteText(glyphLine, 0, 1, pos);
}
NUnit.Framework.Assert.AreEqual(new byte[] { OPEN_BRACKET_CODE, CLOSE_BRACKET_CODE }, bos.ToArray());
}
private class TestSimpleFont : PdfSimpleFont<FontProgram> {
public TestSimpleFont(FontEncoding fontEncoding) {
this.fontEncoding = fontEncoding;
SetFontProgram(FontProgramFactory.CreateFont(StandardFonts.HELVETICA));
}
public override Glyph GetGlyph(int unicode) {
if (unicode == E_CODE) {
return E_GLYPH_CUSTOM_MAPPED;
}
return null;
}
protected internal override void AddFontStream(PdfDictionary fontDescriptor) {
}
}
}
}

View File

@@ -0,0 +1,71 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.IO.Font;
using TSpdf.IO.Font.Constants;
using TSpdf.Kernel.Pdf;
using TSpdf.Test;
namespace TSpdf.Kernel.Font {
[NUnit.Framework.Category("UnitTest")]
public class PdfTrueTypeFontTest : ExtendedTSpdfTest {
public static readonly String SOURCE_FOLDER = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/font/PdfTrueTypeFontTest/";
[NUnit.Framework.Test]
public virtual void TestReadingPdfTrueTypeFontWithType1StandardFontProgram() {
// We deliberately use an existing PDF in this test and not simplify the test to create the
// PDF object structure on the fly to be able to easily inspect the PDF with other processors
String filePath = SOURCE_FOLDER + "trueTypeFontWithStandardFontProgram.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(filePath));
PdfDictionary fontDict = pdfDocument.GetPage(1).GetResources().GetResource(PdfName.Font).GetAsDictionary(new
PdfName("F1"));
PdfFont pdfFont = PdfFontFactory.CreateFont(fontDict);
NUnit.Framework.Assert.AreEqual(542, pdfFont.GetFontProgram().GetAvgWidth());
NUnit.Framework.Assert.AreEqual(556, pdfFont.GetGlyph('a').GetWidth());
}
[NUnit.Framework.Test]
public virtual void IsBuiltInTest() {
PdfFont font = PdfFontFactory.CreateFont(CreateTrueTypeFontDictionaryWithStandardHelveticaFont());
NUnit.Framework.Assert.IsTrue(font is PdfTrueTypeFont);
NUnit.Framework.Assert.IsTrue(((PdfTrueTypeFont)font).IsBuiltInFont());
}
[NUnit.Framework.Test]
public virtual void IsNotBuiltInTest() {
PdfFont font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "NotoSans-Regular.ttf", PdfEncodings.WINANSI);
NUnit.Framework.Assert.IsTrue(font is PdfTrueTypeFont);
NUnit.Framework.Assert.IsFalse(((PdfTrueTypeFont)font).IsBuiltInFont());
}
private static PdfDictionary CreateTrueTypeFontDictionaryWithStandardHelveticaFont() {
PdfDictionary fontDictionary = new PdfDictionary();
fontDictionary.Put(PdfName.Type, PdfName.Font);
fontDictionary.Put(PdfName.Subtype, PdfName.TrueType);
fontDictionary.Put(PdfName.Encoding, PdfName.WinAnsiEncoding);
fontDictionary.Put(PdfName.BaseFont, new PdfName(StandardFonts.HELVETICA));
return fontDictionary;
}
}
}

View File

@@ -0,0 +1,107 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using TSpdf.IO.Font;
using TSpdf.IO.Font.Otf;
using TSpdf.Kernel.Exceptions;
using TSpdf.Kernel.Pdf;
using TSpdf.Test;
namespace TSpdf.Kernel.Font {
[NUnit.Framework.Category("UnitTest")]
public class PdfType0FontTest : ExtendedTSpdfTest {
public static readonly String DESTINATION_FOLDER = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/resources/TSpdf/kernel/font/PdfType0FontTest/";
public static readonly String SOURCE_FOLDER = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/font/PdfType0FontTest/";
[NUnit.Framework.Test]
public virtual void TrueTypeFontAndCmapConstructorTest() {
TrueTypeFont ttf = new TrueTypeFont(SOURCE_FOLDER + "NotoSerif-Regular_v1.7.ttf");
PdfType0Font type0Font = new PdfType0Font(ttf, PdfEncodings.IDENTITY_H);
CMapEncoding cmap = type0Font.GetCmap();
NUnit.Framework.Assert.IsNotNull(cmap);
NUnit.Framework.Assert.IsTrue(cmap.IsDirect());
NUnit.Framework.Assert.IsFalse(cmap.HasUniMap());
NUnit.Framework.Assert.IsNull(cmap.GetUniMapName());
NUnit.Framework.Assert.AreEqual("Adobe", cmap.GetRegistry());
NUnit.Framework.Assert.AreEqual("Identity", cmap.GetOrdering());
NUnit.Framework.Assert.AreEqual(0, cmap.GetSupplement());
NUnit.Framework.Assert.AreEqual(PdfEncodings.IDENTITY_H, cmap.GetCmapName());
}
[NUnit.Framework.Test]
public virtual void UnsupportedCmapTest() {
TrueTypeFont ttf = new TrueTypeFont(SOURCE_FOLDER + "NotoSerif-Regular_v1.7.ttf");
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => new PdfType0Font(ttf, PdfEncodings.
WINANSI));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.ONLY_IDENTITY_CMAPS_SUPPORTS_WITH_TRUETYPE,
e.Message);
}
[NUnit.Framework.Test]
public virtual void DictionaryConstructorTest() {
String filePath = SOURCE_FOLDER + "documentWithType0Noto.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(filePath));
PdfDictionary fontDict = pdfDocument.GetPage(1).GetResources().GetResource(PdfName.Font).GetAsDictionary(new
PdfName("F1"));
PdfType0Font type0Font = new PdfType0Font(fontDict);
CMapEncoding cmap = type0Font.GetCmap();
NUnit.Framework.Assert.IsNotNull(cmap);
NUnit.Framework.Assert.IsTrue(cmap.IsDirect());
NUnit.Framework.Assert.IsFalse(cmap.HasUniMap());
NUnit.Framework.Assert.IsNull(cmap.GetUniMapName());
NUnit.Framework.Assert.AreEqual("Adobe", cmap.GetRegistry());
NUnit.Framework.Assert.AreEqual("Identity", cmap.GetOrdering());
NUnit.Framework.Assert.AreEqual(0, cmap.GetSupplement());
NUnit.Framework.Assert.AreEqual(PdfEncodings.IDENTITY_H, cmap.GetCmapName());
}
[NUnit.Framework.Test]
public virtual void AppendThreeSurrogatePairsTest() {
// this text contains three successive surrogate pairs, which should result in three glyphs
String textWithThreeSurrogatePairs = "\uD800\uDF10\uD800\uDF00\uD800\uDF11";
PdfFont type0Font = PdfFontFactory.CreateFont(SOURCE_FOLDER + "NotoSansOldItalic-Regular.ttf", PdfEncodings
.IDENTITY_H);
IList<Glyph> glyphs = new List<Glyph>();
type0Font.AppendGlyphs(textWithThreeSurrogatePairs, 0, textWithThreeSurrogatePairs.Length - 1, glyphs);
NUnit.Framework.Assert.AreEqual(3, glyphs.Count);
}
[NUnit.Framework.Test]
public virtual void GetUniMapFromOrderingTest() {
NUnit.Framework.Assert.AreEqual("UniCNS-UTF16-H", PdfType0Font.GetUniMapFromOrdering("CNS1", true));
NUnit.Framework.Assert.AreEqual("UniCNS-UTF16-V", PdfType0Font.GetUniMapFromOrdering("CNS1", false));
NUnit.Framework.Assert.AreEqual("UniJIS-UTF16-H", PdfType0Font.GetUniMapFromOrdering("Japan1", true));
NUnit.Framework.Assert.AreEqual("UniJIS-UTF16-V", PdfType0Font.GetUniMapFromOrdering("Japan1", false));
NUnit.Framework.Assert.AreEqual("UniKS-UTF16-H", PdfType0Font.GetUniMapFromOrdering("Korea1", true));
NUnit.Framework.Assert.AreEqual("UniKS-UTF16-V", PdfType0Font.GetUniMapFromOrdering("Korea1", false));
NUnit.Framework.Assert.AreEqual("UniGB-UTF16-H", PdfType0Font.GetUniMapFromOrdering("GB1", true));
NUnit.Framework.Assert.AreEqual("UniGB-UTF16-V", PdfType0Font.GetUniMapFromOrdering("GB1", false));
NUnit.Framework.Assert.AreEqual("Identity-H", PdfType0Font.GetUniMapFromOrdering("Identity", true));
NUnit.Framework.Assert.AreEqual("Identity-V", PdfType0Font.GetUniMapFromOrdering("Identity", false));
}
}
}

View File

@@ -0,0 +1,294 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.Commons.Utils;
using TSpdf.IO.Font.Otf;
using TSpdf.Kernel.Exceptions;
using TSpdf.Kernel.Pdf;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.Kernel.Font {
[NUnit.Framework.Category("UnitTest")]
public class PdfType3FontTest : ExtendedTSpdfTest {
private const float EPS = 1e-4f;
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.TYPE3_FONT_INITIALIZATION_ISSUE)]
public virtual void AddDifferentGlyphsInConstructorTest() {
PdfDictionary dictionary = new PdfDictionary();
dictionary.Put(PdfName.FontMatrix, new PdfArray());
PdfDictionary charProcs = new PdfDictionary();
charProcs.Put(new PdfName("space"), new PdfStream());
charProcs.Put(new PdfName("A"), new PdfStream());
dictionary.Put(PdfName.CharProcs, charProcs);
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);
NUnit.Framework.Assert.IsNotNull(type3Font.GetFontProgram());
int spaceGlyphCode = 32;
Glyph glyph = type3Font.GetFontProgram().GetGlyph(spaceGlyphCode);
NUnit.Framework.Assert.AreEqual(new Glyph(spaceGlyphCode, 0, new char[] { ' ' }), glyph);
int AGlyphCode = 65;
glyph = type3Font.GetFontProgram().GetGlyph(AGlyphCode);
NUnit.Framework.Assert.AreEqual(new Glyph(AGlyphCode, 0, new char[] { 'A' }), glyph);
}
private sealed class _PdfType3Font_62 : PdfType3Font {
public _PdfType3Font_62(PdfDictionary baseArg1)
: base(baseArg1) {
}
protected internal override PdfDocument GetDocument() {
return null;
}
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.TYPE3_FONT_INITIALIZATION_ISSUE)]
public virtual void AddAlreadyExistingGlyphTest() {
PdfDictionary dictionary = new PdfDictionary();
dictionary.Put(PdfName.FontMatrix, new PdfArray());
PdfDictionary charProcs = new PdfDictionary();
charProcs.Put(new PdfName("A"), new PdfStream());
dictionary.Put(PdfName.CharProcs, charProcs);
dictionary.Put(PdfName.Widths, new PdfArray());
PdfType3Font type3Font = new _PdfType3Font_87(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);
NUnit.Framework.Assert.AreEqual(0, type3Glyph.GetLly(), EPS);
NUnit.Framework.Assert.AreEqual(0, type3Glyph.GetUrx(), EPS);
NUnit.Framework.Assert.AreEqual(0, type3Glyph.GetUry(), EPS);
}
private sealed class _PdfType3Font_87 : PdfType3Font {
public _PdfType3Font_87(PdfDictionary baseArg1)
: base(baseArg1) {
}
protected internal override PdfDocument GetDocument() {
return null;
}
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.TYPE3_FONT_INITIALIZATION_ISSUE)]
public virtual void SetFontStretchTest() {
PdfDictionary dictionary = new PdfDictionary();
dictionary.Put(PdfName.FontMatrix, new PdfArray());
PdfDictionary charProcs = new PdfDictionary();
dictionary.Put(PdfName.CharProcs, charProcs);
dictionary.Put(PdfName.Widths, new PdfArray());
PdfType3Font type3Font = new PdfType3Font(dictionary);
String fontStretch = "test";
type3Font.SetFontStretch(fontStretch);
NUnit.Framework.Assert.IsNotNull(type3Font.fontProgram);
NUnit.Framework.Assert.IsNotNull(type3Font.fontProgram.GetFontNames());
NUnit.Framework.Assert.AreEqual(fontStretch, type3Font.fontProgram.GetFontNames().GetFontStretch());
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.TYPE3_FONT_INITIALIZATION_ISSUE)]
public virtual void SetPdfFontFlagsTest() {
PdfDictionary dictionary = new PdfDictionary();
dictionary.Put(PdfName.FontMatrix, new PdfArray());
PdfDictionary charProcs = new PdfDictionary();
dictionary.Put(PdfName.CharProcs, charProcs);
dictionary.Put(PdfName.Widths, new PdfArray());
PdfType3Font type3Font = new PdfType3Font(dictionary);
int randomTestFontFlagsValue = 5;
type3Font.SetPdfFontFlags(randomTestFontFlagsValue);
NUnit.Framework.Assert.IsNotNull(type3Font.fontProgram);
NUnit.Framework.Assert.AreEqual(randomTestFontFlagsValue, type3Font.fontProgram.GetPdfFontFlags());
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.TYPE3_FONT_INITIALIZATION_ISSUE)]
public virtual void GlyphWithUnicodeBiggerThan32CannotBeEncodedTest() {
PdfDictionary dictionary = new PdfDictionary();
dictionary.Put(PdfName.FontMatrix, new PdfArray());
PdfDictionary charProcs = new PdfDictionary();
dictionary.Put(PdfName.CharProcs, charProcs);
dictionary.Put(PdfName.Widths, new PdfArray());
PdfType3Font type3Font = new PdfType3Font(dictionary);
int cannotEncodeAndAUnicodeBiggerThan32TestValue = 333;
NUnit.Framework.Assert.IsNull(type3Font.GetGlyph(cannotEncodeAndAUnicodeBiggerThan32TestValue));
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.TYPE3_FONT_INITIALIZATION_ISSUE)]
public virtual void ContainsGlyphTest() {
PdfDictionary dictionary = new PdfDictionary();
dictionary.Put(PdfName.FontMatrix, new PdfArray());
PdfDictionary charProcs = new PdfDictionary();
dictionary.Put(PdfName.CharProcs, charProcs);
dictionary.Put(PdfName.Widths, new PdfArray());
PdfType3Font type3Font = new _PdfType3Font_157(dictionary);
NUnit.Framework.Assert.IsFalse(type3Font.ContainsGlyph(333));
NUnit.Framework.Assert.IsFalse(type3Font.ContainsGlyph(-5));
NUnit.Framework.Assert.IsFalse(type3Font.ContainsGlyph(32));
type3Font.AddGlyph(' ', 0, 0, 0, 1, 1);
NUnit.Framework.Assert.IsTrue(type3Font.ContainsGlyph(32));
type3Font.AddGlyph('A', 0, 0, 0, 0, 0);
NUnit.Framework.Assert.IsTrue(type3Font.ContainsGlyph(65));
}
private sealed class _PdfType3Font_157 : PdfType3Font {
public _PdfType3Font_157(PdfDictionary baseArg1)
: base(baseArg1) {
}
protected internal override PdfDocument GetDocument() {
return null;
}
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.TYPE3_FONT_INITIALIZATION_ISSUE)]
public virtual void FlushExceptionTest() {
PdfDictionary dictionary = new PdfDictionary();
dictionary.Put(PdfName.FontMatrix, new PdfArray());
PdfDictionary charProcs = new PdfDictionary();
dictionary.Put(PdfName.CharProcs, charProcs);
dictionary.Put(PdfName.Widths, new PdfArray());
PdfType3Font type3Font = new PdfType3FontTest.DisableEnsureUnderlyingObjectHasIndirectReference(this, dictionary
);
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => type3Font.Flush());
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.NO_GLYPHS_DEFINED_FOR_TYPE_3_FONT, e.Message
);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.TYPE3_FONT_INITIALIZATION_ISSUE)]
public virtual void FillFontDescriptorTest() {
PdfDictionary dictionary = new PdfDictionary();
dictionary.Put(PdfName.FontMatrix, new PdfArray());
PdfDictionary charProcs = new PdfDictionary();
dictionary.Put(PdfName.CharProcs, charProcs);
dictionary.Put(PdfName.Widths, new PdfArray());
PdfDictionary fontDescriptor = new PdfDictionary();
String fontStretch = "test";
fontDescriptor.Put(PdfName.FontStretch, new PdfName(fontStretch));
dictionary.Put(PdfName.FontDescriptor, fontDescriptor);
PdfType3Font type3Font = new _PdfType3Font_201(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)
: base(baseArg1) {
}
protected internal override PdfDocument GetDocument() {
return null;
}
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.TYPE3_FONT_INITIALIZATION_ISSUE)]
public virtual void NoCharProcsTest() {
PdfDictionary dictionary = new PdfDictionary();
dictionary.Put(PdfName.FontMatrix, new PdfArray());
dictionary.Put(PdfName.Widths, new PdfArray());
NUnit.Framework.Assert.DoesNotThrow(() => new PdfType3Font(dictionary));
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.TYPE3_FONT_INITIALIZATION_ISSUE)]
public virtual void NoEncodingTest() {
PdfDictionary dictionary = new PdfDictionary();
dictionary.Put(PdfName.FontMatrix, new PdfArray());
PdfDictionary charProcs = new PdfDictionary();
dictionary.Put(PdfName.CharProcs, charProcs);
dictionary.Put(PdfName.Widths, new PdfArray());
NUnit.Framework.Assert.DoesNotThrow(() => new PdfType3Font(dictionary));
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.TYPE3_FONT_INITIALIZATION_ISSUE)]
public virtual void NoDifferenceTest() {
PdfDictionary dictionary = new PdfDictionary();
dictionary.Put(PdfName.FontMatrix, new PdfArray());
PdfDictionary charProcs = new PdfDictionary();
dictionary.Put(PdfName.CharProcs, charProcs);
dictionary.Put(PdfName.Widths, new PdfArray());
PdfDictionary encoding = new PdfDictionary();
dictionary.Put(PdfName.Encoding, encoding);
NUnit.Framework.Assert.DoesNotThrow(() => new PdfType3Font(dictionary));
}
[NUnit.Framework.Test]
public virtual void MissingFontMatrixTest() {
PdfDictionary dictionary = new PdfDictionary();
dictionary.Put(PdfName.Widths, new PdfArray());
dictionary.Put(PdfName.ToUnicode, PdfName.IdentityH);
dictionary.Put(PdfName.Encoding, new PdfName("zapfdingbatsencoding"));
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => new PdfType3Font(dictionary));
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(KernelExceptionMessageConstant.MISSING_REQUIRED_FIELD_IN_FONT_DICTIONARY
, PdfName.FontMatrix), e.Message);
}
[NUnit.Framework.Test]
public virtual void MissingWidthsTest() {
PdfDictionary dictionary = new PdfDictionary();
dictionary.Put(PdfName.FontMatrix, new PdfArray());
dictionary.Put(PdfName.ToUnicode, PdfName.IdentityH);
dictionary.Put(PdfName.Encoding, new PdfName("zapfdingbatsencoding"));
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => new PdfType3Font(dictionary));
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(KernelExceptionMessageConstant.MISSING_REQUIRED_FIELD_IN_FONT_DICTIONARY
, PdfName.Widths), e.Message);
}
[NUnit.Framework.Test]
public virtual void NoCharProcGlyphForDifferenceTest() {
PdfDictionary font = new PdfDictionary();
font.Put(PdfName.FontMatrix, new PdfArray());
font.Put(PdfName.Widths, new PdfArray());
font.Put(PdfName.CharProcs, new PdfDictionary());
PdfDictionary encoding = new PdfDictionary();
PdfArray differences = new PdfArray();
differences.Add(0, new PdfNumber(65));
differences.Add(1, new PdfName("A"));
encoding.Put(PdfName.Differences, differences);
font.Put(PdfName.Encoding, encoding);
NUnit.Framework.Assert.DoesNotThrow(() => new PdfType3Font(font));
}
private class DisableEnsureUnderlyingObjectHasIndirectReference : PdfType3Font {
internal DisableEnsureUnderlyingObjectHasIndirectReference(PdfType3FontTest _enclosing, PdfDictionary fontDictionary
)
: base(fontDictionary) {
this._enclosing = _enclosing;
}
protected internal override void EnsureUnderlyingObjectHasIndirectReference() {
}
private readonly PdfType3FontTest _enclosing;
}
}
}

View File

@@ -0,0 +1,114 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using TSpdf.Test;
namespace TSpdf.Kernel.Font {
[NUnit.Framework.Category("UnitTest")]
public class Type3FontTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void AddGlyphTest() {
Type3Font font = new Type3Font(false);
font.AddGlyph(1, 1, 600, null, null);
NUnit.Framework.Assert.AreEqual(1, font.GetNumberOfGlyphs());
}
[NUnit.Framework.Test]
public virtual void AddGlyphsWithDifferentUnicodeTest() {
Type3Font font = new Type3Font(false);
font.AddGlyph(1, 1, 600, null, null);
font.AddGlyph(2, 2, 600, null, null);
NUnit.Framework.Assert.AreEqual(2, font.GetNumberOfGlyphs());
NUnit.Framework.Assert.AreEqual(1, font.GetGlyphByCode(1).GetUnicode());
NUnit.Framework.Assert.AreEqual(2, font.GetGlyphByCode(2).GetUnicode());
}
[NUnit.Framework.Test]
public virtual void AddGlyphsWithDifferentCodesTest() {
Type3Font font = new Type3Font(false);
font.AddGlyph(1, -1, 600, null, null);
font.AddGlyph(2, -1, 700, null, null);
NUnit.Framework.Assert.AreEqual(2, font.GetNumberOfGlyphs());
NUnit.Framework.Assert.AreEqual(600, font.GetGlyphByCode(1).GetWidth());
NUnit.Framework.Assert.AreEqual(700, font.GetGlyphByCode(2).GetWidth());
}
[NUnit.Framework.Test]
public virtual void ReplaceGlyphsWithSameUnicodeTest() {
Type3Font font = new Type3Font(false);
font.AddGlyph(1, 1, 600, null, null);
font.AddGlyph(2, 1, 600, null, null);
NUnit.Framework.Assert.AreEqual(1, font.GetNumberOfGlyphs());
NUnit.Framework.Assert.AreEqual(2, font.GetGlyph(1).GetCode());
}
[NUnit.Framework.Test]
public virtual void ReplaceGlyphWithSameCodeTest() {
Type3Font font = new Type3Font(false);
font.AddGlyph(1, -1, 600, null, null);
font.AddGlyph(1, -1, 700, null, null);
NUnit.Framework.Assert.AreEqual(1, font.GetNumberOfGlyphs());
NUnit.Framework.Assert.AreEqual(700, font.GetGlyphByCode(1).GetWidth());
}
[NUnit.Framework.Test]
public virtual void NotAddGlyphWithSameCodeEmptyUnicodeFirstTest() {
Type3Font font = new Type3Font(false);
font.AddGlyph(1, -1, 600, null, null);
font.AddGlyph(1, 100, 600, null, null);
NUnit.Framework.Assert.AreEqual(1, font.GetNumberOfGlyphs());
NUnit.Framework.Assert.AreEqual(1, font.GetGlyph(100).GetCode());
NUnit.Framework.Assert.AreEqual(100, font.GetGlyphByCode(1).GetUnicode());
}
[NUnit.Framework.Test]
public virtual void ReplaceGlyphWithSameCodeEmptyUnicodeLastTest() {
Type3Font font = new Type3Font(false);
font.AddGlyph(1, 100, 600, null, null);
font.AddGlyph(1, -1, 600, null, null);
NUnit.Framework.Assert.IsNull(font.GetGlyph(-1));
NUnit.Framework.Assert.IsNull(font.GetGlyph(100));
NUnit.Framework.Assert.AreEqual(1, font.GetNumberOfGlyphs());
NUnit.Framework.Assert.AreEqual(-1, font.GetGlyphByCode(1).GetUnicode());
}
}
}

View File

@@ -0,0 +1,66 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using System.IO;
using TSpdf.IO.Image;
using TSpdf.Kernel.Exceptions;
using TSpdf.Kernel.Pdf;
using TSpdf.Test;
namespace TSpdf.Kernel.Font {
[NUnit.Framework.Category("UnitTest")]
public class Type3GlyphUnitTest : ExtendedTSpdfTest {
private static readonly String SOURCE_FOLDER = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/font/Type3GlyphUnitTest/";
[NUnit.Framework.Test]
public virtual void AddImageWithoutMaskTest() {
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(new MemoryStream()));
Type3Glyph glyph = new Type3Glyph(new PdfStream(), pdfDoc);
ImageData img = ImageDataFactory.Create(SOURCE_FOLDER + "imageTest.png");
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => glyph.AddImageWithTransformationMatrix
(img, 100, 0, 0, 100, 0, 0, false));
NUnit.Framework.Assert.AreEqual("Not colorized type3 fonts accept only mask images.", e.Message);
}
[NUnit.Framework.Test]
public virtual void AddInlineImageMaskTest() {
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(new MemoryStream()));
Type3Glyph glyph = new Type3Glyph(new PdfStream(), pdfDoc);
ImageData img = ImageDataFactory.Create(SOURCE_FOLDER + "imageTest.png");
img.MakeMask();
NUnit.Framework.Assert.IsNull(glyph.AddImageWithTransformationMatrix(img, 100, 0, 0, 100, 0, 0, true));
}
[NUnit.Framework.Test]
public virtual void AddImageMaskAsNotInlineTest() {
//TODO DEVSIX-5764 Display message error for non-inline images in type 3 glyph
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(new MemoryStream()));
Type3Glyph glyph = new Type3Glyph(new PdfStream(), pdfDoc);
ImageData img = ImageDataFactory.Create(SOURCE_FOLDER + "imageTest.png");
img.MakeMask();
NUnit.Framework.Assert.Catch(typeof(NullReferenceException), () => glyph.AddImageWithTransformationMatrix(
img, 100, 0, 0, 100, 0, 0, false));
}
}
}

View File

@@ -0,0 +1,351 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using TSpdf.Test;
namespace TSpdf.Kernel.Geom {
[NUnit.Framework.Category("UnitTest")]
public class AffineTransformTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void SelfTest() {
AffineTransform affineTransform = new AffineTransform();
NUnit.Framework.Assert.IsTrue(affineTransform.Equals(affineTransform));
}
[NUnit.Framework.Test]
public virtual void NullTest() {
AffineTransform affineTransform = new AffineTransform();
NUnit.Framework.Assert.IsFalse(affineTransform.Equals(null));
}
[NUnit.Framework.Test]
public virtual void OtherClassTest() {
AffineTransform affineTransform = new AffineTransform();
String @string = "Test";
NUnit.Framework.Assert.IsFalse(affineTransform.Equals(@string));
}
[NUnit.Framework.Test]
public virtual void SameValuesTest() {
AffineTransform affineTransform1 = new AffineTransform(0d, 1d, 2d, 3d, 4d, 5d);
AffineTransform affineTransform2 = new AffineTransform(0d, 1d, 2d, 3d, 4d, 5d);
int hash1 = affineTransform1.GetHashCode();
int hash2 = affineTransform2.GetHashCode();
NUnit.Framework.Assert.IsFalse(affineTransform1 == affineTransform2);
NUnit.Framework.Assert.AreEqual(hash1, hash2);
NUnit.Framework.Assert.IsTrue(affineTransform1.Equals(affineTransform2));
}
[NUnit.Framework.Test]
public virtual void DifferentValuesTest() {
AffineTransform affineTransform1 = new AffineTransform(0d, 1d, 2d, 3d, 4d, 5d);
AffineTransform affineTransform2 = new AffineTransform(5d, 4d, 3d, 2d, 1d, 1d);
int hash1 = affineTransform1.GetHashCode();
int hash2 = affineTransform2.GetHashCode();
NUnit.Framework.Assert.IsFalse(affineTransform1 == affineTransform2);
NUnit.Framework.Assert.AreNotEqual(hash1, hash2);
NUnit.Framework.Assert.IsFalse(affineTransform1.Equals(affineTransform2));
}
[NUnit.Framework.Test]
public virtual void GetRotateInstanceTest() {
AffineTransform rotateOne = AffineTransform.GetRotateInstance(Math.PI / 2);
AffineTransform expected = new AffineTransform(0, 1, -1, 0, 0, 0);
NUnit.Framework.Assert.AreEqual(rotateOne, expected);
}
[NUnit.Framework.Test]
public virtual void GetRotateInstanceTranslateTest() {
AffineTransform rotateTranslate = AffineTransform.GetRotateInstance(Math.PI / 2, 10, 5);
AffineTransform expected = new AffineTransform(0, 1, -1, 0, 15, -5);
NUnit.Framework.Assert.AreEqual(rotateTranslate, expected);
}
[NUnit.Framework.Test]
public virtual void CloneTest() {
AffineTransform original = new AffineTransform();
AffineTransform clone = original.Clone();
NUnit.Framework.Assert.IsTrue(original != clone);
NUnit.Framework.Assert.IsTrue(original.Equals(clone));
}
[NUnit.Framework.Test]
public virtual void GetTransformValuesTest() {
float[] matrix = new float[] { 0f, 1f, 2f, 3f, 4f, 5f };
AffineTransform affineTransform = new AffineTransform(matrix);
NUnit.Framework.Assert.AreEqual(matrix[0], affineTransform.GetScaleX(), 0.0);
NUnit.Framework.Assert.AreEqual(matrix[3], affineTransform.GetScaleY(), 0.0);
NUnit.Framework.Assert.AreEqual(matrix[2], affineTransform.GetShearX(), 0.0);
NUnit.Framework.Assert.AreEqual(matrix[1], affineTransform.GetShearY(), 0.0);
NUnit.Framework.Assert.AreEqual(matrix[4], affineTransform.GetTranslateX(), 0.0);
NUnit.Framework.Assert.AreEqual(matrix[5], affineTransform.GetTranslateY(), 0.0);
NUnit.Framework.Assert.AreEqual(32, affineTransform.GetTransformType(), 0.0);
}
[NUnit.Framework.Test]
public virtual void CreateAffineTransformFromOtherATTest() {
AffineTransform template = new AffineTransform(0, 1, 2, 3, 4, 5);
AffineTransform result = new AffineTransform(template);
NUnit.Framework.Assert.AreNotSame(template, result);
NUnit.Framework.Assert.AreEqual(template, result);
}
[NUnit.Framework.Test]
public virtual void CreateAffineTransformFromFloatArrayTest() {
float[] matrix = new float[] { 0f, 1f, 2f, 3f, 4f, 5f };
AffineTransform expected = new AffineTransform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix
[5]);
AffineTransform result = new AffineTransform(matrix);
NUnit.Framework.Assert.AreEqual(expected, result);
}
[NUnit.Framework.Test]
public virtual void CreateAffineTransformFromDoubleArrayTest() {
double[] matrix = new double[] { 0d, 1d, 2d, 3d, 4d, 5d };
AffineTransform expected = new AffineTransform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix
[5]);
AffineTransform result = new AffineTransform(matrix);
NUnit.Framework.Assert.AreEqual(expected, result);
}
[NUnit.Framework.Test]
public virtual void SetTransformTest() {
float[] matrix = new float[] { 0f, 1f, 2f, 3f, 4f, 5f };
AffineTransform expected = new AffineTransform(matrix);
AffineTransform result = new AffineTransform();
result.SetTransform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
NUnit.Framework.Assert.AreEqual(expected, result);
}
[NUnit.Framework.Test]
public virtual void SetToIdentityTest() {
AffineTransform expected = new AffineTransform(1, 0, 0, 1, 0, 0);
AffineTransform result = new AffineTransform();
result.SetToIdentity();
NUnit.Framework.Assert.AreEqual(expected, result);
}
[NUnit.Framework.Test]
public virtual void SetToShearTypeIdentityTest() {
double shx = 0d;
double shy = 0d;
AffineTransform expected = new AffineTransform(1, shx, shy, 1, 0, 0);
AffineTransform result = new AffineTransform();
result.SetToShear(shx, shy);
NUnit.Framework.Assert.AreEqual(expected, result);
}
[NUnit.Framework.Test]
public virtual void SetToShearTypeUnknownTest() {
double shx = 1d;
double shy = 1d;
AffineTransform expected = new AffineTransform(1, shx, shy, 1, 0, 0);
AffineTransform result = new AffineTransform();
result.SetToShear(shx, shy);
NUnit.Framework.Assert.AreEqual(expected, result);
}
[NUnit.Framework.Test]
public virtual void GetShearInstanceTest() {
double shx = 1d;
double shy = 1d;
AffineTransform expected = new AffineTransform(1, shx, shy, 1, 0, 0);
AffineTransform result = AffineTransform.GetShearInstance(shx, shy);
NUnit.Framework.Assert.AreEqual(expected, result);
}
[NUnit.Framework.Test]
public virtual void ShearTest() {
double shx = 1d;
double shy = 1d;
AffineTransform expected = new AffineTransform(4d, 6d, 4d, 6d, 5d, 6d);
AffineTransform result = new AffineTransform(1d, 2d, 3d, 4d, 5d, 6d);
result.Shear(shx, shy);
NUnit.Framework.Assert.AreEqual(expected, result);
}
[NUnit.Framework.Test]
public virtual void RotateTest() {
double angle = Math.PI / 2;
AffineTransform expected = new AffineTransform(3d, 4d, -1d, -2d, 5d, 6d);
AffineTransform result = new AffineTransform(1d, 2d, 3d, 4d, 5d, 6d);
result.Rotate(angle);
NUnit.Framework.Assert.AreEqual(expected, result);
}
[NUnit.Framework.Test]
public virtual void PreConcatenateTest() {
AffineTransform expected = new AffineTransform(6d, 6d, 14d, 14d, 24d, 24d);
AffineTransform result = new AffineTransform(1d, 2d, 3d, 4d, 5d, 6d);
AffineTransform template = new AffineTransform(2d, 2d, 2d, 2d, 2d, 2d);
result.PreConcatenate(template);
NUnit.Framework.Assert.AreEqual(expected, result);
}
[NUnit.Framework.Test]
public virtual void TransformDoubleArrayTest() {
AffineTransform affineTransform = new AffineTransform(1d, 2d, 3d, 4d, 5d, 6d);
double[] expected = new double[] { 0d, 13d, 18d, 13d, 18d, 0d };
double[] src = new double[] { 2d, 2d, 2d, 2d, 2d, 2d };
double[] dest = new double[6];
affineTransform.Transform(src, 1, dest, 1, 2);
TSpdf.Test.TestUtil.AreEqual(expected, dest, 0);
}
[NUnit.Framework.Test]
public virtual void TransformDoubleArraySourceDestEqualsTest() {
AffineTransform affineTransform = new AffineTransform(1d, 2d, 3d, 4d, 5d, 6d);
double[] expected = new double[] { 2d, 2d, 13d, 18d, 13d, 18d };
double[] src = new double[] { 2d, 2d, 2d, 2d, 2d, 2d };
affineTransform.Transform(src, 1, src, 2, 2);
TSpdf.Test.TestUtil.AreEqual(expected, src, 0);
}
[NUnit.Framework.Test]
public virtual void TransformFloatArrayTest() {
AffineTransform affineTransform = new AffineTransform(1f, 2f, 3f, 4f, 5f, 6f);
float[] expected = new float[] { 0f, 13f, 18f, 13f, 18f, 0f };
float[] src = new float[] { 2f, 2f, 2f, 2f, 2f, 2f };
float[] dest = new float[6];
affineTransform.Transform(src, 1, dest, 1, 2);
TSpdf.Test.TestUtil.AreEqual(expected, dest, 0);
}
[NUnit.Framework.Test]
public virtual void TransformFloatArraySourceDestEqualsTest() {
AffineTransform affineTransform = new AffineTransform(1f, 2f, 3f, 4f, 5f, 6f);
float[] expected = new float[] { 2f, 2f, 13f, 18f, 13f, 18f };
float[] src = new float[] { 2f, 2f, 2f, 2f, 2f, 2f };
affineTransform.Transform(src, 1, src, 2, 2);
TSpdf.Test.TestUtil.AreEqual(expected, src, 0);
}
[NUnit.Framework.Test]
public virtual void TransformFloatToDoubleTest() {
AffineTransform affineTransform = new AffineTransform(1f, 2f, 3f, 4f, 5f, 6f);
double[] expected = new double[] { 0d, 13d, 18d, 13d, 18d, 0d };
float[] src = new float[] { 2f, 2f, 2f, 2f, 2f, 2f };
double[] dest = new double[6];
affineTransform.Transform(src, 1, dest, 1, 2);
TSpdf.Test.TestUtil.AreEqual(expected, dest, 0);
}
[NUnit.Framework.Test]
public virtual void TransformDoubleToFloatTest() {
AffineTransform affineTransform = new AffineTransform(1f, 2f, 3f, 4f, 5f, 6f);
float[] expected = new float[] { 0f, 13f, 18f, 13f, 18f, 0f };
double[] src = new double[] { 2d, 2d, 2d, 2d, 2d, 2d };
float[] dest = new float[6];
affineTransform.Transform(src, 1, dest, 1, 2);
TSpdf.Test.TestUtil.AreEqual(expected, dest, 0);
}
[NUnit.Framework.Test]
public virtual void DeltaTransformPointTest() {
AffineTransform affineTransform = new AffineTransform(1f, 2f, 3f, 4f, 5f, 6f);
Point src = new Point(2, 2);
Point dest = new Point();
Point expected = new Point(8, 12);
affineTransform.DeltaTransform(src, dest);
NUnit.Framework.Assert.AreEqual(expected, dest);
}
[NUnit.Framework.Test]
public virtual void DeltaTransformPointNullDestTest() {
AffineTransform affineTransform = new AffineTransform(1f, 2f, 3f, 4f, 5f, 6f);
Point src = new Point(2, 2);
Point expected = new Point(8, 12);
Point dest = affineTransform.DeltaTransform(src, null);
NUnit.Framework.Assert.AreEqual(expected, dest);
}
[NUnit.Framework.Test]
public virtual void DeltaTransformDoubleArrayTest() {
AffineTransform affineTransform = new AffineTransform(1f, 2f, 3f, 4f, 5f, 6f);
double[] expected = new double[] { 0d, 8d, 12d, 8d, 12d, 0d };
double[] src = new double[] { 2d, 2d, 2d, 2d, 2d, 2d };
double[] dest = new double[6];
affineTransform.DeltaTransform(src, 1, dest, 1, 2);
TSpdf.Test.TestUtil.AreEqual(expected, dest, 0);
}
[NUnit.Framework.Test]
public virtual void InverseTransformPointTest() {
AffineTransform affineTransform = new AffineTransform(1f, 2f, 3f, 4f, 5f, 6f);
Point src = new Point(2, 2);
Point dest = new Point();
Point expected = new Point(0, -1);
affineTransform.InverseTransform(src, dest);
NUnit.Framework.Assert.AreEqual(expected, dest);
}
[NUnit.Framework.Test]
public virtual void InverseTransformPointNullTest() {
AffineTransform affineTransform = new AffineTransform(1f, 2f, 3f, 4f, 5f, 6f);
Point src = new Point(2, 2);
Point expected = new Point(0, -1);
Point dest = affineTransform.InverseTransform(src, null);
NUnit.Framework.Assert.AreEqual(expected, dest);
}
[NUnit.Framework.Test]
public virtual void InverseTransformDoubleArrayTest() {
AffineTransform affineTransform = new AffineTransform(1f, 2f, 3f, 4f, 5f, 6f);
double[] expected = new double[] { 0d, -0d, -1d, -0d, -1d, 0d };
double[] src = new double[] { 2d, 2d, 2d, 2d, 2d, 2d };
double[] dest = new double[6];
affineTransform.InverseTransform(src, 1, dest, 1, 2);
TSpdf.Test.TestUtil.AreEqual(expected, dest, 0);
}
[NUnit.Framework.Test]
public virtual void InverseTransformFloatArrayTest() {
AffineTransform affineTransform = new AffineTransform(1f, 2f, 3f, 4f, 5f, 6f);
float[] expected = new float[] { 0f, -0f, -1f, -0f, -1f, 0f };
float[] src = new float[] { 2f, 2f, 2f, 2f, 2f, 2f };
float[] dest = new float[6];
affineTransform.InverseTransform(src, 1, dest, 1, 2);
TSpdf.Test.TestUtil.AreEqual(expected, dest, 0);
}
}
}

View File

@@ -0,0 +1,131 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System.Collections.Generic;
using TSpdf.Commons.Utils;
using TSpdf.Test;
namespace TSpdf.Kernel.Geom {
[NUnit.Framework.Category("UnitTest")]
public class BezierCurveTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void ApproximationTest() {
IList<Point> controlPoints = JavaUtil.ArraysAsList(new Point(0f, 0f), new Point(-5f, 20f), new Point(7f, -
15f), new Point(20f, 5f));
BezierCurve curve = new BezierCurve(controlPoints);
IList<Point> approximation = curve.GetPiecewiseLinearApproximation();
IList<Point> expectedApproximation = JavaUtil.ArraysAsList(new Point(0f, 0f), new Point(-0.419434f, 1.717224f
), new Point(-0.971191f, 4.265442f), new Point(-1.159668f, 5.766296f), new Point(-1.076721f, 6.301537f
), new Point(-0.920105f, 6.414986f), new Point(-0.540527f, 6.270447f), new Point(0.220215f, 5.596008f)
, new Point(1.859375f, 3.879395f), new Point(4.025879f, 1.800232f), new Point(5.724121f, 0.481262f), new
Point(7.598145f, -0.596008f), new Point(9.104919f, -1.148415f), new Point(10.152161f, -1.357231f), new
Point(11.230164f, -1.414986f), new Point(12.335999f, -1.301537f), new Point(13.466736f, -0.996742f), new
Point(14.619446f, -0.480461f), new Point(15.791199f, 0.267448f), new Point(16.979065f, 1.267128f), new
Point(18.180115f, 2.538719f), new Point(19.391418f, 4.102364f), new Point(20f, 5f));
NUnit.Framework.Assert.AreEqual(expectedApproximation.Count, approximation.Count);
for (int i = 0; i < expectedApproximation.Count; ++i) {
NUnit.Framework.Assert.AreEqual(expectedApproximation[i].GetX(), approximation[i].GetX(), 0.001f);
NUnit.Framework.Assert.AreEqual(expectedApproximation[i].GetY(), approximation[i].GetY(), 0.001f);
}
}
[NUnit.Framework.Test]
public virtual void ApproximationWithEqualStartAndEndTest() {
IList<Point> controlPoints = JavaUtil.ArraysAsList(new Point(0f, 0f), new Point(-5f, 20f), new Point(7f, -
15f), new Point(0f, 0f));
BezierCurve curve = new BezierCurve(controlPoints);
IList<Point> approximation = curve.GetPiecewiseLinearApproximation();
IList<Point> expectedApproximation = JavaUtil.ArraysAsList(new Point(0f, 0f), new Point(-0.747070f, 3.131104f
), new Point(-1.235962f, 5.747223f), new Point(-1.244339f, 6.259632f), new Point(-1.177597f, 6.350613f
), new Point(-0.985474f, 6.159210f), new Point(-0.592163f, 5.392914f), new Point(0.184570f, 3.460693f)
, new Point(1.291992f, 0.230713f), new Point(2.094727f, -2.618408f), new Point(2.243042f, -3.765106f),
new Point(2.026978f, -3.769684f), new Point(1.497437f, -2.986908f), new Point(0.601685f, -1.262970f),
new Point(0f, 0f));
NUnit.Framework.Assert.AreEqual(expectedApproximation.Count, approximation.Count);
for (int i = 0; i < expectedApproximation.Count; ++i) {
NUnit.Framework.Assert.AreEqual(expectedApproximation[i].GetX(), approximation[i].GetX(), 0.001f);
NUnit.Framework.Assert.AreEqual(expectedApproximation[i].GetY(), approximation[i].GetY(), 0.001f);
}
}
[NUnit.Framework.Test]
public virtual void ApproximationWithEqualSecondAndEndTest() {
IList<Point> controlPoints = JavaUtil.ArraysAsList(new Point(0f, 0f), new Point(20f, 5f), new Point(7f, -15f
), new Point(20f, 5f));
BezierCurve curve = new BezierCurve(controlPoints);
IList<Point> approximation = curve.GetPiecewiseLinearApproximation();
IList<Point> expectedApproximation = JavaUtil.ArraysAsList(new Point(0f, 0f), new Point(1.780121f, 0.397491f
), new Point(4.803497f, 0.800629f), new Point(7.183075f, 0.760651f), new Point(9.005280f, 0.372772f),
new Point(10.356537f, -0.267792f), new Point(11.323273f, -1.065826f), new Point(12.241455f, -2.349854f
), new Point(12.780609f, -3.452606f), new Point(13.073517f, -3.928375f), new Point(13.414032f, -4.085541f
), new Point(13.888580f, -3.828888f), new Point(15.040771f, -2.459717f), new Point(17.852783f, 1.702881f
), new Point(20f, 5f));
NUnit.Framework.Assert.AreEqual(expectedApproximation.Count, approximation.Count);
for (int i = 0; i < expectedApproximation.Count; ++i) {
NUnit.Framework.Assert.AreEqual(expectedApproximation[i].GetX(), approximation[i].GetX(), 0.001f);
NUnit.Framework.Assert.AreEqual(expectedApproximation[i].GetY(), approximation[i].GetY(), 0.001f);
}
}
[NUnit.Framework.Test]
public virtual void ApproximationWithEqualStartAndEndAndHugeDistanceToleranceManhattanTest() {
IList<Point> controlPoints = JavaUtil.ArraysAsList(new Point(0f, 0f), new Point(-5f, 20f), new Point(7f, -
15f), new Point(0f, 0f));
BezierCurve curve = new BezierCurve(controlPoints);
double oldDistanceToleranceManhattan = BezierCurve.distanceToleranceManhattan;
try {
BezierCurve.distanceToleranceManhattan = 142d;
IList<Point> approximation = curve.GetPiecewiseLinearApproximation();
IList<Point> expectedApproximation = JavaUtil.ArraysAsList(new Point(0.000000f, 0.000000f), new Point(0.75f
, 1.875f), new Point(0.000000f, 0.000000f));
NUnit.Framework.Assert.AreEqual(expectedApproximation.Count, approximation.Count);
for (int i = 0; i < expectedApproximation.Count; ++i) {
NUnit.Framework.Assert.AreEqual(expectedApproximation[i].GetX(), approximation[i].GetX(), 0.001f);
NUnit.Framework.Assert.AreEqual(expectedApproximation[i].GetY(), approximation[i].GetY(), 0.001f);
}
}
finally {
BezierCurve.distanceToleranceManhattan = oldDistanceToleranceManhattan;
}
}
}
}

View File

@@ -0,0 +1,103 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using TSpdf.Test;
namespace TSpdf.Kernel.Geom {
[NUnit.Framework.Category("UnitTest")]
public class LineSegmentTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void ContainsPointNullTest() {
LineSegment lineSegment = new LineSegment(new Vector(20.3246f, 769.4974f, 1.0f), new Vector(151.22923f, 769.4974f
, 1.0f));
NUnit.Framework.Assert.IsFalse(lineSegment.ContainsPoint(null));
}
[NUnit.Framework.Test]
public virtual void ContainsPointTest() {
Vector pointToCheck = new Vector(20.3246f, 769.4974f, 1.0f);
LineSegment lineSegment = new LineSegment(pointToCheck, new Vector(151.22923f, 769.4974f, 1.0f));
NUnit.Framework.Assert.IsTrue(lineSegment.ContainsPoint(pointToCheck));
}
[NUnit.Framework.Test]
public virtual void NotContainsPointLeftTest() {
Vector pointToCheck = new Vector(100.3246f, 769.4974f, 1.0f);
LineSegment lineSegment = new LineSegment(new Vector(120.3246f, 769.4974f, 1.0f), new Vector(151.22923f, 769.4974f
, 1.0f));
NUnit.Framework.Assert.IsFalse(lineSegment.ContainsPoint(pointToCheck));
}
[NUnit.Framework.Test]
public virtual void NotContainsPointRightTest() {
Vector pointToCheck = new Vector(160.3246f, 769.4974f, 1.0f);
LineSegment lineSegment = new LineSegment(new Vector(120.3246f, 769.4974f, 1.0f), new Vector(151.22923f, 769.4974f
, 1.0f));
NUnit.Framework.Assert.IsFalse(lineSegment.ContainsPoint(pointToCheck));
}
[NUnit.Framework.Test]
public virtual void ContainsSegmentNullTest() {
LineSegment lineSegment = new LineSegment(new Vector(100.3246f, 769.4974f, 1.0f), new Vector(151.22923f, 769.4974f
, 1.0f));
NUnit.Framework.Assert.IsFalse(lineSegment.ContainsSegment(null));
}
[NUnit.Framework.Test]
public virtual void ContainsSegmentTest() {
LineSegment lineSegment = new LineSegment(new Vector(100.3246f, 769.4974f, 1.0f), new Vector(151.22923f, 769.4974f
, 1.0f));
LineSegment segmentToCheck = new LineSegment(new Vector(110.3246f, 769.4974f, 1.0f), new Vector(140.22923f
, 769.4974f, 1.0f));
NUnit.Framework.Assert.IsTrue(lineSegment.ContainsSegment(segmentToCheck));
}
[NUnit.Framework.Test]
public virtual void NotContainsSegmentTest() {
LineSegment lineSegment = new LineSegment(new Vector(120.3246f, 769.4974f, 1.0f), new Vector(151.22923f, 769.4974f
, 1.0f));
LineSegment segmentToCheck = new LineSegment(new Vector(110.3246f, 769.4974f, 1.0f), new Vector(115.22923f
, 769.4974f, 1.0f));
NUnit.Framework.Assert.IsFalse(lineSegment.ContainsSegment(segmentToCheck));
}
}
}

View File

@@ -0,0 +1,81 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using TSpdf.Test;
namespace TSpdf.Kernel.Geom {
[NUnit.Framework.Category("UnitTest")]
public class MatrixTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void TestMultiply() {
Matrix m1 = new Matrix(2, 3, 4, 5, 6, 7);
Matrix m2 = new Matrix(8, 9, 10, 11, 12, 13);
Matrix shouldBe = new Matrix(46, 51, 82, 91, 130, 144);
Matrix rslt = m1.Multiply(m2);
NUnit.Framework.Assert.AreEqual(shouldBe, rslt);
}
[NUnit.Framework.Test]
public virtual void TestDeterminant() {
Matrix m = new Matrix(2, 3, 4, 5, 6, 7);
NUnit.Framework.Assert.AreEqual(-2f, m.GetDeterminant(), .001f);
}
[NUnit.Framework.Test]
public virtual void TestSubtract() {
Matrix m1 = new Matrix(1, 2, 3, 4, 5, 6);
Matrix m2 = new Matrix(6, 5, 4, 3, 2, 1);
Matrix shouldBe = new Matrix(-5, -3, 0, -1, 1, 0, 3, 5, 0);
Matrix rslt = m1.Subtract(m2);
NUnit.Framework.Assert.AreEqual(shouldBe, rslt);
}
[NUnit.Framework.Test]
public virtual void TestAdd() {
Matrix m1 = new Matrix(1, 2, 3, 4, 5, 6);
Matrix m2 = new Matrix(6, 5, 4, 3, 2, 1);
Matrix shouldBe = new Matrix(7, 7, 0, 7, 7, 0, 7, 7, 2);
Matrix rslt = m1.Add(m2);
NUnit.Framework.Assert.AreEqual(shouldBe, rslt);
}
}
}

View File

@@ -0,0 +1,38 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using TSpdf.Test;
namespace TSpdf.Kernel.Geom {
[NUnit.Framework.Category("UnitTest")]
public class PageSizeUnitTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void ConstructFromRectangleTest() {
Rectangle rectangle = new Rectangle(0, 0, 100, 200);
PageSize pageSize = new PageSize(rectangle);
NUnit.Framework.Assert.AreEqual(rectangle.x, pageSize.x, 1e-5);
NUnit.Framework.Assert.AreEqual(rectangle.y, pageSize.y, 1e-5);
NUnit.Framework.Assert.AreEqual(rectangle.width, pageSize.width, 1e-5);
NUnit.Framework.Assert.AreEqual(rectangle.height, pageSize.height, 1e-5);
}
}
}

View File

@@ -0,0 +1,246 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using TSpdf.Test;
namespace TSpdf.Kernel.Geom {
[NUnit.Framework.Category("UnitTest")]
public class PointTest : ExtendedTSpdfTest {
private static double EPSILON_COMPARISON = 1E-12;
[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.Test]
public virtual void DoubleParamConstructorTest() {
Point first = new Point(0.13, 1.1);
NUnit.Framework.Assert.AreEqual(0.13, first.GetX(), EPSILON_COMPARISON);
NUnit.Framework.Assert.AreEqual(1.1, first.GetY(), EPSILON_COMPARISON);
}
[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.Test]
public virtual void EqualsItselfTest() {
Point first = new Point(1.23, 1.1);
NUnit.Framework.Assert.IsTrue(first.Equals(first));
NUnit.Framework.Assert.AreEqual(first.GetHashCode(), first.GetHashCode());
}
[NUnit.Framework.Test]
public virtual void EqualsToAnotherPointTest() {
Point first = new Point(1.23, 1.1);
Point second = new Point(1.23, 1.1);
NUnit.Framework.Assert.IsTrue(first.Equals(second));
NUnit.Framework.Assert.IsTrue(second.Equals(first));
NUnit.Framework.Assert.AreEqual(first.GetHashCode(), second.GetHashCode());
}
[NUnit.Framework.Test]
public virtual void NotEqualsToAnotherPointTest() {
Point first = new Point(1.23, 1.1);
Point second = new Point(1.23, 1.2);
NUnit.Framework.Assert.IsFalse(first.Equals(second));
NUnit.Framework.Assert.IsFalse(second.Equals(first));
NUnit.Framework.Assert.AreNotEqual(first.GetHashCode(), second.GetHashCode());
}
[NUnit.Framework.Test]
public virtual void NotEqualsToNullTest() {
Point first = new Point(1.23, 1.1);
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.Test]
public virtual void DistanceByPointTest() {
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), EPSILON_COMPARISON);
}
[NUnit.Framework.Test]
public virtual void DistanceItselfTest() {
Point first = new Point(1, 1);
NUnit.Framework.Assert.AreEqual(0, first.Distance(first), EPSILON_COMPARISON);
}
[NUnit.Framework.Test]
public virtual void ToStringTest() {
Point first = new Point(1.23, 1.1);
NUnit.Framework.Assert.AreEqual("Point: [x=1.23,y=1.1]", first.ToString());
}
[NUnit.Framework.Test]
public virtual void CloneTest() {
Point first = new Point(1.23, 1.1);
Point clone = (Point)first.Clone();
NUnit.Framework.Assert.AreEqual(first, clone);
NUnit.Framework.Assert.AreEqual(first.GetHashCode(), clone.GetHashCode());
}
[NUnit.Framework.Test]
public virtual void TranslateTest() {
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);
NUnit.Framework.Assert.AreEqual(expectedPoints[1], point);
point.Translate(0, h);
NUnit.Framework.Assert.AreEqual(expectedPoints[2], point);
point.Translate(-w, 0);
NUnit.Framework.Assert.AreEqual(expectedPoints[3], point);
point.Translate(0, -h);
NUnit.Framework.Assert.AreEqual(expectedPoints[0], point);
}
[NUnit.Framework.Test]
public virtual void PointVsItLocationTest() {
Point first = new Point(1.23, 1.1);
Point location = first.GetLocation();
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);
NUnit.Framework.Assert.AreEqual(first, second);
}
}
}

View File

@@ -0,0 +1,674 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.Collections.Generic;
using System.IO;
using TSpdf.Commons.Utils;
using TSpdf.Kernel.Exceptions;
using TSpdf.Kernel.Pdf;
using TSpdf.Test;
namespace TSpdf.Kernel.Geom {
[NUnit.Framework.Category("UnitTest")]
public class RectangleTest : ExtendedTSpdfTest {
private const float OVERLAP_EPSILON = 0.1f;
[NUnit.Framework.Test]
public virtual void OverlapWithEpsilon() {
Rectangle first = new Rectangle(0, 0, 10, 10);
Rectangle second = new Rectangle(-10, 0, 10.09f, 5);
NUnit.Framework.Assert.IsFalse(first.Overlaps(second, OVERLAP_EPSILON));
second.SetWidth(10.11f);
NUnit.Framework.Assert.IsTrue(first.Overlaps(second, OVERLAP_EPSILON));
second = new Rectangle(5, 9.91f, 5, 5);
NUnit.Framework.Assert.IsFalse(first.Overlaps(second, OVERLAP_EPSILON));
second.SetY(9.89f);
NUnit.Framework.Assert.IsTrue(first.Overlaps(second, OVERLAP_EPSILON));
second = new Rectangle(9.91f, 0, 5, 5);
NUnit.Framework.Assert.IsFalse(first.Overlaps(second, OVERLAP_EPSILON));
second.SetX(9.89f);
NUnit.Framework.Assert.IsTrue(first.Overlaps(second, OVERLAP_EPSILON));
second = new Rectangle(5, -10, 5, 10.09f);
NUnit.Framework.Assert.IsFalse(first.Overlaps(second, OVERLAP_EPSILON));
second.SetHeight(10.11f);
NUnit.Framework.Assert.IsTrue(first.Overlaps(second, OVERLAP_EPSILON));
}
[NUnit.Framework.Test]
public virtual void OverlapWithNegativeEpsilon() {
Rectangle first = new Rectangle(0, 0, 10, 10);
Rectangle second = new Rectangle(-10, 0, 9.89f, 5);
NUnit.Framework.Assert.IsFalse(first.Overlaps(second, -OVERLAP_EPSILON));
second.SetWidth(9.91f);
NUnit.Framework.Assert.IsTrue(first.Overlaps(second, -OVERLAP_EPSILON));
second = new Rectangle(5, 10.11f, 5, 5);
NUnit.Framework.Assert.IsFalse(first.Overlaps(second, -OVERLAP_EPSILON));
second.SetY(10.09f);
NUnit.Framework.Assert.IsTrue(first.Overlaps(second, -OVERLAP_EPSILON));
second = new Rectangle(10.11f, 0, 5, 5);
NUnit.Framework.Assert.IsFalse(first.Overlaps(second, -OVERLAP_EPSILON));
second.SetX(10.09f);
NUnit.Framework.Assert.IsTrue(first.Overlaps(second, -OVERLAP_EPSILON));
second = new Rectangle(5, -10, 5, 9.89f);
NUnit.Framework.Assert.IsFalse(first.Overlaps(second, -OVERLAP_EPSILON));
second.SetHeight(9.91f);
NUnit.Framework.Assert.IsTrue(first.Overlaps(second, -OVERLAP_EPSILON));
}
[NUnit.Framework.Test]
public virtual void RectangleOverlapTest01() {
//Intersection
Rectangle one = new Rectangle(0, 0, 10, 10);
Rectangle two = new Rectangle(5, 5, 5, 5);
bool result = one.Overlaps(two);
NUnit.Framework.Assert.IsTrue(result);
//envelopment
one = new Rectangle(0, 0, 10, 10);
two = new Rectangle(2, 2, 5, 5);
result = one.Overlaps(two);
NUnit.Framework.Assert.IsTrue(result);
//identical
one = new Rectangle(0, 0, 10, 10);
two = new Rectangle(0, 0, 10, 10);
result = one.Overlaps(two);
NUnit.Framework.Assert.IsTrue(result);
}
[NUnit.Framework.Test]
public virtual void RectangleOverlapTest02() {
//Left
//Top left
Rectangle one = new Rectangle(0, 0, 10, 10);
Rectangle two = new Rectangle(15, 15, 10, 10);
bool result = one.Overlaps(two);
NUnit.Framework.Assert.IsFalse(result);
//Middle left
one = new Rectangle(0, 0, 10, 10);
two = new Rectangle(15, 5, 10, 10);
result = one.Overlaps(two);
NUnit.Framework.Assert.IsFalse(result);
//Lower left
one = new Rectangle(0, 0, 10, 10);
two = new Rectangle(15, -5, 10, 10);
result = one.Overlaps(two);
NUnit.Framework.Assert.IsFalse(result);
//Bottom
//Bottom left
one = new Rectangle(0, 0, 10, 10);
two = new Rectangle(5, -15, 10, 10);
result = one.Overlaps(two);
NUnit.Framework.Assert.IsFalse(result);
//Bottom right
one = new Rectangle(0, 0, 10, 10);
two = new Rectangle(-5, -15, 10, 10);
result = one.Overlaps(two);
NUnit.Framework.Assert.IsFalse(result);
//Right
//Lower right
one = new Rectangle(0, 0, 10, 10);
two = new Rectangle(-15, -5, 10, 10);
result = one.Overlaps(two);
NUnit.Framework.Assert.IsFalse(result);
//Upper right
one = new Rectangle(0, 0, 10, 10);
two = new Rectangle(-15, 5, 10, 10);
result = one.Overlaps(two);
NUnit.Framework.Assert.IsFalse(result);
//Top
//Top right
one = new Rectangle(0, 0, 10, 10);
two = new Rectangle(-5, 15, 10, 10);
result = one.Overlaps(two);
NUnit.Framework.Assert.IsFalse(result);
//Top left
one = new Rectangle(0, 0, 10, 10);
two = new Rectangle(5, 15, 10, 10);
result = one.Overlaps(two);
NUnit.Framework.Assert.IsFalse(result);
}
[NUnit.Framework.Test]
public virtual void EnvelopTest01() {
//one contains two
Rectangle one = new Rectangle(0, 0, 10, 10);
Rectangle two = new Rectangle(5, 5, 5, 5);
bool result = one.Contains(two);
NUnit.Framework.Assert.IsTrue(result);
}
[NUnit.Framework.Test]
public virtual void EnvelopsTest02() {
//two identical rectangles
Rectangle one = new Rectangle(0, 0, 10, 10);
Rectangle two = new Rectangle(0, 0, 10, 10);
bool result = one.Contains(two);
NUnit.Framework.Assert.IsTrue(result);
}
[NUnit.Framework.Test]
public virtual void EnvelopsTest03() {
//One intersects two but does not envelop
Rectangle one = new Rectangle(0, 0, 10, 10);
Rectangle two = new Rectangle(5, 5, 10, 10);
bool result = one.Contains(two);
NUnit.Framework.Assert.IsFalse(result);
}
[NUnit.Framework.Test]
public virtual void EnvelopsTest04() {
//one and two do not
Rectangle one = new Rectangle(0, 0, 10, 10);
Rectangle two = new Rectangle(-15, -15, 10, 10);
bool result = one.Contains(two);
NUnit.Framework.Assert.IsFalse(result);
}
[NUnit.Framework.Test]
public virtual void GetIntersectionTest01() {
//Cases where there is an intersection rectangle
Rectangle main;
Rectangle second;
Rectangle actual;
Rectangle expected;
bool areEqual;
main = new Rectangle(2, 2, 8, 8);
//A. Main rectangle is greater in both dimension than second rectangle
second = new Rectangle(4, 8, 4, 4);
//1.Middle top
expected = new Rectangle(4, 8, 4, 2);
actual = main.GetIntersection(second);
areEqual = expected.EqualsWithEpsilon(actual);
//2.Middle Right
second.MoveRight(4);
expected = new Rectangle(8, 8, 2, 2);
actual = main.GetIntersection(second);
areEqual = areEqual && (expected.EqualsWithEpsilon(actual));
//3.Right middle
second.MoveDown(4);
expected = new Rectangle(8, 4, 2, 4);
actual = main.GetIntersection(second);
areEqual = areEqual && (expected.EqualsWithEpsilon(actual));
//4.Bottom right
second.MoveDown(4);
expected = new Rectangle(8, 2, 2, 2);
actual = main.GetIntersection(second);
areEqual = areEqual && (expected.EqualsWithEpsilon(actual));
//5.Bottom middle
second.MoveLeft(4);
expected = new Rectangle(4, 2, 4, 2);
actual = main.GetIntersection(second);
areEqual = areEqual && (expected.EqualsWithEpsilon(actual));
//6.Bottom Left
second.MoveLeft(4);
expected = new Rectangle(2, 2, 2, 2);
actual = main.GetIntersection(second);
areEqual = areEqual && (expected.EqualsWithEpsilon(actual));
//7.Left Middle
second.MoveUp(4);
expected = new Rectangle(2, 4, 2, 4);
actual = main.GetIntersection(second);
areEqual = areEqual && (expected.EqualsWithEpsilon(actual));
//8.Left Top
second.MoveUp(4);
expected = new Rectangle(2, 8, 2, 2);
actual = main.GetIntersection(second);
areEqual = areEqual && (expected.EqualsWithEpsilon(actual));
//B. Main rectangle is greater in width but not height than second rectangle
//1. Left
second = new Rectangle(0, 0, 4, 12);
expected = new Rectangle(2, 2, 2, 8);
actual = main.GetIntersection(second);
areEqual = areEqual && (expected.EqualsWithEpsilon(actual));
//2. Middle
second.MoveRight(4);
expected = new Rectangle(4, 2, 4, 8);
actual = main.GetIntersection(second);
areEqual = areEqual && (expected.EqualsWithEpsilon(actual));
//3. Right
second.MoveRight(4);
expected = new Rectangle(8, 2, 2, 8);
actual = main.GetIntersection(second);
areEqual = areEqual && (expected.EqualsWithEpsilon(actual));
//C. Main rectangle is greater in height but not width than second rectangle
//1. Top
second = new Rectangle(0, 8, 12, 4);
expected = new Rectangle(2, 8, 8, 2);
actual = main.GetIntersection(second);
areEqual = areEqual && (expected.EqualsWithEpsilon(actual));
//2. Middle
second.MoveDown(4);
expected = new Rectangle(2, 4, 8, 4);
actual = main.GetIntersection(second);
areEqual = areEqual && (expected.EqualsWithEpsilon(actual));
//3. Bottom
second.MoveDown(4);
expected = new Rectangle(2, 2, 8, 2);
actual = main.GetIntersection(second);
areEqual = areEqual && (expected.EqualsWithEpsilon(actual));
//Check if any have failed
NUnit.Framework.Assert.IsTrue(areEqual);
}
[NUnit.Framework.Test]
public virtual void GetIntersectionTest02() {
//Cases where the two rectangles do not intersect
Rectangle main;
Rectangle second;
Rectangle actual;
bool noIntersection;
main = new Rectangle(2, 2, 8, 8);
//Top
second = new Rectangle(4, 12, 4, 4);
actual = main.GetIntersection(second);
noIntersection = actual == null;
//Right
second = new Rectangle(12, 4, 4, 4);
actual = main.GetIntersection(second);
noIntersection = noIntersection && ((actual) == null);
//Bottom
second = new Rectangle(4, -8, 4, 4);
actual = main.GetIntersection(second);
noIntersection = noIntersection && ((actual) == null);
//Left
second = new Rectangle(-8, 4, 4, 4);
actual = main.GetIntersection(second);
noIntersection = noIntersection && ((actual) == null);
NUnit.Framework.Assert.IsTrue(noIntersection);
}
[NUnit.Framework.Test]
public virtual void GetIntersectionTest03() {
//Edge cases: envelopment
//A equal rectangles
Rectangle main;
Rectangle second;
Rectangle actual;
Rectangle expected;
bool areEqual;
main = new Rectangle(2, 2, 8, 8);
second = new Rectangle(main);
expected = new Rectangle(main);
actual = main.GetIntersection(second);
areEqual = expected.EqualsWithEpsilon(actual);
//B main contains second
main = new Rectangle(2, 2, 8, 8);
second = new Rectangle(4, 4, 4, 4);
expected = new Rectangle(second);
actual = main.GetIntersection(second);
areEqual = areEqual && (expected.EqualsWithEpsilon(actual));
//C second contains main
main = new Rectangle(2, 2, 8, 8);
second = new Rectangle(0, 0, 12, 12);
expected = new Rectangle(main);
actual = main.GetIntersection(second);
areEqual = areEqual && (expected.EqualsWithEpsilon(actual));
NUnit.Framework.Assert.IsTrue(areEqual);
}
[NUnit.Framework.Test]
public virtual void GetIntersectionTest04() {
//Edge case: intersections on edges
Rectangle main;
Rectangle second;
Rectangle actual;
Rectangle expected;
bool areEqual;
main = new Rectangle(2, 2, 8, 8);
//Top
second = new Rectangle(4, 10, 4, 4);
expected = new Rectangle(4, 10, 4, 0);
actual = main.GetIntersection(second);
areEqual = expected.EqualsWithEpsilon(actual);
//Right
second = new Rectangle(10, 4, 4, 4);
expected = new Rectangle(10, 4, 0, 4);
actual = main.GetIntersection(second);
areEqual = areEqual && (expected.EqualsWithEpsilon(actual));
//Bottom
second = new Rectangle(4, -2, 4, 4);
expected = new Rectangle(4, 2, 4, 0);
actual = main.GetIntersection(second);
areEqual = areEqual && (expected.EqualsWithEpsilon(actual));
//Left
second = new Rectangle(-2, 4, 4, 4);
expected = new Rectangle(2, 4, 0, 4);
actual = main.GetIntersection(second);
areEqual = areEqual && (expected.EqualsWithEpsilon(actual));
//Edge case: intersection on corners
//Top-Left
second = new Rectangle(-2, 10, 4, 4);
expected = new Rectangle(2, 10, 0, 0);
actual = main.GetIntersection(second);
areEqual = areEqual && (expected.EqualsWithEpsilon(actual));
//Top-Right
second = new Rectangle(10, 10, 4, 4);
expected = new Rectangle(10, 10, 0, 0);
actual = main.GetIntersection(second);
areEqual = areEqual && (expected.EqualsWithEpsilon(actual));
//Bottom-Right
second = new Rectangle(10, -2, 4, 4);
expected = new Rectangle(10, 2, 0, 0);
actual = main.GetIntersection(second);
areEqual = areEqual && (expected.EqualsWithEpsilon(actual));
//Bottom-Left
second = new Rectangle(-2, -2, 4, 4);
expected = new Rectangle(2, 2, 0, 0);
actual = main.GetIntersection(second);
areEqual = areEqual && (expected.EqualsWithEpsilon(actual));
NUnit.Framework.Assert.IsTrue(areEqual);
}
[NUnit.Framework.Test]
public virtual void CreateBoundingRectangleFromQuadPointsTest01() {
Rectangle actual;
Rectangle expected;
float[] points = new float[] { 0, 0, 2, 1, 1, 2, -2, 1 };
PdfArray quadpoints = new PdfArray(points);
expected = new Rectangle(-2, 0, 4, 2);
actual = Rectangle.CreateBoundingRectangleFromQuadPoint(quadpoints);
bool? areEqual = expected.EqualsWithEpsilon(actual);
NUnit.Framework.Assert.IsTrue(areEqual);
}
[NUnit.Framework.Test]
public virtual void CreateBoundingRectangleFromQuadPointsTest02() {
float[] points = new float[] { 0, 0, 2, 1, 1, 2, -2, 1, 0 };
PdfArray quadpoints = new PdfArray(points);
bool exception = false;
try {
Rectangle.CreateBoundingRectangleFromQuadPoint(quadpoints);
}
catch (PdfException) {
exception = true;
}
NUnit.Framework.Assert.IsTrue(exception);
}
[NUnit.Framework.Test]
public virtual void CreateBoundingRectanglesFromQuadPointsTest01() {
IList<Rectangle> actual;
IList<Rectangle> expected;
bool areEqual = true;
float[] points = new float[] { 0, 0, 2, 1, 1, 2, -2, 1, 0, -1, 2, 0, 1, 1, -2, 0 };
PdfArray quadpoints = new PdfArray(points);
expected = new List<Rectangle>();
expected.Add(new Rectangle(-2, 0, 4, 2));
expected.Add(new Rectangle(-2, -1, 4, 2));
actual = Rectangle.CreateBoundingRectanglesFromQuadPoint(quadpoints);
for (int i = 0; i < expected.Count; i++) {
areEqual = areEqual && expected[i].EqualsWithEpsilon(actual[i]);
}
NUnit.Framework.Assert.IsTrue(areEqual);
}
[NUnit.Framework.Test]
public virtual void CreateBoundingRectanglesFromQuadPointsTest02() {
float[] points = new float[] { 0, 0, 2, 1, 1, 2, -2, 1, 0, -1, 2, 0, 1, 1, -2, 0, 1 };
PdfArray quadpoints = new PdfArray(points);
bool exception = false;
try {
Rectangle.CreateBoundingRectanglesFromQuadPoint(quadpoints);
}
catch (PdfException) {
exception = true;
}
NUnit.Framework.Assert.IsTrue(exception);
}
[NUnit.Framework.Test]
public virtual void TranslateOnRotatedPageTest01() {
// we need a page with set rotation and page size to test Rectangle#getRectangleOnRotatedPage
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new MemoryStream()));
PdfPage page = pdfDocument.AddNewPage();
NUnit.Framework.Assert.IsTrue(PageSize.A4.EqualsWithEpsilon(page.GetPageSize()));
// Test rectangle
Rectangle testRectangle = new Rectangle(200, 200, 100, 200);
NUnit.Framework.Assert.AreEqual(0, page.GetRotation());
NUnit.Framework.Assert.IsTrue(new Rectangle(200, 200, 100, 200).EqualsWithEpsilon(Rectangle.GetRectangleOnRotatedPage
(testRectangle, page)));
page.SetRotation(90);
NUnit.Framework.Assert.AreEqual(90, page.GetRotation());
NUnit.Framework.Assert.IsTrue(new Rectangle(195, 200, 200, 100).EqualsWithEpsilon(Rectangle.GetRectangleOnRotatedPage
(testRectangle, page)));
page.SetRotation(180);
NUnit.Framework.Assert.AreEqual(180, page.GetRotation());
NUnit.Framework.Assert.IsTrue(new Rectangle(295, 442, 100, 200).EqualsWithEpsilon(Rectangle.GetRectangleOnRotatedPage
(testRectangle, page)));
page.SetRotation(270);
NUnit.Framework.Assert.AreEqual(270, page.GetRotation());
NUnit.Framework.Assert.IsTrue(new Rectangle(200, 542, 200, 100).EqualsWithEpsilon(Rectangle.GetRectangleOnRotatedPage
(testRectangle, page)));
page.SetRotation(360);
NUnit.Framework.Assert.AreEqual(0, page.GetRotation());
NUnit.Framework.Assert.IsTrue(new Rectangle(200, 200, 100, 200).EqualsWithEpsilon(Rectangle.GetRectangleOnRotatedPage
(testRectangle, page)));
}
[NUnit.Framework.Test]
public virtual void CalculateBBoxTest() {
Point a = new Point(100, 100);
Point b = new Point(200, 100);
Point c = new Point(200, 200);
Point d = new Point(100, 200);
// Zero rotation
Rectangle.CalculateBBox(JavaUtil.ArraysAsList(a, b, c, d));
NUnit.Framework.Assert.IsTrue(new Rectangle(100, 100, 100, 100).EqualsWithEpsilon(Rectangle.CalculateBBox(
JavaUtil.ArraysAsList(a, b, c, d))));
// 270 degree rotation
a = new Point(200, 100);
b = new Point(200, 200);
c = new Point(100, 200);
d = new Point(100, 100);
NUnit.Framework.Assert.IsTrue(new Rectangle(100, 100, 100, 100).EqualsWithEpsilon(Rectangle.CalculateBBox(
JavaUtil.ArraysAsList(a, b, c, d))));
// it looks as follows:
// dxxxxxx
// xxxxxxx
// cxxxxxa
// xxxxxxx
// xxxxxxb
a = new Point(200, 100);
b = new Point(200, 0);
c = new Point(0, 100);
d = new Point(0, 200);
NUnit.Framework.Assert.IsTrue(new Rectangle(0, 0, 200, 200).EqualsWithEpsilon(Rectangle.CalculateBBox(JavaUtil.ArraysAsList
(a, b, c, d))));
}
[NUnit.Framework.Test]
public virtual void SetBBoxWithoutNormalizationTest() {
Rectangle rectangle = new Rectangle(0, 0, 100, 200);
NUnit.Framework.Assert.AreEqual(0, rectangle.GetX(), 1e-5);
NUnit.Framework.Assert.AreEqual(0, rectangle.GetY(), 1e-5);
NUnit.Framework.Assert.AreEqual(100, rectangle.GetWidth(), 1e-5);
NUnit.Framework.Assert.AreEqual(200, rectangle.GetHeight(), 1e-5);
//set bBox without any normalization needed
rectangle.SetBbox(10, 10, 90, 190);
NUnit.Framework.Assert.AreEqual(10, rectangle.GetX(), 1e-5);
NUnit.Framework.Assert.AreEqual(10, rectangle.GetY(), 1e-5);
NUnit.Framework.Assert.AreEqual(80, rectangle.GetWidth(), 1e-5);
NUnit.Framework.Assert.AreEqual(180, rectangle.GetHeight(), 1e-5);
}
[NUnit.Framework.Test]
public virtual void SetBBoxNormalizeXTest() {
Rectangle rectangle = new Rectangle(0, 0, 100, 200);
NUnit.Framework.Assert.AreEqual(0, rectangle.GetX(), 1e-5);
NUnit.Framework.Assert.AreEqual(0, rectangle.GetY(), 1e-5);
NUnit.Framework.Assert.AreEqual(100, rectangle.GetWidth(), 1e-5);
NUnit.Framework.Assert.AreEqual(200, rectangle.GetHeight(), 1e-5);
//set bBox where llx > urx
rectangle.SetBbox(90, 10, 10, 190);
NUnit.Framework.Assert.AreEqual(10, rectangle.GetX(), 1e-5);
NUnit.Framework.Assert.AreEqual(10, rectangle.GetY(), 1e-5);
NUnit.Framework.Assert.AreEqual(80, rectangle.GetWidth(), 1e-5);
NUnit.Framework.Assert.AreEqual(180, rectangle.GetHeight(), 1e-5);
}
[NUnit.Framework.Test]
public virtual void SetBBoxNormalizeYTest() {
Rectangle rectangle = new Rectangle(0, 0, 100, 200);
NUnit.Framework.Assert.AreEqual(0, rectangle.GetX(), 1e-5);
NUnit.Framework.Assert.AreEqual(0, rectangle.GetY(), 1e-5);
NUnit.Framework.Assert.AreEqual(100, rectangle.GetWidth(), 1e-5);
NUnit.Framework.Assert.AreEqual(200, rectangle.GetHeight(), 1e-5);
//set bBox where lly > ury
rectangle.SetBbox(10, 190, 90, 10);
NUnit.Framework.Assert.AreEqual(10, rectangle.GetX(), 1e-5);
NUnit.Framework.Assert.AreEqual(10, rectangle.GetY(), 1e-5);
NUnit.Framework.Assert.AreEqual(80, rectangle.GetWidth(), 1e-5);
NUnit.Framework.Assert.AreEqual(180, rectangle.GetHeight(), 1e-5);
}
[NUnit.Framework.Test]
public virtual void SetXTest() {
Rectangle rectangle = new Rectangle(0, 0, 100, 200);
NUnit.Framework.Assert.AreEqual(0, rectangle.GetX(), 1e-5);
rectangle.SetX(50);
NUnit.Framework.Assert.AreEqual(50, rectangle.GetX(), 1e-5);
}
[NUnit.Framework.Test]
public virtual void SetYTest() {
Rectangle rectangle = new Rectangle(0, 0, 100, 200);
NUnit.Framework.Assert.AreEqual(0, rectangle.GetY(), 1e-5);
rectangle.SetY(50);
NUnit.Framework.Assert.AreEqual(50, rectangle.GetY(), 1e-5);
}
[NUnit.Framework.Test]
public virtual void SetWidthTest() {
Rectangle rectangle = new Rectangle(0, 0, 100, 200);
NUnit.Framework.Assert.AreEqual(100, rectangle.GetWidth(), 1e-5);
rectangle.SetWidth(50);
NUnit.Framework.Assert.AreEqual(50, rectangle.GetWidth(), 1e-5);
}
[NUnit.Framework.Test]
public virtual void SetHeightTest() {
Rectangle rectangle = new Rectangle(0, 0, 100, 200);
NUnit.Framework.Assert.AreEqual(200, rectangle.GetHeight(), 1e-5);
rectangle.SetHeight(50);
NUnit.Framework.Assert.AreEqual(50, rectangle.GetHeight(), 1e-5);
}
[NUnit.Framework.Test]
public virtual void IncreaseHeightTest() {
Rectangle rectangle = new Rectangle(0, 0, 100, 200);
NUnit.Framework.Assert.AreEqual(200, rectangle.GetHeight(), 1e-5);
rectangle.IncreaseHeight(50);
NUnit.Framework.Assert.AreEqual(250, rectangle.GetHeight(), 1e-5);
}
[NUnit.Framework.Test]
public virtual void DecreaseHeightTest() {
Rectangle rectangle = new Rectangle(0, 0, 100, 200);
NUnit.Framework.Assert.AreEqual(200, rectangle.GetHeight(), 1e-5);
rectangle.DecreaseHeight(50);
NUnit.Framework.Assert.AreEqual(150, rectangle.GetHeight(), 1e-5);
}
[NUnit.Framework.Test]
public virtual void ApplyMarginsShrinkTest() {
Rectangle rectangle = new Rectangle(0, 0, 100, 200);
NUnit.Framework.Assert.AreEqual(0, rectangle.GetX(), 1e-5);
NUnit.Framework.Assert.AreEqual(0, rectangle.GetY(), 1e-5);
NUnit.Framework.Assert.AreEqual(100, rectangle.GetWidth(), 1e-5);
NUnit.Framework.Assert.AreEqual(200, rectangle.GetHeight(), 1e-5);
//shrink the rectangle
rectangle.ApplyMargins(20, 20, 20, 20, false);
NUnit.Framework.Assert.AreEqual(20, rectangle.GetX(), 1e-5);
NUnit.Framework.Assert.AreEqual(20, rectangle.GetY(), 1e-5);
NUnit.Framework.Assert.AreEqual(60, rectangle.GetWidth(), 1e-5);
NUnit.Framework.Assert.AreEqual(160, rectangle.GetHeight(), 1e-5);
}
[NUnit.Framework.Test]
public virtual void ApplyMarginsExpandTest() {
Rectangle rectangle = new Rectangle(20, 20, 100, 200);
NUnit.Framework.Assert.AreEqual(20, rectangle.GetX(), 1e-5);
NUnit.Framework.Assert.AreEqual(20, rectangle.GetY(), 1e-5);
NUnit.Framework.Assert.AreEqual(100, rectangle.GetWidth(), 1e-5);
NUnit.Framework.Assert.AreEqual(200, rectangle.GetHeight(), 1e-5);
//expand the rectangle
rectangle.ApplyMargins(10, 10, 10, 10, true);
NUnit.Framework.Assert.AreEqual(10, rectangle.GetX(), 1e-5);
NUnit.Framework.Assert.AreEqual(10, rectangle.GetY(), 1e-5);
NUnit.Framework.Assert.AreEqual(120, rectangle.GetWidth(), 1e-5);
NUnit.Framework.Assert.AreEqual(220, rectangle.GetHeight(), 1e-5);
}
[NUnit.Framework.Test]
public virtual void ToStringTest() {
Rectangle rectangle = new Rectangle(0, 0, 100f, 200f);
String rectangleString = rectangle.ToString();
//Using contains() to check for value instead of equals() on the whole string due to the
//differences between decimal numbers formatting in java and .NET.
NUnit.Framework.Assert.IsTrue(rectangleString.Contains("100"));
NUnit.Framework.Assert.IsTrue(rectangleString.Contains("200"));
}
[NUnit.Framework.Test]
public virtual void CloneTest() {
PageSize originalPageSize = new PageSize(15, 20);
PageSize copyAsPageSize = (PageSize)originalPageSize.Clone();
Rectangle copyAsRectangle = ((Rectangle)originalPageSize).Clone();
NUnit.Framework.Assert.AreEqual(typeof(PageSize), copyAsPageSize.GetType());
NUnit.Framework.Assert.AreEqual(typeof(PageSize), copyAsRectangle.GetType());
}
[NUnit.Framework.Test]
public virtual void DecreaseWidthTest() {
Rectangle rectangle = new Rectangle(100, 200);
rectangle.DecreaseWidth(10);
NUnit.Framework.Assert.AreEqual(90, rectangle.GetWidth(), Rectangle.EPS);
}
[NUnit.Framework.Test]
public virtual void IncreaseWidthTest() {
Rectangle rectangle = new Rectangle(100, 200);
rectangle.IncreaseWidth(10);
NUnit.Framework.Assert.AreEqual(110, rectangle.GetWidth(), Rectangle.EPS);
}
}
}

View File

@@ -0,0 +1,78 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using TSpdf.Commons.Utils;
using TSpdf.Test;
namespace TSpdf.Kernel.Geom {
[NUnit.Framework.Category("UnitTest")]
public class ShapeTransformUtilTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void TransformBezierCurveTest() {
BezierCurve inBezierCurve = new BezierCurve(JavaUtil.ArraysAsList(new Point(0, 0), new Point(0, 5), new Point
(5, 5), new Point(5, 0)));
Matrix ctm = new Matrix(1, 0, 0, 1, 5, 5);
BezierCurve outBezierCurve = ShapeTransformUtil.TransformBezierCurve(inBezierCurve, ctm);
BezierCurve cmpBezierCurve = new BezierCurve(JavaUtil.ArraysAsList(new Point(-5, -5), new Point(-5, 0), new
Point(0, 0), new Point(0, -5)));
NUnit.Framework.Assert.AreEqual(cmpBezierCurve.GetBasePoints().ToArray(), outBezierCurve.GetBasePoints().ToArray
());
}
[NUnit.Framework.Test]
public virtual void TransformLineTest() {
Line inLine = new Line(new Point(0, 0), new Point(10, 10));
Matrix ctm = new Matrix(2, 0, 0, 1, 5, 5);
Line outLine = ShapeTransformUtil.TransformLine(inLine, ctm);
Line cmpLine = new Line(new Point(-2.5, -5), new Point(2.5, 5));
NUnit.Framework.Assert.AreEqual(cmpLine.GetBasePoints().ToArray(), outLine.GetBasePoints().ToArray());
}
[NUnit.Framework.Test]
public virtual void TransformPathTest() {
Line inLine = new Line(new Point(0, 0), new Point(10, 10));
BezierCurve inBezierCurve = new BezierCurve(JavaUtil.ArraysAsList(new Point(0, 0), new Point(0, 5), new Point
(5, 5), new Point(5, 0)));
Subpath inSubpath = new Subpath();
inSubpath.AddSegment(inLine);
inSubpath.AddSegment(inBezierCurve);
Path inPath = new Path(JavaUtil.ArraysAsList(inSubpath));
Matrix ctm = new Matrix(1, 0, 0, 1, 5, 5);
Path outPath = ShapeTransformUtil.TransformPath(inPath, ctm);
Line cmpLine = new Line(new Point(-5, -5), new Point(5, 5));
BezierCurve cmpBezierCurve = new BezierCurve(JavaUtil.ArraysAsList(new Point(-5, -5), new Point(-5, 0), new
Point(0, 0), new Point(0, -5)));
Subpath cmpSubpath = new Subpath();
inSubpath.AddSegment(cmpLine);
inSubpath.AddSegment(cmpBezierCurve);
Path cmpPath = new Path(JavaUtil.ArraysAsList(cmpSubpath));
for (int i = 0; i < cmpPath.GetSubpaths().Count; i++) {
Subpath subpath = cmpPath.GetSubpaths()[i];
for (int j = 0; j < subpath.GetSegments().Count; j++) {
IShape cmpShape = subpath.GetSegments()[j];
IShape outShape = outPath.GetSubpaths()[i].GetSegments()[j];
NUnit.Framework.Assert.AreEqual(cmpShape.GetBasePoints().ToArray(), outShape.GetBasePoints().ToArray());
}
}
}
}
}

View File

@@ -0,0 +1,57 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using TSpdf.Test;
namespace TSpdf.Kernel.Geom {
[NUnit.Framework.Category("UnitTest")]
public class VectorTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void TestCrossVector() {
Vector v = new Vector(2, 3, 4);
Matrix m = new Matrix(5, 6, 7, 8, 9, 10);
Vector shouldBe = new Vector(67, 76, 4);
Vector rslt = v.Cross(m);
NUnit.Framework.Assert.AreEqual(shouldBe, rslt);
}
}
}

View File

@@ -0,0 +1,50 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using TSpdf.Test;
namespace TSpdf.Kernel.Numbering {
[NUnit.Framework.Category("UnitTest")]
public class ArmenianNumberingTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void NegativeToArmenianTest() {
NUnit.Framework.Assert.AreEqual("", ArmenianNumbering.ToArmenian(-10));
}
[NUnit.Framework.Test]
public virtual void ZeroToArmenianTest() {
NUnit.Framework.Assert.AreEqual("", ArmenianNumbering.ToArmenian(0));
}
[NUnit.Framework.Test]
public virtual void ToArmenianTest() {
NUnit.Framework.Assert.AreEqual("\u0554\u054B\u0542\u0539", ArmenianNumbering.ToArmenian(9999));
NUnit.Framework.Assert.AreEqual("\u0552\u054A\u0540\u0534", ArmenianNumbering.ToArmenian(7874));
}
[NUnit.Framework.Test]
public virtual void NumberGreaterThan9999toArmenianTest() {
NUnit.Framework.Assert.AreEqual("\u0554\u0554\u0554\u0554\u0554\u0554\u0554\u0532", ArmenianNumbering.ToArmenian
(63002));
}
}
}

View File

@@ -0,0 +1,50 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using TSpdf.Test;
namespace TSpdf.Kernel.Numbering {
[NUnit.Framework.Category("UnitTest")]
public class GeorgianNumberingTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void NegativeToGeorgianTest() {
NUnit.Framework.Assert.AreEqual("", GeorgianNumbering.ToGeorgian(-10));
}
[NUnit.Framework.Test]
public virtual void ZeroToGeorgianTest() {
NUnit.Framework.Assert.AreEqual("", GeorgianNumbering.ToGeorgian(0));
}
[NUnit.Framework.Test]
public virtual void ToGeorgianTest() {
NUnit.Framework.Assert.AreEqual("\u10F5", GeorgianNumbering.ToGeorgian(10000));
NUnit.Framework.Assert.AreEqual("\u10F4\u10E8\u10F2\u10D6", GeorgianNumbering.ToGeorgian(7967));
}
[NUnit.Framework.Test]
public virtual void NumberGreaterThan10000toGeorgianTest() {
NUnit.Framework.Assert.AreEqual("\u10F5\u10F5\u10F5\u10F5\u10F5\u10F5\u10D2", GeorgianNumbering.ToGeorgian
(60003));
}
}
}

View File

@@ -0,0 +1,95 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System.Text;
using TSpdf.Test;
namespace TSpdf.Kernel.Numbering {
[NUnit.Framework.Category("UnitTest")]
public class GreekAlphabetNumberingTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void TestUpperCase() {
StringBuilder builder = new StringBuilder();
for (int i = 1; i <= 25; i++) {
builder.Append(GreekAlphabetNumbering.ToGreekAlphabetNumber(i, true));
}
// 25th symbol is `AA`, i.e. alphabet has 24 letters.
NUnit.Framework.Assert.AreEqual("ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩΑΑ", builder.ToString());
}
[NUnit.Framework.Test]
public virtual void TestLowerCase() {
StringBuilder builder = new StringBuilder();
for (int i = 1; i <= 25; i++) {
builder.Append(GreekAlphabetNumbering.ToGreekAlphabetNumber(i, false));
}
// 25th symbol is `αα`, i.e. alphabet has 24 letters.
NUnit.Framework.Assert.AreEqual("αβγδεζηθικλμνξοπρστυφχψωαα", builder.ToString());
}
[NUnit.Framework.Test]
public virtual void TestUpperCaseSymbol() {
StringBuilder builder = new StringBuilder();
for (int i = 1; i <= 25; i++) {
builder.Append(GreekAlphabetNumbering.ToGreekAlphabetNumber(i, true, true));
}
// Symbol font use regular WinAnsi codes for greek letters.
NUnit.Framework.Assert.AreEqual("ABGDEZHQIKLMNXOPRSTUFCYWAA", builder.ToString());
}
[NUnit.Framework.Test]
public virtual void TestLowerCaseSymbol() {
StringBuilder builder = new StringBuilder();
for (int i = 1; i <= 25; i++) {
builder.Append(GreekAlphabetNumbering.ToGreekAlphabetNumber(i, false, true));
}
// Symbol font use regular WinAnsi codes for greek letters.
NUnit.Framework.Assert.AreEqual("abgdezhqiklmnxoprstufcywaa", builder.ToString());
}
[NUnit.Framework.Test]
public virtual void IntIsNotEnoughForInternalCalculationsTest() {
NUnit.Framework.Assert.AreEqual("ζλαββωσ", GreekAlphabetNumbering.ToGreekAlphabetNumberLowerCase(1234567890
));
}
}
}

View File

@@ -0,0 +1,65 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.Test;
namespace TSpdf.Kernel.Numbering {
[NUnit.Framework.Category("UnitTest")]
public class RomanNumberingTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void NegativeConvertTest() {
NUnit.Framework.Assert.AreEqual("-vi", RomanNumbering.Convert(-6));
}
[NUnit.Framework.Test]
public virtual void ZeroConvertTest() {
NUnit.Framework.Assert.AreEqual("", RomanNumbering.Convert(0));
}
[NUnit.Framework.Test]
public virtual void ConvertTest() {
NUnit.Framework.Assert.AreEqual("mdclxvi", RomanNumbering.Convert(1666));
NUnit.Framework.Assert.AreEqual("mcmlxxxiii", RomanNumbering.Convert(1983));
NUnit.Framework.Assert.AreEqual("mmm", RomanNumbering.Convert(3000));
NUnit.Framework.Assert.AreEqual("|vi|", RomanNumbering.Convert(6000));
NUnit.Framework.Assert.AreEqual("|vi|dccxxxiii", RomanNumbering.Convert(6733));
}
[NUnit.Framework.Test]
public virtual void ToRomanTest() {
String expected = "dcclvi";
NUnit.Framework.Assert.AreEqual(expected.ToUpperInvariant(), RomanNumbering.ToRoman(756, true));
NUnit.Framework.Assert.AreEqual(expected.ToLowerInvariant(), RomanNumbering.ToRoman(756, false));
}
[NUnit.Framework.Test]
public virtual void ToRomanUpperCaseTest() {
NUnit.Framework.Assert.AreEqual("CCCLXXXVI", RomanNumbering.ToRomanUpperCase(386));
}
[NUnit.Framework.Test]
public virtual void ToRomanLowerCaseTest() {
NUnit.Framework.Assert.AreEqual("xxvi", RomanNumbering.ToRomanLowerCase(26));
}
}
}

View File

@@ -0,0 +1,292 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.Text;
using TSpdf.IO.Font;
using TSpdf.IO.Font.Constants;
using TSpdf.Kernel.Font;
using TSpdf.Kernel.Pdf.Canvas;
using TSpdf.Kernel.Pdf.Canvas.Parser;
using TSpdf.Kernel.Utils;
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("IntegrationTest")]
public class EncodingTest : ExtendedTSpdfTest {
public static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/pdf/EncodingTest/";
public static readonly String outputFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory + "/test/TSpdf/kernel/pdf/EncodingTest/";
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
CreateDestinationFolder(outputFolder);
}
[NUnit.Framework.Test]
public virtual void SurrogatePairTest() {
String fileName = "surrogatePairTest.pdf";
PdfWriter writer = new PdfWriter(outputFolder + fileName);
PdfDocument doc = new PdfDocument(writer);
PdfFont font = PdfFontFactory.CreateFont(sourceFolder + "DejaVuSans.ttf", PdfEncodings.IDENTITY_H);
PdfCanvas canvas = new PdfCanvas(doc.AddNewPage());
canvas.SaveState().BeginText().MoveText(36, 750).SetFontAndSize(font, 72).ShowText("\uD835\uDD59\uD835\uDD56\uD835\uDD5D\uD835\uDD5D\uD835\uDD60\uD83D\uDE09\uD835\uDD68"
+ "\uD835\uDD60\uD835\uDD63\uD835\uDD5D\uD835\uDD55").EndText().RestoreState();
canvas.Release();
doc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outputFolder + fileName, sourceFolder + "cmp_"
+ fileName, outputFolder, "diff_"));
}
[NUnit.Framework.Test]
public virtual void CustomSimpleEncodingTimesRomanTest() {
String fileName = "customSimpleEncodingTimesRomanTest.pdf";
PdfWriter writer = new PdfWriter(outputFolder + fileName);
PdfDocument doc = new PdfDocument(writer);
PdfFont font = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", "# simple 1 0020 041c 0456 0440 044a 0050 0065 0061 0063"
, PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED);
PdfCanvas canvas = new PdfCanvas(doc.AddNewPage());
canvas.SaveState().BeginText().MoveText(36, 806).SetFontAndSize(font, 12)
// Міръ Peace
.ShowText("\u041C\u0456\u0440\u044A Peace").EndText().RestoreState();
doc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outputFolder + fileName, sourceFolder + "cmp_"
+ fileName, outputFolder, "diff_"));
}
[NUnit.Framework.Test]
public virtual void CustomFullEncodingTimesRomanTest() {
String fileName = "customFullEncodingTimesRomanTest.pdf";
PdfWriter writer = new PdfWriter(outputFolder + fileName);
PdfDocument doc = new PdfDocument(writer);
PdfFont font = PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN, "# full 'A' Aring 0041 'E' Egrave 0045 32 space 0020"
);
PdfCanvas canvas = new PdfCanvas(doc.AddNewPage());
canvas.SaveState().BeginText().MoveText(36, 806).SetFontAndSize(font, 12).ShowText("A E").EndText().RestoreState
();
doc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outputFolder + fileName, sourceFolder + "cmp_"
+ fileName, outputFolder, "diff_"));
}
[NUnit.Framework.Test]
public virtual void NotdefInStandardFontTest() {
String fileName = "notdefInStandardFontTest.pdf";
PdfWriter writer = new PdfWriter(outputFolder + fileName);
PdfDocument doc = new PdfDocument(writer);
PdfFont font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA, "# full 'A' Aring 0041 'E' abc11 0045 32 space 0020"
);
PdfCanvas canvas = new PdfCanvas(doc.AddNewPage());
canvas.SaveState().BeginText().MoveText(36, 786).SetFontAndSize(font, 36).ShowText("A E").EndText().RestoreState
();
font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA, PdfEncodings.WINANSI);
canvas.SaveState().BeginText().MoveText(36, 756).SetFontAndSize(font, 36).ShowText("\u0188").EndText().RestoreState
();
doc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outputFolder + fileName, sourceFolder + "cmp_"
+ fileName, outputFolder, "diff_"));
}
[NUnit.Framework.Test]
public virtual void NotdefInTrueTypeFontTest() {
String fileName = "notdefInTrueTypeFontTest.pdf";
PdfWriter writer = new PdfWriter(outputFolder + fileName);
PdfDocument doc = new PdfDocument(writer);
PdfFont font = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", "# simple 32 0020 00C5 1987", PdfFontFactory.EmbeddingStrategy
.PREFER_EMBEDDED);
PdfCanvas canvas = new PdfCanvas(doc.AddNewPage());
canvas.SaveState().BeginText().MoveText(36, 786).SetFontAndSize(font, 36).ShowText("\u00C5 \u1987").EndText
().RestoreState();
font = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", PdfEncodings.WINANSI, PdfFontFactory.EmbeddingStrategy
.PREFER_EMBEDDED);
canvas.SaveState().BeginText().MoveText(36, 756).SetFontAndSize(font, 36).ShowText("\u1987").EndText().RestoreState
();
doc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outputFolder + fileName, sourceFolder + "cmp_"
+ fileName, outputFolder, "diff_"));
}
[NUnit.Framework.Test]
public virtual void NotdefInType0Test() {
String fileName = "notdefInType0Test.pdf";
PdfWriter writer = new PdfWriter(outputFolder + fileName);
PdfDocument doc = new PdfDocument(writer);
PdfFont font = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", PdfEncodings.IDENTITY_H);
PdfCanvas canvas = new PdfCanvas(doc.AddNewPage());
canvas.SaveState().BeginText().MoveText(36, 786).SetFontAndSize(font, 36).ShowText("\u00C5 \u1987").EndText
().RestoreState();
doc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outputFolder + fileName, sourceFolder + "cmp_"
+ fileName, outputFolder, "diff_"));
}
[NUnit.Framework.Test]
public virtual void SymbolDefaultFontTest() {
String fileName = "symbolDefaultFontTest.pdf";
PdfWriter writer = new PdfWriter(outputFolder + fileName);
PdfDocument doc = new PdfDocument(writer);
PdfFont font = PdfFontFactory.CreateFont(StandardFonts.SYMBOL);
FillSymbolDefaultPage(font, doc.AddNewPage());
//WinAnsi encoding doesn't support special symbols
font = PdfFontFactory.CreateFont(StandardFonts.SYMBOL, PdfEncodings.WINANSI);
FillSymbolDefaultPage(font, doc.AddNewPage());
doc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outputFolder + fileName, sourceFolder + "cmp_"
+ fileName, outputFolder, "diff_"));
}
private void FillSymbolDefaultPage(PdfFont font, PdfPage page) {
PdfCanvas canvas = new PdfCanvas(page);
StringBuilder builder = new StringBuilder();
for (int i = 32; i <= 100; i++) {
builder.Append((char)i);
}
canvas.SaveState().BeginText().SetFontAndSize(font, 12).MoveText(36, 806).ShowText(builder.ToString()).EndText
().RestoreState();
builder = new StringBuilder();
for (int i = 101; i <= 190; i++) {
builder.Append((char)i);
}
canvas.SaveState().BeginText().SetFontAndSize(font, 12).MoveText(36, 786).ShowText(builder.ToString()).EndText
();
builder = new StringBuilder();
for (int i = 191; i <= 254; i++) {
builder.Append((char)i);
}
canvas.BeginText().MoveText(36, 766).ShowText(builder.ToString()).EndText().RestoreState();
}
[NUnit.Framework.Test]
public virtual void SymbolTrueTypeFontWinAnsiTest() {
String fileName = "symbolTrueTypeFontWinAnsiTest.pdf";
PdfWriter writer = new PdfWriter(outputFolder + fileName);
PdfDocument doc = new PdfDocument(writer);
PdfFont font = PdfFontFactory.CreateFont(sourceFolder + "Symbols1.ttf", PdfEncodings.WINANSI, PdfFontFactory.EmbeddingStrategy
.PREFER_EMBEDDED);
PdfCanvas canvas = new PdfCanvas(doc.AddNewPage());
StringBuilder str = new StringBuilder();
for (int i = 32; i <= 65; i++) {
str.Append((char)i);
}
canvas.SaveState().BeginText().MoveText(36, 786).SetFontAndSize(font, 36).ShowText(str.ToString()).EndText
();
str = new StringBuilder();
for (int i = 65; i <= 190; i++) {
str.Append((char)i);
}
canvas.SaveState().BeginText().MoveText(36, 756).SetFontAndSize(font, 36).ShowText(str.ToString()).EndText
();
str = new StringBuilder();
for (int i = 191; i <= 254; i++) {
str.Append((char)i);
}
canvas.BeginText().MoveText(36, 726).SetFontAndSize(font, 36).ShowText(str.ToString()).EndText().RestoreState
();
doc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outputFolder + fileName, sourceFolder + "cmp_"
+ fileName, outputFolder, "diff_"));
}
[NUnit.Framework.Test]
public virtual void SymbolTrueTypeFontIdentityTest() {
String fileName = "symbolTrueTypeFontIdentityTest.pdf";
PdfWriter writer = new PdfWriter(outputFolder + fileName);
PdfDocument doc = new PdfDocument(writer);
PdfFont font = PdfFontFactory.CreateFont(sourceFolder + "Symbols1.ttf", PdfEncodings.IDENTITY_H);
PdfCanvas canvas = new PdfCanvas(doc.AddNewPage());
StringBuilder builder = new StringBuilder();
for (int i = 32; i <= 100; i++) {
builder.Append((char)i);
}
StringBuilder str = new StringBuilder(builder.ToString());
canvas.SaveState().BeginText().SetFontAndSize(font, 36).MoveText(36, 786).ShowText(str.ToString()).EndText
().RestoreState();
str = new StringBuilder();
for (int i = 101; i <= 190; i++) {
str.Append((char)i);
}
canvas.SaveState().BeginText().SetFontAndSize(font, 36).MoveText(36, 746).ShowText(str.ToString()).EndText
().RestoreState();
str = new StringBuilder();
for (int i = 191; i <= 254; i++) {
str.Append((char)i);
}
canvas.SaveState().BeginText().SetFontAndSize(font, 36).MoveText(36, 766).ShowText(str.ToString()).EndText
().RestoreState();
doc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outputFolder + fileName, sourceFolder + "cmp_"
+ fileName, outputFolder, "diff_"));
}
[NUnit.Framework.Test]
public virtual void SymbolTrueTypeFontSameCharsIdentityTest() {
String fileName = "symbolTrueTypeFontSameCharsIdentityTest.pdf";
PdfWriter writer = new PdfWriter(outputFolder + fileName);
PdfDocument doc = new PdfDocument(writer);
PdfFont font = PdfFontFactory.CreateFont(sourceFolder + "Symbols1.ttf", PdfEncodings.IDENTITY_H);
PdfCanvas canvas = new PdfCanvas(doc.AddNewPage());
String line = "AABBCCDDEEFFGGHHIIJJ";
canvas.SaveState().BeginText().SetFontAndSize(font, 36).MoveText(36, 786).ShowText(line).EndText().RestoreState
();
doc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outputFolder + fileName, sourceFolder + "cmp_"
+ fileName, outputFolder, "diff_"));
}
[NUnit.Framework.Test]
public virtual void EncodingStreamExtractionTest() {
String fileName = sourceFolder + "encodingStream01.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(fileName));
String extractedText = PdfTextExtractor.GetTextFromPage(pdfDocument.GetPage(1));
NUnit.Framework.Assert.AreEqual("abc", extractedText);
}
[NUnit.Framework.Test]
public virtual void DifferentCodeSpaceRangeLengthsExtractionTest() {
String fileName = sourceFolder + "differentCodeSpaceRangeLengths01.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(fileName));
String extractedText = PdfTextExtractor.GetTextFromPage(pdfDocument.GetPage(1));
NUnit.Framework.Assert.AreEqual("Hello\u7121\u540dworld\u6b98\u528d", extractedText);
}
}
}

View File

@@ -0,0 +1,165 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.Kernel.Geom;
using TSpdf.Kernel.Logs;
using TSpdf.Kernel.Pdf.Annot;
using TSpdf.Kernel.Pdf.Filespec;
using TSpdf.Kernel.Utils;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("BouncyCastleIntegrationTest")]
public class EncryptedEmbeddedStreamsHandlerTest : ExtendedTSpdfTest {
public static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/pdf/EncryptedEmbeddedStreamsHandlerTest/";
public static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/pdf/EncryptedEmbeddedStreamsHandlerTest/";
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
CreateDestinationFolder(destinationFolder);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void NoReaderStandardEncryptionAddFileAttachment() {
String outFileName = destinationFolder + "noReaderStandardEncryptionAddFileAttachment.pdf";
String cmpFileName = sourceFolder + "cmp_noReaderStandardEncryptionAddFileAttachment.pdf";
PdfDocument pdfDocument = CreateEncryptedDocument(EncryptionConstants.STANDARD_ENCRYPTION_128, outFileName
);
PdfFileSpec fs = PdfFileSpec.CreateEmbeddedFileSpec(pdfDocument, "file".GetBytes(), "description", "file.txt"
, null, null, null);
pdfDocument.AddFileAttachment("file.txt", fs);
pdfDocument.AddNewPage();
pdfDocument.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder
, "diff", "password".GetBytes(), "password".GetBytes()));
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void NoReaderAesEncryptionAddFileAttachment() {
String outFileName = destinationFolder + "noReaderAesEncryptionAddFileAttachment.pdf";
String cmpFileName = sourceFolder + "cmp_noReaderAesEncryptionAddFileAttachment.pdf";
PdfDocument pdfDocument = CreateEncryptedDocument(EncryptionConstants.ENCRYPTION_AES_128, outFileName);
PdfFileSpec fs = PdfFileSpec.CreateEmbeddedFileSpec(pdfDocument, "file".GetBytes(), "description", "file.txt"
, null, null, null);
pdfDocument.AddFileAttachment("file.txt", fs);
pdfDocument.AddNewPage();
pdfDocument.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder
, "diff", "password".GetBytes(), "password".GetBytes()));
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void WithReaderStandardEncryptionAddFileAttachment() {
String outFileName = destinationFolder + "withReaderStandardEncryptionAddFileAttachment.pdf";
String cmpFileName = sourceFolder + "cmp_withReaderStandardEncryptionAddFileAttachment.pdf";
PdfReader reader = new PdfReader(sourceFolder + "pdfWithFileAttachments.pdf", new ReaderProperties().SetPassword
("password".GetBytes()));
// Setting compression level to zero doesn't affect the encryption at any level.
// We do it to simplify observation of the resultant PDF.
PdfDocument pdfDocument = new PdfDocument(reader, new PdfWriter(outFileName).SetCompressionLevel(0));
PdfFileSpec fs = PdfFileSpec.CreateEmbeddedFileSpec(pdfDocument, "file".GetBytes(), "description", "file.txt"
, null, null, null);
pdfDocument.AddFileAttachment("file.txt", fs);
pdfDocument.AddNewPage();
pdfDocument.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder
, "diff"));
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void NoReaderStandardEncryptionAddAnnotation() {
String outFileName = destinationFolder + "noReaderStandardEncryptionAddAnnotation.pdf";
String cmpFileName = sourceFolder + "cmp_noReaderStandardEncryptionAddAnnotation.pdf";
PdfDocument pdfDocument = CreateEncryptedDocument(EncryptionConstants.STANDARD_ENCRYPTION_128, outFileName
);
pdfDocument.AddNewPage();
PdfFileSpec fs = PdfFileSpec.CreateEmbeddedFileSpec(pdfDocument, "file".GetBytes(), "description", "file.txt"
, null, null, null);
pdfDocument.GetPage(1).AddAnnotation(new PdfFileAttachmentAnnotation(new Rectangle(100, 100), fs));
pdfDocument.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder
, "diff", "password".GetBytes(), "password".GetBytes()));
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void WithReaderStandardEncryptionAddAnnotation() {
String outFileName = destinationFolder + "withReaderStandardEncryptionAddAnnotation.pdf";
String cmpFileName = sourceFolder + "cmp_withReaderStandardEncryptionAddAnnotation.pdf";
PdfReader reader = new PdfReader(sourceFolder + "pdfWithFileAttachmentAnnotations.pdf", new ReaderProperties
().SetPassword("password".GetBytes()));
// Setting compression level to zero doesn't affect the encryption at any level.
// We do it to simplify observation of the resultant PDF.
PdfDocument pdfDocument = new PdfDocument(reader, new PdfWriter(outFileName).SetCompressionLevel(0));
pdfDocument.AddNewPage();
PdfFileSpec fs = PdfFileSpec.CreateEmbeddedFileSpec(pdfDocument, "file".GetBytes(), "description", "file.txt"
, null, null, null);
pdfDocument.GetPage(1).AddAnnotation(new PdfFileAttachmentAnnotation(new Rectangle(100, 100), fs));
pdfDocument.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder
, "diff"));
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void ReaderWithoutEncryptionWriterStandardEncryption() {
String outFileName = destinationFolder + "readerWithoutEncryptionWriterStandardEncryption.pdf";
String cmpFileName = sourceFolder + "cmp_readerWithoutEncryptionWriterStandardEncryption.pdf";
PdfReader reader = new PdfReader(sourceFolder + "pdfWithUnencryptedAttachmentAnnotations.pdf");
PdfDocument pdfDocument = CreateEncryptedDocument(reader, EncryptionConstants.STANDARD_ENCRYPTION_128, outFileName
);
PdfFileSpec fs = PdfFileSpec.CreateEmbeddedFileSpec(pdfDocument, "file".GetBytes(), "description", "file.txt"
, null, null, null);
pdfDocument.AddFileAttachment("new attachment", fs);
pdfDocument.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder
, "diff", "password".GetBytes(), "password".GetBytes()));
}
private PdfDocument CreateEncryptedDocument(int encryptionAlgorithm, String outFileName) {
PdfWriter writer = new PdfWriter(outFileName, new WriterProperties().SetStandardEncryption("password".GetBytes
(), "password".GetBytes(), 0, encryptionAlgorithm | EncryptionConstants.EMBEDDED_FILES_ONLY));
// Setting compression level to zero doesn't affect the encryption at any level.
// We do it to simplify observation of the resultant PDF.
writer.SetCompressionLevel(0);
return new PdfDocument(writer);
}
private PdfDocument CreateEncryptedDocument(PdfReader reader, int encryptionAlgorithm, String outFileName) {
PdfWriter writer = new PdfWriter(outFileName, new WriterProperties().SetStandardEncryption("password".GetBytes
(), "password".GetBytes(), 0, encryptionAlgorithm | EncryptionConstants.EMBEDDED_FILES_ONLY));
// Setting compression level to zero doesn't affect the encryption at any level.
// We do it to simplify observation of the resultant PDF.
writer.SetCompressionLevel(0);
return new PdfDocument(reader, writer);
}
}
}

View File

@@ -0,0 +1,77 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using TSpdf.Commons.Actions.Data;
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("IntegrationTest")]
public class FingerPrintTest : ExtendedTSpdfTest {
private ProductData productData;
private ProductData productData2;
private ProductData duplicateProductData;
[NUnit.Framework.SetUp]
public virtual void BeforeTest() {
this.productData = new ProductData("pdfProduct", "pdfProduct", "7.0.0", 1900, 2000);
this.productData2 = new ProductData("pdfProduct2", "pdfProduct2", "7.0.0", 1900, 2000);
this.duplicateProductData = new ProductData("pdfProduct", "pdfProduct", "7.0.0", 1900, 2000);
}
[NUnit.Framework.Test]
public virtual void NormalAddTest() {
FingerPrint fingerPrint = new FingerPrint();
NUnit.Framework.Assert.IsTrue(fingerPrint.RegisterProduct(productData));
NUnit.Framework.Assert.IsTrue(fingerPrint.RegisterProduct(productData2));
NUnit.Framework.Assert.AreEqual(2, fingerPrint.GetProducts().Count);
}
[NUnit.Framework.Test]
public virtual void DuplicateTest() {
FingerPrint fingerPrint = new FingerPrint();
fingerPrint.RegisterProduct(productData);
NUnit.Framework.Assert.IsFalse(fingerPrint.RegisterProduct(duplicateProductData));
}
}
}

View File

@@ -0,0 +1,85 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.Collections.Generic;
using TSpdf.Commons.Utils;
using TSpdf.IO.Font;
using TSpdf.IO.Font.Otf;
using TSpdf.Kernel.Font;
using TSpdf.Kernel.Pdf.Canvas;
using TSpdf.Kernel.Pdf.Canvas.Parser;
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("IntegrationTest")]
public class FontToUnicodeTest : ExtendedTSpdfTest {
public static readonly String fontsFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/pdf/fonts/";
public static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/pdf/FontToUnicodeTest/";
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
CreateDestinationFolder(destinationFolder);
}
[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
String outFileName = destinationFolder + "severalUnicodesWithinOneGlyphTest.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName));
PdfFont font = PdfFontFactory.CreateFont(fontsFolder + "NotoSansCJKjp-Bold.otf", PdfEncodings.IDENTITY_H);
IList<Glyph> glyphs = JavaCollectionsUtil.SingletonList(font.GetGlyph((int)'\u65E0'));
GlyphLine glyphLine = new GlyphLine(glyphs);
PdfCanvas canvas2 = new PdfCanvas(pdfDocument.AddNewPage());
canvas2.SaveState().BeginText().MoveText(36, 800).SetFontAndSize(font, 12).ShowText(glyphLine).EndText().RestoreState
();
pdfDocument.Close();
PdfDocument resultantPdfAsFile = new PdfDocument(new PdfReader(outFileName));
String actualUnicode = PdfTextExtractor.GetTextFromPage(resultantPdfAsFile.GetFirstPage());
NUnit.Framework.Assert.AreEqual("\u2F46", actualUnicode);
}
}
}

View File

@@ -0,0 +1,931 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.Collections.Generic;
using TSpdf.Commons.Utils;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("IntegrationTest")]
public class FreeReferencesTest : ExtendedTSpdfTest {
public static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/pdf/FreeReferencesTest/";
public static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/pdf/FreeReferencesTest/";
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
CreateOrClearDestinationFolder(destinationFolder);
}
[NUnit.Framework.Test]
public virtual void FreeReferencesTest01() {
String src = "freeRefsGapsAndMaxGen.pdf";
String @out = "freeReferencesTest01.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out));
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 15\n" + "0000000010 65535 f \n" + "0000000269 00000 n \n"
+ "0000000561 00000 n \n" + "0000000314 00000 n \n" + "0000000000 65535 f \n" + "0000000006 00000 f \n"
+ "0000000007 00000 f \n" + "0000000008 00000 f \n" + "0000000009 00000 f \n" + "0000000000 00000 f \n"
+ "0000000011 00000 f \n" + "0000000005 00001 f \n" + "0000000133 00000 n \n" + "0000000015 00000 n \n"
+ "0000000613 00000 n \n" };
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
public virtual void FreeReferencesTest02() {
String src = "freeRefsGapsAndMaxGen.pdf";
String @out = "freeReferencesTest02.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out), new StampingProperties().UseAppendMode());
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 5\n" + "0000000010 65535 f \n" + "0000000269 00000 n \n"
+ "0000000569 00000 n \n" + "0000000314 00000 n \n" + "0000000000 65535 f \n" + "10 5\n" + "0000000011 00000 f \n"
+
// Append mode, no possibility to fix subsections in first xref
"0000000000 00001 f \n" + "0000000133 00000 n \n" + "0000000015 00000 n \n" + "0000000480 00000 n \n", "xref\n"
+ "3 1\n" + "0000000995 00000 n \n" };
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
public virtual void FreeReferencesTest03() {
String src = "freeRefsDeletedObj.pdf";
String @out = "freeReferencesTest03.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out), new StampingProperties().UseAppendMode());
pdfDocument.AddNewPage();
// fix page content
PdfStream firstPageContentStream = pdfDocument.GetPage(1).GetContentStream(0);
String firstPageData = TSpdf.Commons.Utils.JavaUtil.GetStringForBytes(firstPageContentStream.GetBytes());
firstPageContentStream.SetData((firstPageData.JSubstring(0, firstPageData.LastIndexOf("BT")) + "ET").GetBytes
());
firstPageContentStream.SetModified();
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 7\n" + "0000000000 65535 f \n" + "0000000265 00000 n \n"
+ "0000000564 00000 n \n" + "0000000310 00000 n \n" + "0000000132 00000 n \n" + "0000000015 00001 n \n"
+ "0000000476 00000 n \n", "xref\n" + "0 1\n" + "0000000005 65535 f \n" + "3 3\n" + "0000000923 00000 n \n"
+ "0000001170 00000 n \n" + "0000000000 00002 f \n" + "7 1\n" + "0000001303 00000 n \n", "xref\n" + "1 3\n"
+ "0000001706 00000 n \n" + "0000001998 00000 n \n" + "0000001751 00000 n \n" + "7 3\n" + "0000002055 00000 n \n"
+ "0000002171 00000 n \n" + "0000002272 00000 n \n" };
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
public virtual void FreeReferencesTest04() {
String src = "simpleDoc.pdf";
String @out = "freeReferencesTest04.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out));
PdfObject contentsObj = pdfDocument.GetPage(1).GetPdfObject().Remove(PdfName.Contents);
NUnit.Framework.Assert.IsTrue(contentsObj is PdfIndirectReference);
PdfIndirectReference contentsRef = (PdfIndirectReference)contentsObj;
contentsRef.SetFree();
PdfObject freedContentsRefRefersTo = contentsRef.GetRefersTo();
NUnit.Framework.Assert.IsNull(freedContentsRefRefersTo);
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 7\n" + "0000000005 65535 f \n" + "0000000133 00000 n \n"
+ "0000000425 00000 n \n" + "0000000178 00000 n \n" + "0000000015 00000 n \n" + "0000000000 00001 f \n"
+ "0000000476 00000 n \n" };
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
public virtual void FreeReferencesTest05() {
String src = "simpleDocWithSubsections.pdf";
String @out = "freeReferencesTest05.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out));
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 14\n" + "0000000004 65535 f \n" + "0000000269 00000 n \n"
+ "0000000561 00000 n \n" + "0000000314 00000 n \n" + "0000000005 00000 f \n" + "0000000006 00000 f \n"
+ "0000000007 00000 f \n" + "0000000008 00000 f \n" + "0000000009 00000 f \n" + "0000000010 00000 f \n"
+ "0000000000 00000 f \n" + "0000000133 00000 n \n" + "0000000015 00000 n \n" + "0000000613 00000 n \n"
};
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
public virtual void FreeReferencesTest06() {
String src = "simpleDocWithSubsections.pdf";
String @out = "freeReferencesTest06.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out), new StampingProperties().UseAppendMode());
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 4\n" + "0000000000 65535 f \n" + "0000000269 00000 n \n"
+ "0000000569 00000 n \n" + "0000000314 00000 n \n" + "11 3\n" + "0000000133 00000 n \n" +
// Append mode, no possibility to fix subsections in first xref
"0000000015 00000 n \n" + "0000000480 00000 n \n", "xref\n" + "3 1\n" + "0000000935 00000 n \n" };
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
public virtual void FreeReferencesTest07() {
String @out = "freeReferencesTest07.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(destinationFolder + @out));
pdfDocument.CreateNextIndirectReference();
pdfDocument.AddNewPage();
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 7\n" + "0000000004 65535 f \n" + "0000000203 00000 n \n"
+ "0000000414 00000 n \n" + "0000000248 00000 n \n" + "0000000000 00001 f \n" + "0000000088 00000 n \n"
+ "0000000015 00000 n \n" };
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
public virtual void FreeReferencesTest08() {
String src = "simpleDoc.pdf";
String @out = "freeReferencesTest08.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out), new StampingProperties().UseAppendMode());
PdfObject contentsObj = pdfDocument.GetPage(1).GetPdfObject().Remove(PdfName.Contents);
pdfDocument.GetPage(1).SetModified();
NUnit.Framework.Assert.IsTrue(contentsObj is PdfIndirectReference);
PdfIndirectReference contentsRef = (PdfIndirectReference)contentsObj;
contentsRef.SetFree();
PdfObject freedContentsRefRefersTo = contentsRef.GetRefersTo();
NUnit.Framework.Assert.IsNull(freedContentsRefRefersTo);
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 7\n" + "0000000000 65535 f \n" + "0000000265 00000 n \n"
+ "0000000564 00000 n \n" + "0000000310 00000 n \n" + "0000000132 00000 n \n" + "0000000015 00000 n \n"
+ "0000000476 00000 n \n", "xref\n" + "0 1\n" + "0000000005 65535 f \n" + "3 3\n" + "0000000923 00000 n \n"
+ "0000001170 00000 n \n" + "0000000000 00001 f \n" };
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.ALREADY_FLUSHED_INDIRECT_OBJECT_MADE_FREE)]
public virtual void FreeARefInWrongWayTest01() {
String @out = "freeARefInWrongWayTest01.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(destinationFolder + @out));
pdfDocument.AddNewPage();
PdfDictionary catalogDict = pdfDocument.GetCatalog().GetPdfObject();
String outerString = "Outer array. Contains inner array at both 0 and 1 index. At 0 - as pdf object, at 1 - as in ref.";
String innerString = "Inner array.";
String description = "Inner array first flushed, then it's ref is made free.";
PdfArray a1 = (PdfArray)new PdfArray().MakeIndirect(pdfDocument);
PdfArray a2 = (PdfArray)new PdfArray().MakeIndirect(pdfDocument);
a1.Add(a2);
a1.Add(a2.GetIndirectReference());
a1.Add(new PdfString(outerString));
a1.Add(new PdfString(description));
a2.Add(new PdfString(innerString));
catalogDict.Put(new PdfName("TestArray"), a1);
a2.Flush();
a2.GetIndirectReference().SetFree();
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 8\n" + "0000000000 65535 f \n" + "0000000235 00000 n \n"
+ "0000000462 00000 n \n" + "0000000296 00000 n \n" + "0000000120 00000 n \n" + "0000000047 00000 n \n"
+ "0000000513 00000 n \n" + "0000000015 00000 n \n" };
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.FLUSHED_OBJECT_CONTAINS_FREE_REFERENCE, Count = 2)]
public virtual void FreeARefInWrongWayTest02() {
String @out = "freeARefInWrongWayTest02.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(destinationFolder + @out));
pdfDocument.AddNewPage();
PdfDictionary catalogDict = pdfDocument.GetCatalog().GetPdfObject();
String outerString = "Outer array. Contains inner array at both 0 and 1 index. At 0 - as pdf object, at 1 - as in ref.";
String innerString = "Inner array.";
String description = "Inner array ref made free, then outer array is flushed.";
PdfArray a1 = (PdfArray)new PdfArray().MakeIndirect(pdfDocument);
PdfArray a2 = (PdfArray)new PdfArray().MakeIndirect(pdfDocument);
a1.Add(a2);
a1.Add(a2.GetIndirectReference());
a1.Add(new PdfString(outerString));
a1.Add(new PdfString(description));
a2.Add(new PdfString(innerString));
catalogDict.Put(new PdfName("TestArray"), a1);
a2.GetIndirectReference().SetFree();
IList<PdfObject> objects = JavaUtil.ArraysAsList(new PdfObject[] { new PdfString("The answer to life is ")
, new PdfNumber(42) });
new PdfArray(objects).MakeIndirect(pdfDocument).Flush();
NUnit.Framework.Assert.IsTrue(a1.Get(1, false) is PdfIndirectReference);
NUnit.Framework.Assert.IsTrue(((PdfIndirectReference)a1.Get(1, false)).IsFree());
a1.Flush();
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 9\n" + "0000000007 65535 f \n" + "0000000432 00000 n \n"
+ "0000000659 00000 n \n" + "0000000493 00000 n \n" + "0000000317 00000 n \n" + "0000000244 00000 n \n"
+ "0000000060 00000 n \n" + "0000000000 00001 f \n" + "0000000015 00000 n \n" };
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.INDIRECT_REFERENCE_USED_IN_FLUSHED_OBJECT_MADE_FREE)]
public virtual void FreeARefInWrongWayTest03() {
String @out = "freeARefInWrongWayTest03.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(destinationFolder + @out));
pdfDocument.AddNewPage();
PdfDictionary catalogDict = pdfDocument.GetCatalog().GetPdfObject();
String outerString = "Outer array. Contains inner array at both 0 and 1 index. At 0 - as pdf object, at 1 - as in ref.";
String innerString = "Inner array.";
String description = "Outer array is flushed, then inner array ref made free.";
PdfArray a1 = (PdfArray)new PdfArray().MakeIndirect(pdfDocument);
PdfArray a2 = (PdfArray)new PdfArray().MakeIndirect(pdfDocument);
a1.Add(a2);
a1.Add(a2.GetIndirectReference());
a1.Add(new PdfString(outerString));
a1.Add(new PdfString(description));
a2.Add(new PdfString(innerString));
catalogDict.Put(new PdfName("TestArray"), a1);
a1.Flush();
a2.GetIndirectReference().SetFree();
NUnit.Framework.Assert.IsFalse(a2.GetIndirectReference().IsFree());
IList<PdfObject> objects = JavaUtil.ArraysAsList(new PdfObject[] { new PdfString("The answer to life is ")
, new PdfNumber(42) });
new PdfArray(objects).MakeIndirect(pdfDocument).Flush();
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 9\n" + "0000000000 65535 f \n" + "0000000431 00000 n \n"
+ "0000000658 00000 n \n" + "0000000492 00000 n \n" + "0000000316 00000 n \n" + "0000000243 00000 n \n"
+ "0000000015 00000 n \n" + "0000000709 00000 n \n" + "0000000201 00000 n \n" };
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.ALREADY_FLUSHED_INDIRECT_OBJECT_MADE_FREE)]
public virtual void FreeARefInWrongWayTest04() {
String @out = "freeARefInWrongWayTest04.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(destinationFolder + @out));
pdfDocument.AddNewPage();
PdfDictionary catalogDict = pdfDocument.GetCatalog().GetPdfObject();
String outerString = "Outer array. Contains inner array at both 0 and 1 index. At 0 - as pdf object, at 1 - as in ref.";
String innerString = "Inner array.";
String description = "Outer array is flushed, then inner array ref made free.";
PdfArray a1 = (PdfArray)new PdfArray().MakeIndirect(pdfDocument);
PdfArray a2 = (PdfArray)new PdfArray().MakeIndirect(pdfDocument);
a1.Add(a2);
a1.Add(a2.GetIndirectReference());
a1.Add(new PdfString(outerString));
a1.Add(new PdfString(description));
a2.Add(new PdfString(innerString));
catalogDict.Put(new PdfName("TestArray"), a1);
a1.Flush();
a2.Flush();
a2.GetIndirectReference().SetFree();
NUnit.Framework.Assert.IsFalse(a2.GetIndirectReference().IsFree());
IList<PdfObject> objects = JavaUtil.ArraysAsList(new PdfObject[] { new PdfString("The answer to life is ")
, new PdfNumber(42) });
new PdfArray(objects).MakeIndirect(pdfDocument).Flush();
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 9\n" + "0000000000 65535 f \n" + "0000000431 00000 n \n"
+ "0000000658 00000 n \n" + "0000000492 00000 n \n" + "0000000316 00000 n \n" + "0000000243 00000 n \n"
+ "0000000015 00000 n \n" + "0000000709 00000 n \n" + "0000000201 00000 n \n" };
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
public virtual void FreeRefsAtEndOfXref01() {
String @out = "freeRefsAtEndOfXref01.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(destinationFolder + @out));
pdfDocument.AddNewPage();
PdfDictionary catalogDict = pdfDocument.GetCatalog().GetPdfObject();
String outerString = "Outer array. Contains inner array at both 0 and 1 index. At 0 - as pdf object, at 1 - as ind ref.";
String innerString = "Inner array.";
String description = "Last entry in the document xref table is free";
PdfArray a1 = (PdfArray)new PdfArray().MakeIndirect(pdfDocument);
PdfArray a2 = (PdfArray)new PdfArray().MakeIndirect(pdfDocument);
a1.Add(a2);
a1.Add(a2.GetIndirectReference());
a1.Add(new PdfString(outerString));
a1.Add(new PdfString(description));
a2.Add(new PdfString(innerString));
catalogDict.Put(new PdfName("TestArray"), a1);
new PdfArray().MakeIndirect(pdfDocument).GetIndirectReference().SetFree();
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 8\n" + "0000000000 65535 f \n" + "0000000203 00000 n \n"
+ "0000000430 00000 n \n" + "0000000264 00000 n \n" + "0000000088 00000 n \n" + "0000000015 00000 n \n"
+ "0000000481 00000 n \n" + "0000000658 00000 n \n" };
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
public virtual void FreeRefsAtEndOfXref02() {
String src = "lastXrefEntryFree.pdf";
String @out = "freeRefsAtEndOfXref02.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out));
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 8\n" + "0000000000 65535 f \n" + "0000000203 00000 n \n"
+ "0000000511 00000 n \n" + "0000000264 00000 n \n" + "0000000088 00000 n \n" + "0000000015 00000 n \n"
+ "0000000562 00000 n \n" + "0000000739 00000 n \n" };
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
public virtual void FreeRefsAtEndOfXref03() {
String src = "lastXrefEntryFree.pdf";
String @out = "freeRefsAtEndOfXref03.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out));
new PdfArray().MakeIndirect(pdfDocument).GetIndirectReference().SetFree();
IList<PdfObject> objects = JavaUtil.ArraysAsList(new PdfObject[] { new PdfString("The answer to life is ")
, new PdfNumber(42) });
new PdfArray(objects).MakeIndirect(pdfDocument).Flush();
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 11\n" + "0000000008 65535 f \n" + "0000000246 00000 n \n"
+ "0000000554 00000 n \n" + "0000000307 00000 n \n" + "0000000131 00000 n \n" + "0000000058 00000 n \n"
+ "0000000605 00000 n \n" + "0000000782 00000 n \n" + "0000000009 00001 f \n" + "0000000000 00001 f \n"
+ "0000000015 00000 n \n" };
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
public virtual void FreeRefsAtEndOfXref04() {
String src = "lastXrefEntryFree.pdf";
String @out = "freeRefsAtEndOfXref04.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out), new StampingProperties().UseAppendMode());
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 9\n" + "0000000008 65535 f \n" + "0000000203 00000 n \n"
+ "0000000430 00000 n \n" + "0000000264 00000 n \n" + "0000000088 00000 n \n" + "0000000015 00000 n \n"
+ "0000000481 00000 n \n" + "0000000658 00000 n \n" + "0000000000 00001 f \n", "xref\n" + "3 1\n" + "0000001038 00000 n \n"
};
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
public virtual void FreeRefsAtEndOfXref05() {
String src = "lastXrefEntryFree.pdf";
String @out = "freeRefsAtEndOfXref05.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out), new StampingProperties().UseAppendMode());
new PdfArray().MakeIndirect(pdfDocument).GetIndirectReference().SetFree();
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 9\n" + "0000000008 65535 f \n" + "0000000203 00000 n \n"
+ "0000000430 00000 n \n" + "0000000264 00000 n \n" + "0000000088 00000 n \n" + "0000000015 00000 n \n"
+ "0000000481 00000 n \n" + "0000000658 00000 n \n" + "0000000000 00001 f \n", "xref\n" + "3 1\n" + "0000001038 00000 n \n"
+ "8 2\n" + "0000000009 00001 f \n" + "0000000000 00001 f \n" };
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
public virtual void FreeRefsAtEndOfXref06() {
String src = "lastXrefEntryFree.pdf";
String @out = "freeRefsAtEndOfXref06.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out), new StampingProperties().UseAppendMode());
new PdfArray().MakeIndirect(pdfDocument).GetIndirectReference().SetFree();
IList<PdfObject> objects = JavaUtil.ArraysAsList(new PdfObject[] { new PdfString("The answer to life is ")
, new PdfNumber(42) });
new PdfArray(objects).MakeIndirect(pdfDocument).Flush();
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 9\n" + "0000000008 65535 f \n" + "0000000203 00000 n \n"
+ "0000000430 00000 n \n" + "0000000264 00000 n \n" + "0000000088 00000 n \n" + "0000000015 00000 n \n"
+ "0000000481 00000 n \n" + "0000000658 00000 n \n" + "0000000000 00001 f \n", "xref\n" + "3 1\n" + "0000001081 00000 n \n"
+ "8 3\n" + "0000000009 00001 f \n" + "0000000000 00001 f \n" + "0000001038 00000 n \n" };
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
public virtual void NotUsedIndRef01() {
String src = "freeRefsDeletedObj.pdf";
String @out = "notUsedIndRef01.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out));
pdfDocument.SetFlushUnusedObjects(true);
PdfIndirectReference newIndRef1 = pdfDocument.CreateNextIndirectReference();
PdfIndirectReference newIndRef2 = pdfDocument.CreateNextIndirectReference();
IList<PdfObject> objects = JavaUtil.ArraysAsList(new PdfObject[] { new PdfString("The answer to life is ")
, new PdfNumber(42) });
new PdfArray(objects).MakeIndirect(pdfDocument).Flush();
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 11\n" + "0000000005 65535 f \n" + "0000000308 00000 n \n"
+ "0000000600 00000 n \n" + "0000000353 00000 n \n" + "0000000175 00000 n \n" + "0000000008 00002 f \n"
+ "0000000651 00000 n \n" + "0000000058 00000 n \n" + "0000000009 00001 f \n" + "0000000000 00001 f \n"
+ "0000000015 00000 n \n" };
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
public virtual void NotUsedIndRef02() {
String src = "freeRefsDeletedObj.pdf";
String @out = "notUsedIndRef02.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out));
pdfDocument.SetFlushUnusedObjects(false);
PdfIndirectReference newIndRef1 = pdfDocument.CreateNextIndirectReference();
PdfIndirectReference newIndRef2 = pdfDocument.CreateNextIndirectReference();
IList<PdfObject> objects = JavaUtil.ArraysAsList(new PdfObject[] { new PdfString("The answer to life is ")
, new PdfNumber(42) });
new PdfArray(objects).MakeIndirect(pdfDocument).Flush();
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 11\n" + "0000000005 65535 f \n" + "0000000308 00000 n \n"
+ "0000000600 00000 n \n" + "0000000353 00000 n \n" + "0000000175 00000 n \n" + "0000000008 00002 f \n"
+ "0000000651 00000 n \n" + "0000000058 00000 n \n" + "0000000009 00001 f \n" + "0000000000 00001 f \n"
+ "0000000015 00000 n \n" };
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
public virtual void NotUsedIndRef03() {
String src = "freeRefsDeletedObj.pdf";
String @out = "notUsedIndRef03.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out), new StampingProperties().UseAppendMode());
PdfIndirectReference newIndRef1 = pdfDocument.CreateNextIndirectReference();
PdfIndirectReference newIndRef2 = pdfDocument.CreateNextIndirectReference();
IList<PdfObject> objects = JavaUtil.ArraysAsList(new PdfObject[] { new PdfString("The answer to life is ")
, new PdfNumber(42) });
new PdfArray(objects).MakeIndirect(pdfDocument).Flush();
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 7\n" + "0000000000 65535 f \n" + "0000000265 00000 n \n"
+ "0000000564 00000 n \n" + "0000000310 00000 n \n" + "0000000132 00000 n \n" + "0000000015 00001 n \n"
+ "0000000476 00000 n \n", "xref\n" + "0 1\n" + "0000000005 65535 f \n" + "3 3\n" + "0000000923 00000 n \n"
+ "0000001170 00000 n \n" + "0000000000 00002 f \n" + "7 1\n" + "0000001303 00000 n \n", "xref\n" + "3 1\n"
+ "0000001749 00000 n \n" + "5 1\n" + "0000000008 00002 f \n" + "8 3\n" + "0000000009 00001 f \n" + "0000000000 00001 f \n"
+ "0000001706 00000 n \n" };
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.INVALID_INDIRECT_REFERENCE)]
public virtual void CorruptedDocIndRefToFree01() {
String src = "corruptedDocIndRefToFree.pdf";
String @out = "corruptedDocIndRefToFree01.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out));
pdfDocument.Close();
pdfDocument = new PdfDocument(new PdfReader(destinationFolder + @out));
PdfObject contentsObj = pdfDocument.GetPage(1).GetPdfObject().Get(PdfName.Contents);
NUnit.Framework.Assert.AreEqual(PdfNull.PDF_NULL, contentsObj);
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 7\n" + "0000000005 65535 f \n" + "0000000147 00000 n \n"
+ "0000000439 00000 n \n" + "0000000192 00000 n \n" + "0000000015 00000 n \n" + "0000000000 00001 f \n"
+ "0000000490 00000 n \n" };
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
public virtual void InvalidFreeRefsListHandling01() {
String src = "invalidFreeRefsList01.pdf";
String @out = "invalidFreeRefsListHandling01.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out));
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 15\n" + "0000000010 65535 f \n" + "0000000269 00000 n \n"
+ "0000000561 00000 n \n" + "0000000314 00000 n \n" + "0000000000 65535 f \n" + "0000000006 00000 f \n"
+ "0000000007 00000 f \n" + "0000000008 00000 f \n" + "0000000009 00000 f \n" + "0000000011 00000 f \n"
+ "0000000005 00000 f \n" + "0000000000 00001 f \n" + "0000000133 00000 n \n" + "0000000015 00000 n \n"
+ "0000000613 00000 n \n" };
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
public virtual void InvalidFreeRefsListHandling02() {
String src = "invalidFreeRefsList02.pdf";
String @out = "invalidFreeRefsListHandling02.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out));
pdfDocument.SetFlushUnusedObjects(true);
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 18\n" + "0000000010 65535 f \n" + "0000000269 00000 n \n"
+ "0000000561 00000 n \n" + "0000000314 00000 n \n" + "0000000000 65535 f \n" + "0000000006 00000 f \n"
+ "0000000007 00000 f \n" + "0000000008 00000 f \n" + "0000000009 00000 f \n" + "0000000015 00000 f \n"
+ "0000000011 00000 f \n" + "0000000005 00001 f \n" + "0000000133 00000 n \n" + "0000000015 00000 n \n"
+ "0000000613 00000 n \n" + "0000000016 00001 f \n" + "0000000000 00001 f \n" + "0000000702 00000 n \n"
};
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
public virtual void InvalidFreeRefsListHandling03() {
String src = "invalidFreeRefsList03.pdf";
String @out = "invalidFreeRefsListHandling03.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out));
pdfDocument.SetFlushUnusedObjects(true);
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 18\n" + "0000000010 65535 f \n" + "0000000269 00000 n \n"
+ "0000000561 00000 n \n" + "0000000314 00000 n \n" + "0000000000 65535 f \n" + "0000000006 00000 f \n"
+ "0000000007 00000 f \n" + "0000000008 00000 f \n" + "0000000009 00000 f \n" + "0000000015 00000 f \n"
+ "0000000011 00000 f \n" + "0000000005 00001 f \n" + "0000000133 00000 n \n" + "0000000015 00000 n \n"
+ "0000000613 00000 n \n" + "0000000016 00001 f \n" + "0000000000 00001 f \n" + "0000000702 00000 n \n"
};
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
public virtual void InvalidFreeRefsListHandling04() {
String src = "invalidFreeRefsList04.pdf";
String @out = "invalidFreeRefsListHandling04.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out));
pdfDocument.SetFlushUnusedObjects(true);
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 18\n" + "0000000010 65535 f \n" + "0000000269 00000 n \n"
+ "0000000561 00000 n \n" + "0000000314 00000 n \n" + "0000000006 65535 f \n" + "0000000004 00000 f \n"
+ "0000000007 00000 f \n" + "0000000008 00000 f \n" + "0000000009 00000 f \n" + "0000000015 00000 f \n"
+ "0000000011 00000 f \n" + "0000000005 00001 f \n" + "0000000133 00000 n \n" + "0000000015 00000 n \n"
+ "0000000613 00000 n \n" + "0000000016 00001 f \n" + "0000000000 00001 f \n" + "0000000702 00000 n \n"
};
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
public virtual void InvalidFreeRefsListHandling05() {
String src = "invalidFreeRefsList05.pdf";
String @out = "invalidFreeRefsListHandling05.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out));
pdfDocument.SetFlushUnusedObjects(true);
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 18\n" + "0000000005 65535 f \n" + "0000000269 00000 n \n"
+ "0000000561 00000 n \n" + "0000000314 00000 n \n" + "0000000000 65535 f \n" + "0000000006 00000 f \n"
+ "0000000007 00000 f \n" + "0000000008 00000 f \n" + "0000000009 00000 f \n" + "0000000010 00000 f \n"
+ "0000000011 00000 f \n" + "0000000015 00001 f \n" + "0000000133 00000 n \n" + "0000000015 00000 n \n"
+ "0000000613 00000 n \n" + "0000000016 00001 f \n" + "0000000000 00001 f \n" + "0000000702 00000 n \n"
};
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
public virtual void InvalidFreeRefsListHandling06() {
String src = "invalidFreeRefsList06.pdf";
String @out = "invalidFreeRefsListHandling06.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out));
pdfDocument.SetFlushUnusedObjects(true);
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 18\n" + "0000000010 65535 f \n" + "0000000269 00000 n \n"
+ "0000000561 00000 n \n" + "0000000314 00000 n \n" + "0000000000 65535 f \n" + "0000000006 00000 f \n"
+ "0000000007 00000 f \n" + "0000000008 00000 f \n" + "0000000009 00000 f \n" + "0000000015 00000 f \n"
+ "0000000011 00000 f \n" + "0000000005 00001 f \n" + "0000000133 00000 n \n" + "0000000015 00000 n \n"
+ "0000000613 00000 n \n" + "0000000016 00001 f \n" + "0000000000 00001 f \n" + "0000000702 00000 n \n"
};
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
public virtual void InvalidFreeRefsListHandling07() {
String src = "invalidFreeRefsList07.pdf";
String @out = "invalidFreeRefsListHandling07.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out));
pdfDocument.SetFlushUnusedObjects(true);
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 18\n" + "0000000010 65535 f \n" + "0000000269 00000 n \n"
+ "0000000561 00000 n \n" + "0000000314 00000 n \n" + "0000000000 65535 f \n" + "0000000006 00000 f \n"
+ "0000000007 00000 f \n" + "0000000008 00000 f \n" + "0000000009 00000 f \n" + "0000000015 00000 f \n"
+ "0000000011 00000 f \n" + "0000000005 00001 f \n" + "0000000133 00000 n \n" + "0000000015 00000 n \n"
+ "0000000613 00000 n \n" + "0000000016 00001 f \n" + "0000000004 00001 f \n" + "0000000702 00000 n \n"
};
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
public virtual void InvalidFreeRefsListHandling08() {
String src = "invalidFreeRefsList08.pdf";
String @out = "invalidFreeRefsListHandling08.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out), new StampingProperties().UseAppendMode());
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 18\n" + "0000000010 65535 f \n" + "0000000315 00000 n \n"
+ "0000000607 00000 n \n" + "0000000360 00000 n \n" + "0000000000 65535 f \n" + "0000000006 00000 f \n"
+ "0000000007 00000 f \n" + "0000000008 00000 f \n" + "0000000009 00000 f \n" + "0000000015 00000 f \n"
+ "0000000011 00000 f \n" + "0000000005 00001 f \n" + "0000000179 00000 n \n" + "0000000061 00000 n \n"
+ "0000000659 00000 n \n" + "0000000016 00001 f \n" + "0000000002 00001 f \n" + "0000000015 00000 n \n"
, "xref\n" + "3 1\n" + "0000001278 00000 n \n" + "16 1\n" + "0000000000 00001 f \n" };
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
public virtual void InvalidFreeRefsListHandling09() {
String src = "invalidFreeRefsList09.pdf";
String @out = "invalidFreeRefsListHandling09.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out), new StampingProperties().UseAppendMode());
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 18\n" + "0000000010 65535 f \n" + "0000000315 00000 n \n"
+ "0000000607 00000 n \n" + "0000000360 00000 n \n" + "0009999999 65535 f \n" + "0000000006 00000 f \n"
+ "0000000007 00000 f \n" + "0000000008 00000 f \n" + "0000000009 00000 f \n" + "0000000015 00000 f \n"
+ "0000000011 00000 f \n" + "0000000005 00001 f \n" + "0000000179 00000 n \n" + "0000000061 00000 n \n"
+ "0000000659 00000 n \n" + "0000999999 00001 f \n" + "0000000000 00001 f \n" + "0000000015 00000 n \n"
, "xref\n" + "3 2\n" + "0000001278 00000 n \n" + "0000000016 65535 f \n" + "15 1\n" + "0000000004 00001 f \n"
};
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
public virtual void InvalidFreeRefsListHandling10() {
String src = "invalidFreeRefsList10.pdf";
String @out = "invalidFreeRefsListHandling10.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out), new StampingProperties().UseAppendMode());
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 18\n" + "0000000010 65535 f \n" + "0000000315 00000 n \n"
+ "0000000607 00000 n \n" + "0000000360 00000 n \n" + "0000000000 65535 f \n" + "0000000006 00000 f \n"
+ "0000000002 00000 f \n" + "0000000016 00000 f \n" + "0000000009 00000 f \n" + "0000000015 00000 f \n"
+ "0000000011 00000 f \n" + "0000000005 00001 f \n" + "0000000179 00000 n \n" + "0000000061 00000 n \n"
+ "0000000659 00000 n \n" + "0000000016 00001 f \n" + "0000000008 00001 f \n" + "0000000015 00000 n \n"
, "xref\n" + "3 1\n" + "0000001278 00000 n \n" + "6 2\n" + "0000000007 00000 f \n" + "0000000008 00000 f \n"
+ "16 1\n" + "0000000000 00001 f \n" };
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
public virtual void FreeRefsXrefStream01() {
String src = "freeRefsGapsAndListSpecificOrder.pdf";
String out1 = "freeRefsXrefStream01_xrefStream.pdf";
String out2 = "freeRefsXrefStream01.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ out1, new WriterProperties().SetFullCompressionMode(true)));
pdfDocument.Close();
pdfDocument = new PdfDocument(new PdfReader(destinationFolder + out1), new PdfWriter(destinationFolder + out2
, new WriterProperties().SetFullCompressionMode(false)));
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(out2);
String[] expected = new String[] { "xref\n" + "0 15\n" + "0000000011 65535 f \n" + "0000000269 00000 n \n"
+ "0000000561 00000 n \n" + "0000000314 00000 n \n" + "0000000000 65535 f \n" + "0000000006 00000 f \n"
+ "0000000007 00000 f \n" + "0000000008 00000 f \n" + "0000000009 00000 f \n" + "0000000000 00000 f \n"
+ "0000000005 00000 f \n" + "0000000010 00001 f \n" + "0000000133 00000 n \n" + "0000000015 00000 n \n"
+ "0000000613 00000 n \n" };
CompareXrefTables(xrefString, expected);
}
/// <summary>
/// Free refs reusing is disabled at the moment, however it might be valuable to keep an eye on such case,
/// in case something will change.
/// </summary>
[NUnit.Framework.Test]
public virtual void FreeRefsReusingTest01() {
String src = "simpleDoc.pdf";
String @out = "freeRefsReusingTest01.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out));
PdfString s = new PdfString("New indirect object in the document.");
PdfArray newIndObj = (PdfArray)new PdfArray(JavaCollectionsUtil.SingletonList<PdfObject>(s)).MakeIndirect(
pdfDocument);
pdfDocument.GetCatalog().Put(new PdfName("TestKey"), newIndObj);
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 8\n" + "0000000000 65535 f \n" + "0000000265 00000 n \n"
+ "0000000571 00000 n \n" + "0000000324 00000 n \n" + "0000000132 00000 n \n" + "0000000015 00000 n \n"
+ "0000000622 00000 n \n" + "0000000710 00000 n \n" };
CompareXrefTables(xrefString, expected);
}
/// <summary>
/// Free refs reusing is disabled at the moment, however it might be valuable to keep an eye on such case,
/// in case something will change.
/// </summary>
[NUnit.Framework.Test]
public virtual void FreeRefsReusingTest02() {
String src = "simpleDocWithSubsections.pdf";
String @out = "freeRefsReusingTest02.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out));
PdfString s = new PdfString("New indirect object in the document.");
PdfArray newIndObj = (PdfArray)new PdfArray(JavaCollectionsUtil.SingletonList<PdfObject>(s)).MakeIndirect(
pdfDocument);
pdfDocument.GetCatalog().Put(new PdfName("TestKey"), newIndObj);
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 15\n" + "0000000004 65535 f \n" + "0000000269 00000 n \n"
+ "0000000576 00000 n \n" + "0000000329 00000 n \n" + "0000000005 00000 f \n" + "0000000006 00000 f \n"
+ "0000000007 00000 f \n" + "0000000008 00000 f \n" + "0000000009 00000 f \n" + "0000000010 00000 f \n"
+ "0000000000 00000 f \n" + "0000000133 00000 n \n" + "0000000015 00000 n \n" + "0000000628 00000 n \n"
+ "0000000717 00000 n \n" };
CompareXrefTables(xrefString, expected);
}
/// <summary>
/// Free refs reusing is disabled at the moment, however it might be valuable to keep an eye on such case,
/// in case something will change.
/// </summary>
[NUnit.Framework.Test]
public virtual void FreeRefsReusingTest03() {
String src = "simpleDocWithFreeList.pdf";
String @out = "freeRefsReusingTest03.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out));
PdfString s = new PdfString("New indirect object in the document.");
PdfArray newIndObj = (PdfArray)new PdfArray(JavaCollectionsUtil.SingletonList<PdfObject>(s)).MakeIndirect(
pdfDocument);
pdfDocument.GetCatalog().Put(new PdfName("TestKey"), newIndObj);
pdfDocument.GetCatalog().Put(new PdfName("TestKey2"), pdfDocument.GetPdfObject(10));
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 12\n" + "0000000009 65535 f \n" + "0000000265 00000 n \n"
+ "0000000588 00000 n \n" + "0000000341 00000 n \n" + "0000000132 00000 n \n" + "0000000000 00002 f \n"
+ "0000000639 00000 n \n" + "0000000015 00000 n \n" + "0000000005 00001 f \n" + "0000000008 00001 f \n"
+ "0000000727 00000 n \n" + "0000000773 00000 n \n" };
CompareXrefTables(xrefString, expected);
}
/// <summary>
/// Free refs reusing is disabled at the moment, however it might be valuable to keep an eye on such cases,
/// if something will change in future.
/// </summary>
[NUnit.Framework.Test]
public virtual void FreeRefsReusingTest04() {
String src = "freeRefsMaxGenOnly.pdf";
String @out = "freeRefsReusingTest04.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out));
PdfString s = new PdfString("New indirect object in the document.");
PdfArray newIndObj = (PdfArray)new PdfArray(JavaCollectionsUtil.SingletonList<PdfObject>(s)).MakeIndirect(
pdfDocument);
pdfDocument.GetCatalog().Put(new PdfName("TestKey"), newIndObj);
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 8\n" + "0000000005 65535 f \n" + "0000000133 00000 n \n"
+ "0000000439 00000 n \n" + "0000000192 00000 n \n" + "0000000015 00000 n \n" + "0000000000 65535 f \n"
+ "0000000490 00000 n \n" + "0000000578 00000 n \n" };
CompareXrefTables(xrefString, expected);
}
/// <summary>
/// Free refs reusing is disabled at the moment, however it might be valuable to keep an eye on such case,
/// in case something will change.
/// </summary>
[NUnit.Framework.Test]
public virtual void FreeRefsReusingTest05() {
String src = "simpleDocWithFreeList.pdf";
String @out = "freeRefsReusingTest05.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out));
PdfString s = new PdfString("New indirect object in the document.");
PdfArray newIndObj = (PdfArray)new PdfArray(JavaCollectionsUtil.SingletonList<PdfObject>(s)).MakeIndirect(
pdfDocument);
newIndObj.GetIndirectReference().SetFree();
pdfDocument.GetCatalog().Put(new PdfName("TestKey"), pdfDocument.GetPdfObject(10));
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 11\n" + "0000000009 65535 f \n" + "0000000265 00000 n \n"
+ "0000000572 00000 n \n" + "0000000325 00000 n \n" + "0000000132 00000 n \n" + "0000000000 00002 f \n"
+ "0000000623 00000 n \n" + "0000000015 00000 n \n" + "0000000005 00001 f \n" + "0000000008 00001 f \n"
+ "0000000711 00000 n \n" };
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
public virtual void FreeRefsReusingTest06() {
String src = "simpleDoc.pdf";
String @out = "freeRefsReusingTest06.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + src), new PdfWriter(destinationFolder
+ @out));
PdfObject contentsObj = pdfDocument.GetPage(1).GetPdfObject().Remove(PdfName.Contents);
NUnit.Framework.Assert.IsTrue(contentsObj is PdfIndirectReference);
PdfIndirectReference contentsRef = (PdfIndirectReference)contentsObj;
contentsRef.SetFree();
PdfString s = new PdfString("New indirect object in the document.");
PdfArray newIndObj = (PdfArray)new PdfArray(JavaCollectionsUtil.SingletonList<PdfObject>(s)).MakeIndirect(
pdfDocument);
pdfDocument.GetCatalog().Put(new PdfName("TestKey"), newIndObj);
pdfDocument.Close();
String[] xrefString = ExtractXrefTableAsStrings(@out);
String[] expected = new String[] { "xref\n" + "0 8\n" + "0000000005 65535 f \n" + "0000000133 00000 n \n"
+ "0000000439 00000 n \n" + "0000000192 00000 n \n" + "0000000015 00000 n \n" + "0000000000 00001 f \n"
+ "0000000490 00000 n \n" + "0000000578 00000 n \n" };
CompareXrefTables(xrefString, expected);
}
[NUnit.Framework.Test]
public virtual void ReadingXrefWithLotsOfFreeObjTest() {
String input = sourceFolder + "readingXrefWithLotsOfFreeObj.pdf";
String output = destinationFolder + "result_readingXrefWithLotsOfFreeObj.pdf";
//Test for array out of bounds when a pdf contains multiple free references
PdfDocument doc = new PdfDocument(new PdfReader(input), new PdfWriter(output));
int actualNumberOfObj = doc.GetNumberOfPdfObjects();
NUnit.Framework.Assert.AreEqual(68, actualNumberOfObj);
NUnit.Framework.Assert.IsNull(doc.GetPdfObject(7));
PdfXrefTable xref = doc.GetXref();
int freeRefsCount = 0;
for (int i = 0; i < xref.Size(); i++) {
if (xref.Get(i).IsFree()) {
freeRefsCount = freeRefsCount + 1;
}
}
NUnit.Framework.Assert.AreEqual(31, freeRefsCount);
doc.Close();
}
private void CompareXrefTables(String[] xrefString, String[] expected) {
NUnit.Framework.Assert.AreEqual(expected.Length, xrefString.Length);
for (int i = 0; i < xrefString.Length; ++i) {
if (!CompareXrefSection(xrefString[i], expected[i])) {
// XrefTables are different. Use Assert method in order to show differences gracefully.
NUnit.Framework.Assert.AreEqual(expected, xrefString);
}
}
}
private bool CompareXrefSection(String xrefSection, String expectedSection) {
String[] xrefEntries = TSpdf.Commons.Utils.StringUtil.Split(xrefSection, "\n");
String[] expectedEntries = TSpdf.Commons.Utils.StringUtil.Split(expectedSection, "\n");
if (xrefEntries.Length != expectedEntries.Length) {
return false;
}
for (int i = 0; i < xrefEntries.Length; ++i) {
String actual = xrefEntries[i].Trim();
String expected = expectedEntries[i].Trim();
if (actual.EndsWith("n")) {
actual = actual.Substring(10);
expected = expected.Substring(10);
}
if (!actual.Equals(expected)) {
return false;
}
}
return true;
}
private String[] ExtractXrefTableAsStrings(String @out) {
byte[] outPdfBytes = ReadFile(destinationFolder + @out);
String outPdfContent = TSpdf.Commons.Utils.JavaUtil.GetStringForBytes(outPdfBytes, System.Text.Encoding.ASCII
);
String xrefStr = "\nxref";
String trailerStr = "trailer";
int xrefInd = outPdfContent.IndexOf(xrefStr, StringComparison.Ordinal);
int trailerInd = outPdfContent.IndexOf(trailerStr, StringComparison.Ordinal);
int lastXrefInd = outPdfContent.LastIndexOf(xrefStr);
IList<String> xrefs = new List<String>();
while (true) {
xrefs.Add(outPdfContent.JSubstring(xrefInd + 1, trailerInd));
if (xrefInd == lastXrefInd) {
break;
}
xrefInd = outPdfContent.IndexOf(xrefStr, xrefInd + 1);
trailerInd = outPdfContent.IndexOf(trailerStr, trailerInd + 1);
}
return xrefs.ToArray(new String[xrefs.Count]);
}
}
}

View File

@@ -0,0 +1,152 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using TSpdf.IO.Font.Constants;
using TSpdf.IO.Image;
using TSpdf.Kernel.Colors;
using TSpdf.Kernel.Font;
using TSpdf.Kernel.Geom;
using TSpdf.Kernel.Pdf.Canvas;
using TSpdf.Kernel.Utils;
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("IntegrationTest")]
public class ImageFormatsTest : ExtendedTSpdfTest {
public static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/pdf/ImageFormatsTest/";
public static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/pdf/ImageFormatsTest/";
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
CreateOrClearDestinationFolder(destinationFolder);
}
[NUnit.Framework.Test]
public virtual void ImagesWithDifferentDepth() {
String outFileName = destinationFolder + "transparencyTest01.pdf";
String cmpFileName = sourceFolder + "cmp_transparencyTest01.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName, new WriterProperties().SetCompressionLevel
(CompressionConstants.NO_COMPRESSION)));
PdfPage page = pdfDocument.AddNewPage(PageSize.A3);
PdfCanvas canvas = new PdfCanvas(page);
canvas.SetFillColor(ColorConstants.LIGHT_GRAY).Fill();
canvas.Rectangle(80, 0, 700, 1200).Fill();
canvas.SaveState().BeginText().MoveText(116, 1150).SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.
HELVETICA), 14).SetFillColor(ColorConstants.MAGENTA).ShowText("8 bit depth PNG").EndText().RestoreState
();
ImageData img = ImageDataFactory.Create(sourceFolder + "manualTransparency_8bit.png");
canvas.AddImageFittedIntoRectangle(img, new Rectangle(100, 780, 200, 292.59f), false);
canvas.SaveState().BeginText().MoveText(316, 1150).SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.
HELVETICA), 14).SetFillColor(ColorConstants.MAGENTA).ShowText("24 bit depth PNG").EndText().RestoreState
();
img = ImageDataFactory.Create(sourceFolder + "manualTransparency_24bit.png");
canvas.AddImageFittedIntoRectangle(img, new Rectangle(300, 780, 200, 292.59f), false);
canvas.SaveState().BeginText().MoveText(516, 1150).SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.
HELVETICA), 14).SetFillColor(ColorConstants.MAGENTA).ShowText("32 bit depth PNG").EndText().RestoreState
();
img = ImageDataFactory.Create(sourceFolder + "manualTransparency_32bit.png");
canvas.AddImageFittedIntoRectangle(img, new Rectangle(500, 780, 200, 292.59f), false);
canvas.SaveState().BeginText().MoveText(116, 650).SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.HELVETICA
), 16).SetFillColor(ColorConstants.MAGENTA).ShowText("GIF image ").EndText().RestoreState();
img = ImageDataFactory.Create(sourceFolder + "manualTransparency_gif.gif");
canvas.AddImageFittedIntoRectangle(img, new Rectangle(100, 300, 200, 292.59f), false);
canvas.SaveState().BeginText().MoveText(316, 650).SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.HELVETICA
), 16).SetFillColor(ColorConstants.MAGENTA).ShowText("TIF image ").EndText().RestoreState();
img = ImageDataFactory.Create(sourceFolder + "manualTransparency_tif.tif");
canvas.AddImageFittedIntoRectangle(img, new Rectangle(300, 300, 200, 292.59f), false);
canvas.Release();
pdfDocument.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder
, "diff_"));
}
[NUnit.Framework.Test]
public virtual void Png_imageTransparency_8bitDepthImage() {
String outFileName = destinationFolder + "png_imageTransparancy_8bitDepthImage.pdf";
String cmpFileName = sourceFolder + "cmp_png_imageTransparancy_8bitDepthImage.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName, new WriterProperties().SetCompressionLevel
(CompressionConstants.NO_COMPRESSION)));
PdfPage page = pdfDocument.AddNewPage(PageSize.A4);
PdfCanvas canvas = new PdfCanvas(page);
canvas.SetFillColor(ColorConstants.LIGHT_GRAY).Fill();
canvas.Rectangle(80, 0, PageSize.A4.GetWidth() - 80, PageSize.A4.GetHeight()).Fill();
canvas.SaveState().BeginText().MoveText(116, 800).SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.HELVETICA
), 14).SetFillColor(ColorConstants.MAGENTA).ShowText("8 bit depth PNG").MoveText(0, -20).ShowText("This image should not have a black rectangle as background"
).EndText().RestoreState();
ImageData img = ImageDataFactory.Create(sourceFolder + "manualTransparency_8bit.png");
canvas.AddImageFittedIntoRectangle(img, new Rectangle(100, 450, 200, 292.59f), false);
canvas.Release();
pdfDocument.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder
, "diff_"));
}
[NUnit.Framework.Test]
public virtual void Png_imageTransparency_24bitDepthImage() {
String outFileName = destinationFolder + "png_imageTransparancy_24bitDepthImage.pdf";
String cmpFileName = sourceFolder + "cmp_png_imageTransparancy_24bitDepthImage.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName, new WriterProperties().SetCompressionLevel
(CompressionConstants.NO_COMPRESSION)));
PdfPage page = pdfDocument.AddNewPage(PageSize.A4);
PdfCanvas canvas = new PdfCanvas(page);
canvas.SetFillColor(ColorConstants.LIGHT_GRAY).Fill();
canvas.Rectangle(80, 0, PageSize.A4.GetWidth() - 80, PageSize.A4.GetHeight()).Fill();
canvas.SaveState().BeginText().MoveText(116, 800).SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.HELVETICA
), 14).SetFillColor(ColorConstants.MAGENTA).ShowText("24 bit depth PNG").MoveText(0, -20).ShowText("This image should not have a white rectangle as background"
).EndText().RestoreState();
ImageData img = ImageDataFactory.Create(sourceFolder + "manualTransparency_24bit.png");
canvas.AddImageFittedIntoRectangle(img, new Rectangle(100, 450, 200, 292.59f), false);
canvas.SaveState().BeginText().MoveText(116, 400).SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.HELVETICA
), 14).SetFillColor(ColorConstants.MAGENTA).ShowText("32 bit depth PNG").EndText().RestoreState();
img = ImageDataFactory.Create(sourceFolder + "manualTransparency_32bit.png");
canvas.AddImageFittedIntoRectangle(img, new Rectangle(116, 100, 200, 292.59f), false);
canvas.Release();
pdfDocument.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder
, "diff_"));
}
}
}

View File

@@ -0,0 +1,119 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.IO.Font.Constants;
using TSpdf.Kernel.Font;
using TSpdf.Kernel.Geom;
using TSpdf.Kernel.Pdf.Canvas;
using TSpdf.Kernel.Utils;
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("IntegrationTest")]
public class InheritedPageEntriesTest : ExtendedTSpdfTest {
public static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/pdf/InheritedPageEntriesTest/";
public static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/pdf/InheritedPageEntriesTest/";
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
CreateOrClearDestinationFolder(destinationFolder);
}
[NUnit.Framework.Test]
public virtual void AddNewPageToDocumentWithInheritedPageRotationTest() {
//TODO: update cmp-files when DEVSIX-3635 will be fixed
String inputFileName = sourceFolder + "srcFileTestRotationInheritance.pdf";
String outputFileName = destinationFolder + "addNewPageToDocumentWithInheritedPageRotation.pdf";
String cmpFileName = sourceFolder + "cmp_addNewPageToDocumentWithInheritedPageRotation.pdf";
PdfDocument outFile = new PdfDocument(new PdfReader(inputFileName), new PdfWriter(outputFileName));
PdfPage page = outFile.AddNewPage();
PdfCanvas canvas = new PdfCanvas(page);
canvas.BeginText().MoveText(36, 750).SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.HELVETICA), 16
).ShowText("Hello Helvetica!").EndText().SaveState();
outFile.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outputFileName, cmpFileName, destinationFolder
));
}
[NUnit.Framework.Test]
public virtual void SetRotationToPageTest() {
String outputFileName = destinationFolder + "setRotationToPage.pdf";
String cmpFileName = sourceFolder + "cmp_setRotationToPage.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfReader(sourceFolder + "srcFileTestRotationInheritance.pdf"), new
PdfWriter(outputFileName));
PdfPage page = pdfDoc.GetPage(1);
page.SetRotation(90);
pdfDoc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outputFileName, cmpFileName, destinationFolder
));
}
[NUnit.Framework.Test]
public virtual void CopySeveralPagesToDocumentWithInheritedPageRotationTest() {
//TODO: update cmp-files when DEVSIX-3635 will be fixed
String outputFileName = destinationFolder + "copySeveralPagesToDocumentWithInheritedPageRotation.pdf";
String cmpFileName = sourceFolder + "cmp_copySeveralPagesToDocumentWithInheritedPageRotation.pdf";
PdfDocument pdfDoc1 = new PdfDocument(new PdfReader(sourceFolder + "noPagesRotation.pdf"));
PdfDocument pdfDoc2 = new PdfDocument(new PdfReader(sourceFolder + "addSeveralPagesToDocumentWithInheritedPageRotation.pdf"
), new PdfWriter(outputFileName));
pdfDoc1.CopyPagesTo(1, 2, pdfDoc2);
pdfDoc1.Close();
pdfDoc2.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outputFileName, cmpFileName, destinationFolder
));
}
[NUnit.Framework.Test]
public virtual void MediaBoxInheritance() {
String inputFileName = sourceFolder + "mediaBoxInheritanceTestSource.pdf";
PdfDocument outFile = new PdfDocument(new PdfReader(inputFileName));
PdfObject mediaBox = outFile.GetPage(1).GetPdfObject().Get(PdfName.MediaBox);
//Check if MediaBox in Page is absent
NUnit.Framework.Assert.IsNull(mediaBox);
PdfArray array = outFile.GetCatalog().GetPdfObject().GetAsDictionary(PdfName.Pages).GetAsArray(PdfName.MediaBox
);
Rectangle rectangle = array.ToRectangle();
Rectangle pageRect = outFile.GetPage(1).GetMediaBox();
outFile.Close();
NUnit.Framework.Assert.IsTrue(rectangle.EqualsWithEpsilon(pageRect));
}
[NUnit.Framework.Test]
public virtual void CropBoxInheritance() {
String inputFileName = sourceFolder + "cropBoxInheritanceTestSource.pdf";
PdfDocument outFile = new PdfDocument(new PdfReader(inputFileName));
PdfObject cropBox = outFile.GetPage(1).GetPdfObject().Get(PdfName.CropBox);
//Check if CropBox in Page is absent
NUnit.Framework.Assert.IsNull(cropBox);
PdfArray array = outFile.GetCatalog().GetPdfObject().GetAsDictionary(PdfName.Pages).GetAsArray(PdfName.CropBox
);
Rectangle rectangle = array.ToRectangle();
Rectangle pageRect = outFile.GetPage(1).GetCropBox();
outFile.Close();
NUnit.Framework.Assert.IsTrue(rectangle.EqualsWithEpsilon(pageRect));
}
}
}

View File

@@ -0,0 +1,186 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using TSpdf.Kernel.Exceptions;
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("UnitTest")]
public class MemoryLimitsAwareHandlerTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void DefaultMemoryHandler() {
MemoryLimitsAwareHandler handler = new MemoryLimitsAwareHandler();
NUnit.Framework.Assert.AreEqual(int.MaxValue / 100, handler.GetMaxSizeOfSingleDecompressedPdfStream());
NUnit.Framework.Assert.AreEqual(int.MaxValue / 20, handler.GetMaxSizeOfDecompressedPdfStreamsSum());
NUnit.Framework.Assert.AreEqual(50000000, handler.GetMaxNumberOfElementsInXrefStructure());
}
[NUnit.Framework.Test]
public virtual void CustomMemoryHandler() {
MemoryLimitsAwareHandler handler = new MemoryLimitsAwareHandler(1000000);
NUnit.Framework.Assert.AreEqual(100000000, handler.GetMaxSizeOfSingleDecompressedPdfStream());
NUnit.Framework.Assert.AreEqual(500000000, handler.GetMaxSizeOfDecompressedPdfStreamsSum());
}
[NUnit.Framework.Test]
public virtual void OverridenMemoryHandler() {
MemoryLimitsAwareHandler defaultHandler = new MemoryLimitsAwareHandler();
MemoryLimitsAwareHandler customHandler = new _MemoryLimitsAwareHandler_78();
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_78 : MemoryLimitsAwareHandler {
public _MemoryLimitsAwareHandler_78() {
}
public override bool IsMemoryLimitsAwarenessRequiredOnDecompression(PdfArray filters) {
return true;
}
}
[NUnit.Framework.Test]
public virtual void DefaultSingleMemoryHandler() {
MemoryLimitsAwareHandler handler = new MemoryLimitsAwareHandler();
TestSingleStream(handler);
}
[NUnit.Framework.Test]
public virtual void DefaultMultipleMemoryHandler() {
MemoryLimitsAwareHandler handler = new MemoryLimitsAwareHandler();
TestMultipleStreams(handler);
}
[NUnit.Framework.Test]
public virtual void ConsiderBytesTest() {
MemoryLimitsAwareHandler handler = new MemoryLimitsAwareHandler();
long state1 = handler.GetAllMemoryUsedForDecompression();
handler.ConsiderBytesOccupiedByDecompressedPdfStream(100);
long state2 = handler.GetAllMemoryUsedForDecompression();
NUnit.Framework.Assert.AreEqual(state1, state2);
handler.BeginDecompressedPdfStreamProcessing();
handler.ConsiderBytesOccupiedByDecompressedPdfStream(100);
long state3 = handler.GetAllMemoryUsedForDecompression();
NUnit.Framework.Assert.AreEqual(state1, state3);
handler.ConsiderBytesOccupiedByDecompressedPdfStream(80);
long state4 = handler.GetAllMemoryUsedForDecompression();
NUnit.Framework.Assert.AreEqual(state1, state4);
handler.EndDecompressedPdfStreamProcessing();
long state5 = handler.GetAllMemoryUsedForDecompression();
NUnit.Framework.Assert.AreEqual(state1 + 100, state5);
}
[NUnit.Framework.Test]
public virtual void CustomXrefCapacityHandlerTest() {
MemoryLimitsAwareHandler memoryLimitsAwareHandler = new MemoryLimitsAwareHandler();
NUnit.Framework.Assert.AreEqual(50000000, memoryLimitsAwareHandler.GetMaxNumberOfElementsInXrefStructure()
);
memoryLimitsAwareHandler.SetMaxNumberOfElementsInXrefStructure(20);
NUnit.Framework.Assert.AreEqual(20, memoryLimitsAwareHandler.GetMaxNumberOfElementsInXrefStructure());
}
[NUnit.Framework.Test]
public virtual void CheckCapacityExceedsLimitTest() {
MemoryLimitsAwareHandler memoryLimitsAwareHandler = new MemoryLimitsAwareHandler();
// There we add 2 instead of 1 since xref structures used 1-based indexes, so we decrement the capacity
// before check.
int capacityExceededTheLimit = memoryLimitsAwareHandler.GetMaxNumberOfElementsInXrefStructure() + 2;
Exception ex = NUnit.Framework.Assert.Catch(typeof(MemoryLimitsAwareException), () => memoryLimitsAwareHandler
.CheckIfXrefStructureExceedsTheLimit(capacityExceededTheLimit));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.XREF_STRUCTURE_SIZE_EXCEEDED_THE_LIMIT, ex.
Message);
}
[NUnit.Framework.Test]
public virtual void CheckCapacityTest() {
MemoryLimitsAwareHandler memoryLimitsAwareHandler = new MemoryLimitsAwareHandler();
int capacityToSet = 2;
NUnit.Framework.Assert.DoesNotThrow(() => memoryLimitsAwareHandler.CheckIfXrefStructureExceedsTheLimit(capacityToSet
));
}
private static void TestSingleStream(MemoryLimitsAwareHandler handler) {
String expectedExceptionMessage = KernelExceptionMessageConstant.DURING_DECOMPRESSION_SINGLE_STREAM_OCCUPIED_MORE_MEMORY_THAN_ALLOWED;
int expectedFailureIndex = 10;
String occuredExceptionMessage = null;
int limit = handler.GetMaxSizeOfSingleDecompressedPdfStream();
long step = limit / 10;
int i = 0;
try {
handler.BeginDecompressedPdfStreamProcessing();
for (i = 0; i < 11; i++) {
handler.ConsiderBytesOccupiedByDecompressedPdfStream(step * (1 + i));
}
handler.EndDecompressedPdfStreamProcessing();
}
catch (MemoryLimitsAwareException e) {
occuredExceptionMessage = e.Message;
}
NUnit.Framework.Assert.AreEqual(expectedFailureIndex, i);
NUnit.Framework.Assert.AreEqual(expectedExceptionMessage, occuredExceptionMessage);
}
private static void TestMultipleStreams(MemoryLimitsAwareHandler handler) {
String expectedExceptionMessage = KernelExceptionMessageConstant.DURING_DECOMPRESSION_MULTIPLE_STREAMS_IN_SUM_OCCUPIED_MORE_MEMORY_THAN_ALLOWED;
int expectedFailureIndex = 10;
String occuredExceptionMessage = null;
int i = 0;
try {
long limit = handler.GetMaxSizeOfDecompressedPdfStreamsSum();
long step = limit / 10;
for (i = 0; i < 11; i++) {
handler.BeginDecompressedPdfStreamProcessing();
handler.ConsiderBytesOccupiedByDecompressedPdfStream(step);
handler.EndDecompressedPdfStreamProcessing();
}
}
catch (MemoryLimitsAwareException e) {
occuredExceptionMessage = e.Message;
}
NUnit.Framework.Assert.AreEqual(expectedFailureIndex, i);
NUnit.Framework.Assert.AreEqual(expectedExceptionMessage, occuredExceptionMessage);
}
}
}

View File

@@ -0,0 +1,79 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using TSpdf.Kernel.Exceptions;
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("UnitTest")]
public class MemoryLimitsAwareOutputStreamTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void TestMaxSize() {
byte[] bigArray = new byte[70];
byte[] smallArray = new byte[31];
MemoryLimitsAwareOutputStream stream = new MemoryLimitsAwareOutputStream();
stream.SetMaxStreamSize(100);
NUnit.Framework.Assert.AreEqual(100, stream.GetMaxStreamSize());
stream.Write(bigArray, 0, bigArray.Length);
NUnit.Framework.Assert.AreEqual(bigArray.Length, stream.Length);
NUnit.Framework.Assert.Catch(typeof(MemoryLimitsAwareException), () => stream.Write(smallArray, 0, smallArray
.Length));
}
[NUnit.Framework.Test]
public virtual void TestNegativeSize() {
byte[] zeroArray = new byte[0];
MemoryLimitsAwareOutputStream stream = new MemoryLimitsAwareOutputStream();
stream.SetMaxStreamSize(-100);
NUnit.Framework.Assert.AreEqual(-100, stream.GetMaxStreamSize());
NUnit.Framework.Assert.Catch(typeof(MemoryLimitsAwareException), () => stream.Write(zeroArray, 0, zeroArray
.Length));
}
[NUnit.Framework.Test]
public virtual void TestIncorrectLength() {
MemoryLimitsAwareOutputStream stream = new MemoryLimitsAwareOutputStream();
NUnit.Framework.Assert.Catch(typeof(IndexOutOfRangeException), () => stream.Write(new byte[1], 0, -1));
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,61 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using System.IO;
using TSpdf.Kernel.Exceptions;
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("UnitTest")]
public class PageFlushingHelperUnitTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void FlushingInUnsafeModeTest() {
int pageToFlush = 1;
MemoryStream outputStream = new MemoryStream();
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outputStream));
pdfDocument.AddNewPage();
pdfDocument.Close();
pdfDocument = new PdfDocument(new PdfReader(new MemoryStream(outputStream.ToArray())));
PageFlushingHelper pageFlushingHelper = new PageFlushingHelper(pdfDocument);
Exception exception = NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => pageFlushingHelper.UnsafeFlushDeep
(pageToFlush));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.FLUSHING_HELPER_FLUSHING_MODE_IS_NOT_FOR_DOC_READING_MODE
, exception.Message);
}
[NUnit.Framework.Test]
public virtual void FlushingInAppendModeTest() {
int pageToFlush = 1;
MemoryStream outputStream = new MemoryStream();
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outputStream));
pdfDocument.AddNewPage();
pdfDocument.Close();
pdfDocument = new PdfDocument(new PdfReader(new MemoryStream(outputStream.ToArray())));
PageFlushingHelper pageFlushingHelper = new PageFlushingHelper(pdfDocument);
Exception exception = NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => pageFlushingHelper.AppendModeFlush
(pageToFlush));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.FLUSHING_HELPER_FLUSHING_MODE_IS_NOT_FOR_DOC_READING_MODE
, exception.Message);
}
}
}

View File

@@ -0,0 +1,575 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.Collections.Generic;
using System.IO;
using TSpdf.Commons.Utils;
using TSpdf.IO.Font.Constants;
using TSpdf.IO.Image;
using TSpdf.Kernel.Colors;
using TSpdf.Kernel.Font;
using TSpdf.Kernel.Geom;
using TSpdf.Kernel.Pdf.Action;
using TSpdf.Kernel.Pdf.Annot;
using TSpdf.Kernel.Pdf.Canvas;
using TSpdf.Kernel.Pdf.Canvas.Parser;
using TSpdf.Kernel.Pdf.Navigation;
using TSpdf.Kernel.Pdf.Xobject;
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("IntegrationTest")]
public class PageFlushingTest : ExtendedTSpdfTest {
private static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/pdf/PageFlushingTest/";
private static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/pdf/PageFlushingTest/";
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
CreateOrClearDestinationFolder(destinationFolder);
}
[NUnit.Framework.Test]
public virtual void BaseWriting01() {
// not all objects are made indirect before closing
int total = 414;
int flushedExpected = 0;
int notReadExpected = 0;
Test("baseWriting01.pdf", PageFlushingTest.DocMode.WRITING, PageFlushingTest.FlushMode.NONE, PageFlushingTest.PagesOp
.MODIFY, total, flushedExpected, notReadExpected);
}
[NUnit.Framework.Test]
public virtual void PageFlushWriting01() {
int total = 715;
int flushedExpected = 400;
int notReadExpected = 0;
Test("pageFlushWriting01.pdf", PageFlushingTest.DocMode.WRITING, PageFlushingTest.FlushMode.PAGE_FLUSH, PageFlushingTest.PagesOp
.MODIFY, total, flushedExpected, notReadExpected);
}
[NUnit.Framework.Test]
public virtual void UnsafeDeepFlushWriting01() {
int total = 816;
// 100 still hanging: new font dictionaries on every page shall not be flushed before closing
int flushedExpected = 702;
int notReadExpected = 0;
Test("unsafeDeepFlushWriting01.pdf", PageFlushingTest.DocMode.WRITING, PageFlushingTest.FlushMode.UNSAFE_DEEP
, PageFlushingTest.PagesOp.MODIFY, total, flushedExpected, notReadExpected);
}
[NUnit.Framework.Test]
public virtual void AppendModeFlushWriting01() {
int total = 715;
int flushedExpected = 400;
int notReadExpected = 0;
Test("appendModeFlushWriting01.pdf", PageFlushingTest.DocMode.WRITING, PageFlushingTest.FlushMode.APPEND_MODE
, PageFlushingTest.PagesOp.MODIFY, total, flushedExpected, notReadExpected);
}
[NUnit.Framework.Test]
public virtual void BaseReading01() {
int total = 817;
int flushedExpected = 0;
// link annots, line annots, actions and images: one hundred of each
int notReadExpected = 402;
Test("baseReading01.pdf", PageFlushingTest.DocMode.READING, PageFlushingTest.FlushMode.NONE, PageFlushingTest.PagesOp
.READ, total, flushedExpected, notReadExpected);
}
[NUnit.Framework.Test]
public virtual void ReleaseDeepReading01() {
int total = 817;
int flushedExpected = 0;
int notReadExpected = 804;
Test("releaseDeepReading01.pdf", PageFlushingTest.DocMode.READING, PageFlushingTest.FlushMode.RELEASE_DEEP
, PageFlushingTest.PagesOp.READ, total, flushedExpected, notReadExpected);
}
[NUnit.Framework.Test]
public virtual void BaseStamping01() {
// not all objects are made indirect before closing
int total = 1618;
int flushedExpected = 0;
int notReadExpected = 603;
Test("baseStamping01.pdf", PageFlushingTest.DocMode.STAMPING, PageFlushingTest.FlushMode.NONE, PageFlushingTest.PagesOp
.MODIFY, total, flushedExpected, notReadExpected);
}
[NUnit.Framework.Test]
public virtual void PageFlushStamping01() {
int total = 2219;
int flushedExpected = 1200;
int notReadExpected = 403;
Test("pageFlushStamping01.pdf", PageFlushingTest.DocMode.STAMPING, PageFlushingTest.FlushMode.PAGE_FLUSH,
PageFlushingTest.PagesOp.MODIFY, total, flushedExpected, notReadExpected);
}
[NUnit.Framework.Test]
public virtual void UnsafeDeepFlushStamping01() {
int total = 2420;
// 200 still hanging: new font dictionaries on every page shall not be flushed before closing
int flushedExpected = 1602;
int notReadExpected = 603;
Test("unsafeDeepFlushStamping01.pdf", PageFlushingTest.DocMode.STAMPING, PageFlushingTest.FlushMode.UNSAFE_DEEP
, PageFlushingTest.PagesOp.MODIFY, total, flushedExpected, notReadExpected);
}
[NUnit.Framework.Test]
public virtual void AppendModeFlushStamping01() {
int total = 2219;
// 300 less than with page#flush, because of not modified released objects
int flushedExpected = 900;
int notReadExpected = 703;
Test("appendModeFlushStamping01.pdf", PageFlushingTest.DocMode.STAMPING, PageFlushingTest.FlushMode.APPEND_MODE
, PageFlushingTest.PagesOp.MODIFY, total, flushedExpected, notReadExpected);
}
[NUnit.Framework.Test]
public virtual void ReleaseDeepStamping01() {
int total = 1618;
int flushedExpected = 0;
// new objects cannot be released
int notReadExpected = 703;
Test("releaseDeepStamping01.pdf", PageFlushingTest.DocMode.STAMPING, PageFlushingTest.FlushMode.RELEASE_DEEP
, PageFlushingTest.PagesOp.MODIFY, total, flushedExpected, notReadExpected);
}
[NUnit.Framework.Test]
public virtual void BaseAppendMode01() {
int total = 1618;
int flushedExpected = 0;
int notReadExpected = 603;
Test("baseAppendMode01.pdf", PageFlushingTest.DocMode.APPEND, PageFlushingTest.FlushMode.NONE, PageFlushingTest.PagesOp
.MODIFY, total, flushedExpected, notReadExpected);
}
[NUnit.Framework.Test]
public virtual void PageFlushAppendMode01() {
int total = 2219;
int flushedExpected = 900;
int notReadExpected = 403;
Test("pageFlushAppendMode01.pdf", PageFlushingTest.DocMode.APPEND, PageFlushingTest.FlushMode.PAGE_FLUSH,
PageFlushingTest.PagesOp.MODIFY, total, flushedExpected, notReadExpected);
}
[NUnit.Framework.Test]
public virtual void UnsafeDeepFlushAppendMode01() {
int total = 2420;
// 200 still hanging: new font dictionaries on every page shall not be flushed before closing
int flushedExpected = 1502;
int notReadExpected = 703;
Test("unsafeDeepFlushAppendMode01.pdf", PageFlushingTest.DocMode.APPEND, PageFlushingTest.FlushMode.UNSAFE_DEEP
, PageFlushingTest.PagesOp.MODIFY, total, flushedExpected, notReadExpected);
}
[NUnit.Framework.Test]
public virtual void AppendModeFlushAppendMode01() {
int total = 2219;
// 600 still hanging: every new page contains image, font and action
int flushedExpected = 900;
int notReadExpected = 703;
Test("appendModeFlushAppendMode01.pdf", PageFlushingTest.DocMode.APPEND, PageFlushingTest.FlushMode.APPEND_MODE
, PageFlushingTest.PagesOp.MODIFY, total, flushedExpected, notReadExpected);
}
[NUnit.Framework.Test]
public virtual void ReleaseDeepAppendMode01() {
int total = 1618;
int flushedExpected = 0;
// new objects cannot be released
int notReadExpected = 703;
Test("releaseDeepAppendMode01.pdf", PageFlushingTest.DocMode.APPEND, PageFlushingTest.FlushMode.RELEASE_DEEP
, PageFlushingTest.PagesOp.MODIFY, total, flushedExpected, notReadExpected);
}
[NUnit.Framework.Test]
public virtual void BaseLightAppendMode01() {
int total = 1018;
int flushedExpected = 0;
int notReadExpected = 603;
Test("baseLightAppendMode01.pdf", PageFlushingTest.DocMode.APPEND, PageFlushingTest.FlushMode.NONE, PageFlushingTest.PagesOp
.MODIFY_LIGHTLY, total, flushedExpected, notReadExpected);
}
[NUnit.Framework.Test]
public virtual void PageFlushLightAppendMode01() {
int total = 1318;
int flushedExpected = 500;
// in default PdfPage#flush annotations are always read and attempted to be flushed.
int notReadExpected = 403;
Test("pageFlushLightAppendMode01.pdf", PageFlushingTest.DocMode.APPEND, PageFlushingTest.FlushMode.PAGE_FLUSH
, PageFlushingTest.PagesOp.MODIFY_LIGHTLY, total, flushedExpected, notReadExpected);
}
[NUnit.Framework.Test]
public virtual void UnsafeDeepFlushLightAppendMode01() {
int total = 1318;
int flushedExpected = 600;
int notReadExpected = 703;
Test("unsafeDeepFlushLightAppendMode01.pdf", PageFlushingTest.DocMode.APPEND, PageFlushingTest.FlushMode.UNSAFE_DEEP
, PageFlushingTest.PagesOp.MODIFY_LIGHTLY, total, flushedExpected, notReadExpected);
}
[NUnit.Framework.Test]
public virtual void AppendModeFlushLightAppendMode01() {
int total = 1318;
// resources are not flushed, here it's font dictionaries for every page which in any case shall not be flushed before closing.
int flushedExpected = 500;
int notReadExpected = 703;
Test("appendModeFlushLightAppendMode01.pdf", PageFlushingTest.DocMode.APPEND, PageFlushingTest.FlushMode.APPEND_MODE
, PageFlushingTest.PagesOp.MODIFY_LIGHTLY, total, flushedExpected, notReadExpected);
}
[NUnit.Framework.Test]
public virtual void ReleaseDeepLightAppendMode01() {
int total = 1018;
int flushedExpected = 0;
int notReadExpected = 703;
Test("releaseDeepLightAppendMode01.pdf", PageFlushingTest.DocMode.APPEND, PageFlushingTest.FlushMode.RELEASE_DEEP
, PageFlushingTest.PagesOp.MODIFY_LIGHTLY, total, flushedExpected, notReadExpected);
}
[NUnit.Framework.Test]
public virtual void ModifyAnnotationOnlyAppendMode() {
String input = sourceFolder + "100pages.pdf";
String output = destinationFolder + "modifyAnnotOnly.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfReader(input), new PdfWriter(output), new StampingProperties()
.UseAppendMode());
PdfPage page = pdfDoc.GetPage(1);
PdfIndirectReference pageIndRef = page.GetPdfObject().GetIndirectReference();
PdfDictionary annotObj = page.GetAnnotations()[0].SetRectangle(new PdfArray(new Rectangle(0, 0, 300, 300))
).SetPage(page).GetPdfObject();
PageFlushingHelper flushingHelper = new PageFlushingHelper(pdfDoc);
flushingHelper.AppendModeFlush(1);
// annotation is flushed
NUnit.Framework.Assert.IsTrue(annotObj.IsFlushed());
// page is not flushed
NUnit.Framework.Assert.IsFalse(pageIndRef.CheckState(PdfObject.FLUSHED));
// page is released
NUnit.Framework.Assert.IsNull(pageIndRef.refersTo);
// exception is not thrown
pdfDoc.Close();
}
[NUnit.Framework.Test]
public virtual void SetLinkDestinationToPageAppendMode() {
String input = sourceFolder + "100pages.pdf";
String output = destinationFolder + "setLinkDestinationToPageAppendMode.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfReader(input), new PdfWriter(output), new StampingProperties()
.UseAppendMode());
PdfPage page1 = pdfDoc.GetPage(1);
PdfPage page2 = pdfDoc.GetPage(2);
PdfIndirectReference page1IndRef = page1.GetPdfObject().GetIndirectReference();
PdfIndirectReference page2IndRef = page2.GetPdfObject().GetIndirectReference();
PdfDictionary aDict = ((PdfLinkAnnotation)page1.GetAnnotations()[0]).GetAction();
new PdfAction(aDict).Put(PdfName.D, PdfExplicitDestination.CreateXYZ(page2, 300, 400, 1).GetPdfObject());
PageFlushingHelper flushingHelper = new PageFlushingHelper(pdfDoc);
flushingHelper.AppendModeFlush(2);
flushingHelper.UnsafeFlushDeep(1);
// annotation is flushed
NUnit.Framework.Assert.IsTrue(aDict.IsFlushed());
// page is not flushed
NUnit.Framework.Assert.IsFalse(page1IndRef.CheckState(PdfObject.FLUSHED));
// page is released
NUnit.Framework.Assert.IsNull(page1IndRef.refersTo);
// page is not flushed
NUnit.Framework.Assert.IsFalse(page2IndRef.CheckState(PdfObject.FLUSHED));
// page is released
NUnit.Framework.Assert.IsNull(page2IndRef.refersTo);
// exception is not thrown
pdfDoc.Close();
}
[NUnit.Framework.Test]
public virtual void FlushSelfContainingObjectsWritingMode() {
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(new MemoryStream()));
PdfDictionary pageDict = pdfDoc.AddNewPage().GetPdfObject();
PdfDictionary dict1 = new PdfDictionary();
pageDict.Put(new PdfName("dict1"), dict1);
PdfArray arr1 = new PdfArray();
pageDict.Put(new PdfName("arr1"), arr1);
dict1.Put(new PdfName("dict1"), dict1);
dict1.Put(new PdfName("arr1"), arr1);
arr1.Add(arr1);
arr1.Add(dict1);
arr1.MakeIndirect(pdfDoc);
dict1.MakeIndirect(pdfDoc);
PageFlushingHelper flushingHelper = new PageFlushingHelper(pdfDoc);
flushingHelper.UnsafeFlushDeep(1);
NUnit.Framework.Assert.IsTrue(dict1.IsFlushed());
NUnit.Framework.Assert.IsTrue(arr1.IsFlushed());
pdfDoc.Close();
}
// exception is not thrown
[NUnit.Framework.Test]
public virtual void FlushingPageResourcesMadeIndependent() {
String inputFile = sourceFolder + "100pagesSharedResDict.pdf";
String outputFile = destinationFolder + "flushingPageResourcesMadeIndependent.pdf";
PdfDocument pdf = new PdfDocument(new PdfReader(inputFile), new PdfWriter(outputFile));
int numOfAddedXObjectsPerPage = 10;
for (int i = 1; i <= pdf.GetNumberOfPages(); ++i) {
PdfPage sourcePage = pdf.GetPage(i);
PdfDictionary res = sourcePage.GetPdfObject().GetAsDictionary(PdfName.Resources);
PdfDictionary resClone = new PdfDictionary();
// clone dictionary manually to ensure this object is direct and is flushed together with the page
foreach (KeyValuePair<PdfName, PdfObject> e in res.EntrySet()) {
resClone.Put(e.Key, e.Value.Clone());
}
sourcePage.GetPdfObject().Put(PdfName.Resources, resClone);
PdfCanvas pdfCanvas = new PdfCanvas(sourcePage);
pdfCanvas.SaveState();
for (int j = 0; j < numOfAddedXObjectsPerPage; ++j) {
PdfImageXObject xObject = new PdfImageXObject(ImageDataFactory.Create(sourceFolder + "simple.jpg"));
pdfCanvas.AddXObjectFittedIntoRectangle(xObject, new Rectangle(36, 720 - j * 150, 20, 20));
xObject.MakeIndirect(pdf).Flush();
}
pdfCanvas.RestoreState();
pdfCanvas.Release();
sourcePage.Flush();
}
VerifyFlushedObjectsNum(pdf, 1416, 1400, 0);
pdf.Close();
PrintOutputPdfNameAndDir(outputFile);
PdfDocument result = new PdfDocument(new PdfReader(outputFile));
PdfObject page15Res = result.GetPage(15).GetPdfObject().Get(PdfName.Resources, false);
PdfObject page34Res = result.GetPage(34).GetPdfObject().Get(PdfName.Resources, false);
NUnit.Framework.Assert.IsTrue(page15Res.IsDictionary());
NUnit.Framework.Assert.AreEqual(numOfAddedXObjectsPerPage, ((PdfDictionary)page15Res).GetAsDictionary(PdfName
.XObject).Size());
NUnit.Framework.Assert.IsTrue(page34Res.IsDictionary());
NUnit.Framework.Assert.AreNotEqual(page15Res, page34Res);
result.Close();
}
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";
String output = destinationFolder + filename;
PdfDocument pdfDoc;
switch (docMode) {
case PageFlushingTest.DocMode.WRITING: {
pdfDoc = new PdfDocument(new PdfWriter(output));
break;
}
case PageFlushingTest.DocMode.READING: {
pdfDoc = new PdfDocument(new PdfReader(input));
break;
}
case PageFlushingTest.DocMode.STAMPING: {
pdfDoc = new PdfDocument(new PdfReader(input), new PdfWriter(output));
break;
}
case PageFlushingTest.DocMode.APPEND: {
pdfDoc = new PdfDocument(new PdfReader(input), new PdfWriter(output), new StampingProperties().UseAppendMode
());
break;
}
default: {
throw new InvalidOperationException();
}
}
PageFlushingHelper flushingHelper = new PageFlushingHelper(pdfDoc);
PdfFont font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA);
PdfImageXObject xObject = new PdfImageXObject(ImageDataFactory.Create(sourceFolder + "TSpdf.png"));
if (docMode != PageFlushingTest.DocMode.WRITING) {
for (int i = 0; i < 100; ++i) {
PdfPage page = pdfDoc.GetPage(i + 1);
switch (pagesOp) {
case PageFlushingTest.PagesOp.READ: {
PdfTextExtractor.GetTextFromPage(page);
break;
}
case PageFlushingTest.PagesOp.MODIFY: {
AddContentToPage(page, font, xObject);
break;
}
case PageFlushingTest.PagesOp.MODIFY_LIGHTLY: {
AddBasicContent(page, font);
break;
}
}
switch (flushMode) {
case PageFlushingTest.FlushMode.UNSAFE_DEEP: {
flushingHelper.UnsafeFlushDeep(i + 1);
break;
}
case PageFlushingTest.FlushMode.RELEASE_DEEP: {
flushingHelper.ReleaseDeep(i + 1);
break;
}
case PageFlushingTest.FlushMode.APPEND_MODE: {
flushingHelper.AppendModeFlush(i + 1);
break;
}
case PageFlushingTest.FlushMode.PAGE_FLUSH: {
page.Flush();
break;
}
}
}
}
if (docMode != PageFlushingTest.DocMode.READING && pagesOp == PageFlushingTest.PagesOp.MODIFY) {
for (int i = 0; i < 100; ++i) {
PdfPage page = pdfDoc.AddNewPage();
AddContentToPage(page, font, xObject);
switch (flushMode) {
case PageFlushingTest.FlushMode.UNSAFE_DEEP: {
flushingHelper.UnsafeFlushDeep(pdfDoc.GetNumberOfPages());
break;
}
case PageFlushingTest.FlushMode.RELEASE_DEEP: {
flushingHelper.ReleaseDeep(pdfDoc.GetNumberOfPages());
break;
}
case PageFlushingTest.FlushMode.APPEND_MODE: {
flushingHelper.AppendModeFlush(pdfDoc.GetNumberOfPages());
break;
}
case PageFlushingTest.FlushMode.PAGE_FLUSH: {
page.Flush();
break;
}
}
}
}
VerifyFlushedObjectsNum(pdfDoc, total, flushedExpected, notReadExpected);
pdfDoc.Close();
}
private static void VerifyFlushedObjectsNum(PdfDocument pdfDoc, int total, int flushedExpected, int notReadExpected
) {
int flushedActual = 0;
int notReadActual = 0;
for (int i = 0; i < pdfDoc.GetXref().Size(); ++i) {
PdfIndirectReference indRef = pdfDoc.GetXref().Get(i);
if (indRef.CheckState(PdfObject.FLUSHED)) {
++flushedActual;
}
else {
if (!indRef.IsFree() && indRef.refersTo == null) {
++notReadActual;
}
}
}
if (pdfDoc.GetXref().Size() != total || flushedActual != flushedExpected || notReadActual != notReadExpected
) {
NUnit.Framework.Assert.Fail(MessageFormatUtil.Format("\nExpected total: {0}, flushed: {1}, not read: {2};"
+ "\nbut actual was: {3}, flushed: {4}, not read: {5}.", total, flushedExpected, notReadExpected, pdfDoc
.GetXref().Size(), flushedActual, notReadActual));
}
NUnit.Framework.Assert.AreEqual(total, pdfDoc.GetXref().Size(), "wrong num of total objects");
NUnit.Framework.Assert.AreEqual(flushedExpected, flushedActual, "wrong num of flushed objects");
NUnit.Framework.Assert.AreEqual(notReadExpected, notReadActual, "wrong num of not read objects");
}
private static void AddContentToPage(PdfPage pdfPage, PdfFont font, PdfImageXObject xObject) {
PdfCanvas canvas = AddBasicContent(pdfPage, font);
canvas.SaveState().Rectangle(250, 500, 100, 100).Fill().RestoreState();
PdfFont courier = PdfFontFactory.CreateFont(StandardFonts.COURIER);
courier.MakeIndirect(pdfPage.GetDocument());
canvas.SaveState().BeginText().MoveText(36, 650).SetFontAndSize(courier, 16).ShowText("Hello Courier!").EndText
().RestoreState();
canvas.SaveState().Circle(100, 400, 25).Fill().RestoreState();
canvas.SaveState().RoundRectangle(100, 650, 100, 100, 10).Fill().RestoreState();
canvas.SaveState().SetLineWidth(10).RoundRectangle(250, 650, 100, 100, 10).Stroke().RestoreState();
canvas.SaveState().SetLineWidth(5).Arc(400, 650, 550, 750, 0, 180).Stroke().RestoreState();
canvas.SaveState().SetLineWidth(5).MoveTo(400, 550).CurveTo(500, 570, 450, 450, 550, 550).Stroke().RestoreState
();
canvas.AddXObjectFittedIntoRectangle(xObject, new Rectangle(100, 500, 400, xObject.GetHeight()));
PdfImageXObject xObject2 = new PdfImageXObject(ImageDataFactory.Create(sourceFolder + "TSpdf.png"));
xObject2.MakeIndirect(pdfPage.GetDocument());
canvas.AddXObjectFittedIntoRectangle(xObject2, new Rectangle(100, 500, 400, xObject2.GetHeight()));
}
private static PdfCanvas AddBasicContent(PdfPage pdfPage, PdfFont font) {
Rectangle lineAnnotRect = new Rectangle(0, 0, PageSize.A4.GetRight(), PageSize.A4.GetTop());
pdfPage.AddAnnotation(new PdfLinkAnnotation(new Rectangle(100, 600, 100, 20)).SetAction(PdfAction.CreateURI
("http://TSpdfpdf.com"))).AddAnnotation(new PdfLineAnnotation(lineAnnotRect, new float[] { lineAnnotRect
.GetX(), lineAnnotRect.GetY(), lineAnnotRect.GetRight(), lineAnnotRect.GetTop() }).SetColor(ColorConstants
.BLACK));
PdfCanvas canvas = new PdfCanvas(pdfPage);
canvas.Rectangle(100, 100, 100, 100).Fill();
canvas.SaveState().BeginText().SetTextMatrix(AffineTransform.GetRotateInstance(Math.PI / 4, 36, 350)).SetFontAndSize
(font, 72).ShowText("Hello Helvetica!").EndText().RestoreState();
return canvas;
}
private enum DocMode {
WRITING,
READING,
STAMPING,
APPEND
}
private enum FlushMode {
NONE,
PAGE_FLUSH,
UNSAFE_DEEP,
RELEASE_DEEP,
APPEND_MODE
}
private enum PagesOp {
NONE,
READ,
MODIFY,
MODIFY_LIGHTLY
}
}
}

View File

@@ -0,0 +1,336 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using TSpdf.IO.Font.Constants;
using TSpdf.Kernel.Font;
using TSpdf.Kernel.Geom;
using TSpdf.Kernel.Pdf.Annot;
using TSpdf.Kernel.Pdf.Canvas;
using TSpdf.Kernel.Pdf.Tagging;
using TSpdf.Kernel.Utils;
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("IntegrationTest")]
public class ParentTreeTest : ExtendedTSpdfTest {
public static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/pdf/ParentTreeTest/";
public static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/pdf/ParentTreeTest/";
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
CreateDestinationFolder(destinationFolder);
}
[NUnit.Framework.Test]
public virtual void Test01() {
String outFile = destinationFolder + "parentTreeTest01.pdf";
String cmpFile = sourceFolder + "cmp_parentTreeTest01.pdf";
PdfDocument document = new PdfDocument(new PdfWriter(outFile));
document.SetTagged();
PdfStructElem doc = document.GetStructTreeRoot().AddKid(new PdfStructElem(document, PdfName.Document));
PdfPage firstPage = document.AddNewPage();
PdfCanvas canvas = new PdfCanvas(firstPage);
canvas.BeginText();
canvas.SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.COURIER), 24);
canvas.SetTextMatrix(1, 0, 0, 1, 32, 512);
PdfStructElem paragraph = doc.AddKid(new PdfStructElem(document, PdfName.P));
PdfStructElem span1 = paragraph.AddKid(new PdfStructElem(document, PdfName.Span, firstPage));
canvas.OpenTag(new CanvasTag(span1.AddKid(new PdfMcrNumber(firstPage, span1))));
canvas.ShowText("Hello ");
canvas.CloseTag();
canvas.OpenTag(new CanvasTag(span1.AddKid(new PdfMcrDictionary(firstPage, span1))));
canvas.ShowText("World");
canvas.CloseTag();
canvas.EndText();
canvas.Release();
PdfPage secondPage = document.AddNewPage();
document.Close();
NUnit.Framework.Assert.IsTrue(CheckParentTree(outFile, cmpFile));
}
[NUnit.Framework.Test]
public virtual void StampingFormXObjectInnerContentTaggedTest() {
String pdf = sourceFolder + "alreadyTaggedFormXObjectInnerContent.pdf";
String outPdf = destinationFolder + "stampingFormXObjectInnerContentTaggedTest.pdf";
String cmpPdf = sourceFolder + "cmp_stampingFormXObjectInnerContentTaggedTest.pdf";
PdfDocument taggedPdf = new PdfDocument(new PdfReader(pdf), new PdfWriter(outPdf));
taggedPdf.SetTagged();
taggedPdf.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, destinationFolder, "diff"
));
}
[NUnit.Framework.Test]
public virtual void SeveralXObjectsOnOnePageTest() {
String pdf = sourceFolder + "severalXObjectsOnOnePageTest.pdf";
String outPdf = destinationFolder + "severalXObjectsOnOnePageTest.pdf";
String cmpPdf = sourceFolder + "cmp_severalXObjectsOnOnePageTest.pdf";
PdfDocument taggedPdf = new PdfDocument(new PdfReader(pdf), new PdfWriter(outPdf));
taggedPdf.SetTagged();
taggedPdf.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, destinationFolder, "diff"
));
}
[NUnit.Framework.Test]
public virtual void EarlyFlushXObjectTaggedTest() {
String pdf = sourceFolder + "earlyFlushXObjectTaggedTest.pdf";
String outPdf = destinationFolder + "earlyFlushXObjectTaggedTest.pdf";
String cmpPdf = sourceFolder + "cmp_earlyFlushXObjectTaggedTest.pdf";
PdfDocument taggedPdf = new PdfDocument(new PdfReader(pdf), new PdfWriter(outPdf));
PdfDictionary resource = taggedPdf.GetFirstPage().GetResources().GetResource(PdfName.XObject);
resource.Get(new PdfName("Fm1")).Flush();
taggedPdf.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, destinationFolder, "diff"
));
}
[NUnit.Framework.Test]
public virtual void IdenticalMcidIdInOneStreamTest() {
String pdf = sourceFolder + "identicalMcidIdInOneStreamTest.pdf";
String outPdf = destinationFolder + "identicalMcidIdInOneStreamTest.pdf";
String cmpPdf = sourceFolder + "cmp_identicalMcidIdInOneStreamTest.pdf";
PdfDocument taggedPdf = new PdfDocument(new PdfReader(pdf), new PdfWriter(outPdf));
taggedPdf.SetTagged();
taggedPdf.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, destinationFolder, "diff"
));
}
[NUnit.Framework.Test]
public virtual void CopyPageWithFormXObjectTaggedTest() {
String cmpPdf = sourceFolder + "cmp_copyPageWithFormXobjectTaggedTest.pdf";
String outDoc = destinationFolder + "copyPageWithFormXobjectTaggedTest.pdf";
PdfDocument srcPdf = new PdfDocument(new PdfReader(sourceFolder + "copyFromFile.pdf"));
PdfDocument outPdf = new PdfDocument(new PdfReader(sourceFolder + "copyToFile.pdf"), new PdfWriter(outDoc)
);
outPdf.SetTagged();
srcPdf.CopyPagesTo(1, 1, outPdf);
srcPdf.Close();
outPdf.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outDoc, cmpPdf, destinationFolder));
}
[NUnit.Framework.Test]
public virtual void RemovePageWithFormXObjectTaggedTest() {
String cmpPdf = sourceFolder + "cmp_removePageWithFormXobjectTaggedTest.pdf";
String outDoc = destinationFolder + "removePageWithFormXobjectTaggedTest.pdf";
PdfDocument outPdf = new PdfDocument(new PdfReader(sourceFolder + "forRemovePage.pdf"), new PdfWriter(outDoc
));
outPdf.SetTagged();
outPdf.RemovePage(1);
outPdf.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outDoc, cmpPdf, destinationFolder));
}
[NUnit.Framework.Test]
public virtual void Test02() {
String outFile = destinationFolder + "parentTreeTest02.pdf";
String cmpFile = sourceFolder + "cmp_parentTreeTest02.pdf";
PdfDocument document = new PdfDocument(new PdfWriter(outFile));
document.SetTagged();
PdfStructElem doc = document.GetStructTreeRoot().AddKid(new PdfStructElem(document, PdfName.Document));
PdfPage firstPage = document.AddNewPage();
PdfPage secondPage = document.AddNewPage();
PdfCanvas canvas = new PdfCanvas(secondPage);
canvas.BeginText();
canvas.SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.COURIER), 24);
canvas.SetTextMatrix(1, 0, 0, 1, 32, 512);
PdfStructElem paragraph = doc.AddKid(new PdfStructElem(document, PdfName.P));
PdfStructElem span1 = paragraph.AddKid(new PdfStructElem(document, PdfName.Span, secondPage));
canvas.OpenTag(new CanvasTag(span1.AddKid(new PdfMcrNumber(secondPage, span1))));
canvas.ShowText("Hello ");
canvas.CloseTag();
canvas.OpenTag(new CanvasTag(span1.AddKid(new PdfMcrDictionary(secondPage, span1))));
canvas.ShowText("World");
canvas.CloseTag();
canvas.EndText();
canvas.Release();
document.Close();
NUnit.Framework.Assert.IsTrue(CheckParentTree(outFile, cmpFile));
}
[NUnit.Framework.Test]
public virtual void Test03() {
String outFile = destinationFolder + "parentTreeTest03.pdf";
String cmpFile = sourceFolder + "cmp_parentTreeTest03.pdf";
PdfDocument document = new PdfDocument(new PdfWriter(outFile));
document.SetTagged();
PdfStructElem doc = document.GetStructTreeRoot().AddKid(new PdfStructElem(document, PdfName.Document));
PdfPage firstPage = document.AddNewPage();
for (int i = 0; i < 51; i++) {
PdfPage anotherPage = document.AddNewPage();
PdfCanvas canvas = new PdfCanvas(anotherPage);
canvas.BeginText();
canvas.SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.COURIER), 24);
canvas.SetTextMatrix(1, 0, 0, 1, 32, 512);
PdfStructElem paragraph = doc.AddKid(new PdfStructElem(document, PdfName.P));
PdfStructElem span1 = paragraph.AddKid(new PdfStructElem(document, PdfName.Span, anotherPage));
canvas.OpenTag(new CanvasTag(span1.AddKid(new PdfMcrNumber(anotherPage, span1))));
canvas.ShowText("Hello ");
canvas.CloseTag();
canvas.OpenTag(new CanvasTag(span1.AddKid(new PdfMcrDictionary(anotherPage, span1))));
canvas.ShowText("World");
canvas.CloseTag();
canvas.EndText();
canvas.Release();
}
document.Close();
NUnit.Framework.Assert.IsTrue(CheckParentTree(outFile, cmpFile));
}
[NUnit.Framework.Test]
public virtual void Test04() {
String outFile = destinationFolder + "parentTreeTest04.pdf";
String cmpFile = sourceFolder + "cmp_parentTreeTest04.pdf";
PdfDocument document = new PdfDocument(new PdfWriter(outFile));
document.SetTagged();
PdfStructElem doc = document.GetStructTreeRoot().AddKid(new PdfStructElem(document, PdfName.Document));
for (int i = 0; i < 51; i++) {
PdfPage anotherPage = document.AddNewPage();
PdfCanvas canvas = new PdfCanvas(anotherPage);
canvas.BeginText();
canvas.SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.COURIER), 24);
canvas.SetTextMatrix(1, 0, 0, 1, 32, 512);
PdfStructElem paragraph = doc.AddKid(new PdfStructElem(document, PdfName.P));
PdfStructElem span1 = paragraph.AddKid(new PdfStructElem(document, PdfName.Span, anotherPage));
canvas.OpenTag(new CanvasTag(span1.AddKid(new PdfMcrNumber(anotherPage, span1))));
canvas.ShowText("Hello ");
canvas.CloseTag();
canvas.OpenTag(new CanvasTag(span1.AddKid(new PdfMcrDictionary(anotherPage, span1))));
canvas.ShowText("World");
canvas.CloseTag();
canvas.EndText();
canvas.Release();
}
document.Close();
NUnit.Framework.Assert.IsTrue(CheckParentTree(outFile, cmpFile));
}
[NUnit.Framework.Test]
public virtual void Test05() {
String outFile = destinationFolder + "parentTreeTest05.pdf";
String cmpFile = sourceFolder + "cmp_parentTreeTest05.pdf";
PdfDocument document = new PdfDocument(new PdfWriter(outFile));
document.SetTagged();
PdfStructElem doc = document.GetStructTreeRoot().AddKid(new PdfStructElem(document, PdfName.Document));
PdfPage page1 = document.AddNewPage();
PdfCanvas canvas = new PdfCanvas(page1);
canvas.BeginText();
canvas.SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.COURIER), 24);
canvas.SetTextMatrix(1, 0, 0, 1, 32, 512);
PdfStructElem paragraph = doc.AddKid(new PdfStructElem(document, PdfName.P));
PdfStructElem span1 = paragraph.AddKid(new PdfStructElem(document, PdfName.Span, page1));
canvas.OpenTag(new CanvasTag(span1.AddKid(new PdfMcrNumber(page1, span1))));
canvas.ShowText("Hello ");
canvas.CloseTag();
canvas.OpenTag(new CanvasTag(span1.AddKid(new PdfMcrDictionary(page1, span1))));
canvas.ShowText("World");
canvas.CloseTag();
canvas.EndText();
canvas.Release();
PdfPage page2 = document.AddNewPage();
canvas = new PdfCanvas(page2);
canvas.BeginText();
canvas.SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.HELVETICA), 24);
canvas.SetTextMatrix(1, 0, 0, 1, 32, 512);
paragraph = doc.AddKid(new PdfStructElem(document, PdfName.P));
span1 = paragraph.AddKid(new PdfStructElem(document, PdfName.Span, page2));
canvas.OpenTag(new CanvasTag(span1.AddKid(new PdfMcrNumber(page2, span1))));
canvas.ShowText("Hello ");
canvas.CloseTag();
PdfStructElem span2 = paragraph.AddKid(new PdfStructElem(document, PdfName.Span, page2));
canvas.OpenTag(new CanvasTag(span2.AddKid(new PdfMcrNumber(page2, span2))));
canvas.ShowText("World");
canvas.CloseTag();
canvas.EndText();
canvas.Release();
document.Close();
NUnit.Framework.Assert.IsTrue(CheckParentTree(outFile, cmpFile));
}
[NUnit.Framework.Test]
public virtual void Test06() {
String outFile = destinationFolder + "parentTreeTest06.pdf";
String cmpFile = sourceFolder + "cmp_parentTreeTest06.pdf";
PdfDocument document = new PdfDocument(new PdfWriter(outFile));
document.SetTagged();
PdfStructElem doc = document.GetStructTreeRoot().AddKid(new PdfStructElem(document, PdfName.Document));
PdfPage firstPage = document.AddNewPage();
PdfCanvas canvas = new PdfCanvas(firstPage);
canvas.BeginText();
canvas.SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.COURIER), 24);
canvas.SetTextMatrix(1, 0, 0, 1, 32, 512);
PdfStructElem paragraph = doc.AddKid(new PdfStructElem(document, PdfName.P));
PdfStructElem span1 = paragraph.AddKid(new PdfStructElem(document, PdfName.Span, firstPage));
canvas.OpenTag(new CanvasTag(span1.AddKid(new PdfMcrNumber(firstPage, span1))));
canvas.ShowText("Hello ");
canvas.CloseTag();
canvas.OpenTag(new CanvasTag(span1.AddKid(new PdfMcrDictionary(firstPage, span1))));
canvas.ShowText("World");
canvas.CloseTag();
canvas.EndText();
canvas.Release();
PdfPage secondPage = document.AddNewPage();
PdfLinkAnnotation linkExplicitDest = new PdfLinkAnnotation(new Rectangle(35, 785, 160, 15));
secondPage.AddAnnotation(linkExplicitDest);
document.Close();
NUnit.Framework.Assert.IsTrue(CheckParentTree(outFile, cmpFile));
}
private bool CheckParentTree(String outFileName, String cmpFileName) {
PdfReader outReader = new PdfReader(outFileName);
PdfDocument outDocument = new PdfDocument(outReader);
PdfReader cmpReader = new PdfReader(cmpFileName);
PdfDocument cmpDocument = new PdfDocument(cmpReader);
CompareTool.CompareResult result = new CompareTool().CompareByCatalog(outDocument, cmpDocument);
if (!result.IsOk()) {
System.Console.Out.WriteLine(result.GetReport());
}
return result.IsOk();
}
}
}

View File

@@ -0,0 +1,328 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.Collections.Generic;
using System.IO;
using TSpdf.Commons.Utils;
using TSpdf.Kernel.Geom;
using TSpdf.Kernel.Pdf.Action;
using TSpdf.Kernel.Pdf.Annot;
using TSpdf.Kernel.Pdf.Filespec;
using TSpdf.Kernel.Utils;
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("IntegrationTest")]
public class PdfActionTest : ExtendedTSpdfTest {
public static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/pdf/PdfActionTest/";
public static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/pdf/PdfActionTest/";
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
CreateDestinationFolder(destinationFolder);
}
[NUnit.Framework.Test]
public virtual void ActionTest01() {
PdfDocument document = CreateDocument(new PdfWriter(destinationFolder + "actionTest01.pdf"), true);
document.GetCatalog().SetOpenAction(PdfAction.CreateURI("http://TSpdfpdf.com/"));
document.Close();
System.Console.Out.WriteLine(MessageFormatUtil.Format("Please open document {0} and make sure that you're automatically redirected to {1} site."
, destinationFolder + "actionTest01.pdf", "http://TSpdfpdf.com"));
}
[NUnit.Framework.Test]
public virtual void ActionTest02() {
PdfDocument document = CreateDocument(new PdfWriter(destinationFolder + "actionTest02.pdf"), false);
document.GetPage(2).SetAdditionalAction(PdfName.O, PdfAction.CreateURI("http://TSpdfpdf.com/"));
document.Close();
System.Console.Out.WriteLine(MessageFormatUtil.Format("Please open document {0} at page 2 and make sure that you're automatically redirected to {1} site."
, destinationFolder + "actionTest02.pdf", "http://TSpdfpdf.com"));
}
[NUnit.Framework.Test]
public virtual void SoundActionTest() {
String fileName = "soundActionTest.pdf";
PdfDocument document = CreateDocument(new PdfWriter(destinationFolder + fileName), false);
Stream @is = new FileStream(sourceFolder + "sample.aif", FileMode.Open, FileAccess.Read);
PdfStream sound1 = new PdfStream(document, @is);
sound1.Put(PdfName.R, new PdfNumber(32117));
sound1.Put(PdfName.E, PdfName.Signed);
sound1.Put(PdfName.B, new PdfNumber(16));
sound1.Put(PdfName.C, new PdfNumber(1));
document.GetPage(2).SetAdditionalAction(PdfName.O, PdfAction.CreateSound(sound1));
document.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + fileName, sourceFolder
+ "cmp_" + fileName, destinationFolder, "diff_"));
}
[NUnit.Framework.Test]
public virtual void SoundActionWithRepeatFlagTest() {
String fileName = "soundActionWithRepeatFlagTest.pdf";
PdfDocument document = CreateDocument(new PdfWriter(destinationFolder + fileName), false);
Stream @is = new FileStream(sourceFolder + "sample.aif", FileMode.Open, FileAccess.Read);
PdfStream sound1 = new PdfStream(document, @is);
sound1.Put(PdfName.R, new PdfNumber(32117));
sound1.Put(PdfName.E, PdfName.Signed);
sound1.Put(PdfName.B, new PdfNumber(16));
sound1.Put(PdfName.C, new PdfNumber(1));
document.GetPage(2).SetAdditionalAction(PdfName.O, PdfAction.CreateSound(sound1, 1f, false, true, false));
document.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + fileName, sourceFolder
+ "cmp_" + fileName, destinationFolder, "diff_"));
}
[NUnit.Framework.Test]
public virtual void SoundActionWithToBigVolumeTest() {
PdfDocument document = CreateDocument(new PdfWriter(new MemoryStream()), false);
Stream @is = new FileStream(sourceFolder + "sample.aif", FileMode.Open, FileAccess.Read);
PdfStream sound1 = new PdfStream(document, @is);
sound1.Put(PdfName.R, new PdfNumber(32117));
sound1.Put(PdfName.E, PdfName.Signed);
sound1.Put(PdfName.B, new PdfNumber(16));
sound1.Put(PdfName.C, new PdfNumber(1));
try {
document.GetPage(2).SetAdditionalAction(PdfName.O, PdfAction.CreateSound(sound1, 1.1f, false, false, false
));
NUnit.Framework.Assert.Fail("Exception not thrown");
}
catch (Exception e) {
NUnit.Framework.Assert.AreEqual("volume", e.Message);
}
document.Close();
}
[NUnit.Framework.Test]
public virtual void SoundActionWithToLowVolumeTest() {
PdfDocument document = CreateDocument(new PdfWriter(new MemoryStream()), false);
Stream @is = new FileStream(sourceFolder + "sample.aif", FileMode.Open, FileAccess.Read);
PdfStream sound1 = new PdfStream(document, @is);
sound1.Put(PdfName.R, new PdfNumber(32117));
sound1.Put(PdfName.E, PdfName.Signed);
sound1.Put(PdfName.B, new PdfNumber(16));
sound1.Put(PdfName.C, new PdfNumber(1));
try {
document.GetPage(2).SetAdditionalAction(PdfName.O, PdfAction.CreateSound(sound1, -1.1f, false, false, false
));
NUnit.Framework.Assert.Fail("Exception not thrown");
}
catch (Exception e) {
NUnit.Framework.Assert.AreEqual("volume", e.Message);
}
document.Close();
}
[NUnit.Framework.Test]
public virtual void OcgStateTest() {
PdfName stateName = PdfName.ON;
PdfDictionary ocgDict1 = new PdfDictionary();
ocgDict1.Put(PdfName.Type, PdfName.OCG);
ocgDict1.Put(PdfName.Name, new PdfName("ocg1"));
PdfDictionary ocgDict2 = new PdfDictionary();
ocgDict2.Put(PdfName.Type, PdfName.OCG);
ocgDict2.Put(PdfName.Name, new PdfName("ocg2"));
IList<PdfDictionary> dicts = new List<PdfDictionary>();
dicts.Add(ocgDict1);
dicts.Add(ocgDict2);
IList<PdfActionOcgState> ocgStates = new List<PdfActionOcgState>();
ocgStates.Add(new PdfActionOcgState(stateName, dicts));
String fileName = "ocgStateTest.pdf";
PdfDocument document = CreateDocument(new PdfWriter(destinationFolder + fileName), false);
document.GetPage(1).SetAdditionalAction(PdfName.O, PdfAction.CreateSetOcgState(ocgStates));
document.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + fileName, sourceFolder
+ "cmp_" + fileName, destinationFolder, "diff_"));
}
[NUnit.Framework.Test]
public virtual void LaunchActionTest() {
String fileName = "launchActionTest.pdf";
PdfDocument document = CreateDocument(new PdfWriter(destinationFolder + fileName), false);
document.GetPage(1).SetAdditionalAction(PdfName.O, PdfAction.CreateLaunch(new PdfStringFS("launch.sh")));
document.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + fileName, sourceFolder
+ "cmp_" + fileName, destinationFolder, "diff_"));
}
[NUnit.Framework.Test]
public virtual void LaunchActionOnNewWindowTest() {
String fileName = "launchActionOnNewWindowTest.pdf";
PdfDocument document = CreateDocument(new PdfWriter(destinationFolder + fileName), false);
document.GetPage(1).SetAdditionalAction(PdfName.O, PdfAction.CreateLaunch(new PdfStringFS("launch.sh"), true
));
document.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + fileName, sourceFolder
+ "cmp_" + fileName, destinationFolder, "diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateHiddenAnnotationTest() {
String fileName = "createHiddenAnnotationTest.pdf";
PdfDocument document = CreateDocument(new PdfWriter(destinationFolder + fileName), false);
PdfAnnotation annotation = new PdfLineAnnotation(new Rectangle(10, 10, 200, 200), new float[] { 50, 750, 50
, 750 });
document.GetPage(1).SetAdditionalAction(PdfName.O, PdfAction.CreateHide(annotation, true));
document.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + fileName, sourceFolder
+ "cmp_" + fileName, destinationFolder, "diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateHiddenAnnotationsTest() {
String fileName = "createHiddenAnnotationsTest.pdf";
PdfDocument document = CreateDocument(new PdfWriter(destinationFolder + fileName), false);
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 }) };
document.GetPage(1).SetAdditionalAction(PdfName.O, PdfAction.CreateHide(annotations, true));
document.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + fileName, sourceFolder
+ "cmp_" + fileName, destinationFolder, "diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateHiddenByFieldNameTest() {
String fileName = "createHiddenByFieldNameTest.pdf";
PdfDocument document = CreateDocument(new PdfWriter(destinationFolder + fileName), false);
document.GetPage(1).SetAdditionalAction(PdfName.O, PdfAction.CreateHide("name", true));
document.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + fileName, sourceFolder
+ "cmp_" + fileName, destinationFolder, "diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateHiddenByFieldNamesTest() {
String fileName = "createHiddenByFieldNamesTest.pdf";
PdfDocument document = CreateDocument(new PdfWriter(destinationFolder + fileName), false);
document.GetPage(1).SetAdditionalAction(PdfName.O, PdfAction.CreateHide(new String[] { "name1", "name2" },
true));
document.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + fileName, sourceFolder
+ "cmp_" + fileName, destinationFolder, "diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateNamedTest() {
String fileName = "createNamedTest.pdf";
PdfDocument document = CreateDocument(new PdfWriter(destinationFolder + fileName), false);
document.GetPage(1).SetAdditionalAction(PdfName.O, PdfAction.CreateNamed(PdfName.LastPage));
document.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + fileName, sourceFolder
+ "cmp_" + fileName, destinationFolder, "diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateJavaScriptTest() {
String fileName = "createJavaScriptTest.pdf";
PdfDocument document = CreateDocument(new PdfWriter(destinationFolder + fileName), false);
String javaScriptRotatePages = "this.setPageRotations(0,2,90)";
document.GetPage(1).SetAdditionalAction(PdfName.O, PdfAction.CreateJavaScript(javaScriptRotatePages));
document.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + fileName, sourceFolder
+ "cmp_" + fileName, destinationFolder, "diff_"));
}
[NUnit.Framework.Test]
public virtual void SoundAndNextJavaScriptActionTest() {
String fileName = "soundAndNextJavaScriptActionTest.pdf";
PdfDocument document = CreateDocument(new PdfWriter(destinationFolder + fileName), false);
Stream @is = new FileStream(sourceFolder + "sample.aif", FileMode.Open, FileAccess.Read);
PdfStream sound1 = new PdfStream(document, @is);
sound1.Put(PdfName.R, new PdfNumber(32117));
sound1.Put(PdfName.E, PdfName.Signed);
sound1.Put(PdfName.B, new PdfNumber(16));
sound1.Put(PdfName.C, new PdfNumber(1));
PdfAction action = PdfAction.CreateSound(sound1);
action.Next(PdfAction.CreateJavaScript("this.setPageRotations(0,2,90)"));
document.GetPage(2).SetAdditionalAction(PdfName.O, action);
document.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + fileName, sourceFolder
+ "cmp_" + fileName, destinationFolder, "diff_"));
}
[NUnit.Framework.Test]
public virtual void SoundAndTwoNextJavaScriptActionTest() {
String fileName = "soundAndTwoNextJavaScriptActionTest.pdf";
PdfDocument document = CreateDocument(new PdfWriter(destinationFolder + fileName), false);
Stream @is = new FileStream(sourceFolder + "sample.aif", FileMode.Open, FileAccess.Read);
PdfStream sound1 = new PdfStream(document, @is);
sound1.Put(PdfName.R, new PdfNumber(32117));
sound1.Put(PdfName.E, PdfName.Signed);
sound1.Put(PdfName.B, new PdfNumber(16));
sound1.Put(PdfName.C, new PdfNumber(1));
PdfAction action = PdfAction.CreateSound(sound1);
action.Next(PdfAction.CreateJavaScript("this.setPageRotations(0,2,90)"));
action.Next(PdfAction.CreateJavaScript("this.setPageRotations(0,2,180)"));
document.GetPage(2).SetAdditionalAction(PdfName.O, action);
document.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + fileName, sourceFolder
+ "cmp_" + fileName, destinationFolder, "diff_"));
}
private PdfDocument CreateDocument(PdfWriter writer, bool flushPages) {
PdfDocument document = new PdfDocument(writer);
PdfPage p1 = document.AddNewPage();
PdfStream str1 = p1.GetFirstContentStream();
str1.GetOutputStream().WriteString("1 0 0 rg 100 600 100 100 re f\n");
if (flushPages) {
p1.Flush();
}
PdfPage p2 = document.AddNewPage();
PdfStream str2 = p2.GetFirstContentStream();
str2.GetOutputStream().WriteString("0 1 0 rg 100 600 100 100 re f\n");
if (flushPages) {
p2.Flush();
}
PdfPage p3 = document.AddNewPage();
PdfStream str3 = p3.GetFirstContentStream();
str3.GetOutputStream().WriteString("0 0 1 rg 100 600 100 100 re f\n");
if (flushPages) {
p3.Flush();
}
return document;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,240 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.Collections.Generic;
using TSpdf.IO.Source;
using TSpdf.Kernel.Geom;
using TSpdf.Kernel.Pdf.Canvas.Parser;
using TSpdf.Kernel.Pdf.Canvas.Parser.Data;
using TSpdf.Kernel.Pdf.Canvas.Parser.Listener;
using TSpdf.Kernel.Pdf.Colorspace;
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("UnitTest")]
public class PdfArrayTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void TestValuesIndirectContains() {
PdfDocument doc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
PdfArray array = new PdfArray();
array.Add(new PdfNumber(0).MakeIndirect(doc).GetIndirectReference());
array.Add(new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
array.Add(new PdfNumber(2).MakeIndirect(doc));
array.Add(new PdfNumber(3).MakeIndirect(doc));
array.Add(new PdfNumber(4));
array.Add(new PdfNumber(5));
NUnit.Framework.Assert.IsTrue(array.Contains(array.Get(0, false)));
NUnit.Framework.Assert.IsTrue(array.Contains(array.Get(1, false)));
NUnit.Framework.Assert.IsTrue(array.Contains(array.Get(2).GetIndirectReference()));
NUnit.Framework.Assert.IsTrue(array.Contains(array.Get(3).GetIndirectReference()));
NUnit.Framework.Assert.IsTrue(array.Contains(array.Get(4)));
NUnit.Framework.Assert.IsTrue(array.Contains(array.Get(5)));
}
[NUnit.Framework.Test]
public virtual void TestValuesIndirectRemove() {
PdfDocument doc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
PdfArray array = new PdfArray();
array.Add(new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
array.Add(new PdfNumber(2).MakeIndirect(doc).GetIndirectReference());
array.Add(new PdfNumber(3).MakeIndirect(doc));
array.Add(new PdfNumber(4).MakeIndirect(doc));
array.Add(new PdfNumber(5));
array.Add(new PdfNumber(6));
array.Remove(array.Get(0, false));
array.Remove(array.Get(0, false));
array.Remove(array.Get(0).GetIndirectReference());
array.Remove(array.Get(0).GetIndirectReference());
array.Remove(array.Get(0));
array.Remove(array.Get(0));
NUnit.Framework.Assert.AreEqual(0, array.Size());
}
[NUnit.Framework.Test]
public virtual void TestContains() {
PdfDocument doc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
PdfArray array = new PdfArray();
array.Add(new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
array.Add(new PdfNumber(2).MakeIndirect(doc).GetIndirectReference());
array.Add(new PdfNumber(3).MakeIndirect(doc));
array.Add(new PdfNumber(4).MakeIndirect(doc));
array.Add(new PdfNumber(5));
array.Add(new PdfNumber(6));
PdfArray array2 = new PdfArray();
array2.Add(new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
array2.Add(new PdfNumber(2).MakeIndirect(doc).GetIndirectReference());
array2.Add(new PdfNumber(3).MakeIndirect(doc));
array2.Add(new PdfNumber(4).MakeIndirect(doc));
array2.Add(new PdfNumber(5));
array2.Add(new PdfNumber(6));
foreach (PdfObject obj in array2) {
NUnit.Framework.Assert.IsTrue(array.Contains(obj));
}
for (int i = 0; i < array2.Size(); i++) {
NUnit.Framework.Assert.IsTrue(array.Contains(array2.Get(i)));
}
}
[NUnit.Framework.Test]
public virtual void TestRemove() {
PdfDocument doc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
PdfArray array = new PdfArray();
array.Add(new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
array.Add(new PdfNumber(2).MakeIndirect(doc).GetIndirectReference());
array.Add(new PdfNumber(3).MakeIndirect(doc));
array.Add(new PdfNumber(4).MakeIndirect(doc));
array.Add(new PdfNumber(5));
array.Add(new PdfNumber(6));
PdfArray array2 = new PdfArray();
array2.Add(new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
array2.Add(new PdfNumber(2).MakeIndirect(doc).GetIndirectReference());
array2.Add(new PdfNumber(3).MakeIndirect(doc));
array2.Add(new PdfNumber(4).MakeIndirect(doc));
array2.Add(new PdfNumber(5));
array2.Add(new PdfNumber(6));
foreach (PdfObject obj in array2) {
array.Remove(obj);
}
NUnit.Framework.Assert.AreEqual(0, array.Size());
}
[NUnit.Framework.Test]
public virtual void TestRemove2() {
PdfDocument doc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
PdfArray array = new PdfArray();
array.Add(new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
array.Add(new PdfNumber(2).MakeIndirect(doc).GetIndirectReference());
array.Add(new PdfNumber(3).MakeIndirect(doc));
array.Add(new PdfNumber(4).MakeIndirect(doc));
array.Add(new PdfNumber(5));
array.Add(new PdfNumber(6));
PdfArray array2 = new PdfArray();
array2.Add(new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
array2.Add(new PdfNumber(2).MakeIndirect(doc).GetIndirectReference());
array2.Add(new PdfNumber(3).MakeIndirect(doc));
array2.Add(new PdfNumber(4).MakeIndirect(doc));
array2.Add(new PdfNumber(5));
array2.Add(new PdfNumber(6));
for (int i = 0; i < array2.Size(); i++) {
array.Remove(array2.Get(i));
}
NUnit.Framework.Assert.AreEqual(0, array.Size());
}
[NUnit.Framework.Test]
public virtual void TestIndexOf() {
PdfDocument doc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
PdfArray array = new PdfArray();
array.Add(new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
array.Add(new PdfNumber(2).MakeIndirect(doc).GetIndirectReference());
array.Add(new PdfNumber(3).MakeIndirect(doc));
array.Add(new PdfNumber(4).MakeIndirect(doc));
array.Add(new PdfNumber(5));
array.Add(new PdfNumber(6));
PdfArray array2 = new PdfArray();
array2.Add(new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
array2.Add(new PdfNumber(2).MakeIndirect(doc).GetIndirectReference());
array2.Add(new PdfNumber(3).MakeIndirect(doc));
array2.Add(new PdfNumber(4).MakeIndirect(doc));
array2.Add(new PdfNumber(5));
array2.Add(new PdfNumber(6));
int i = 0;
foreach (PdfObject obj in array2) {
NUnit.Framework.Assert.AreEqual(i++, array.IndexOf(obj));
}
}
[NUnit.Framework.Test]
public virtual void TestIndexOf2() {
PdfDocument doc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
PdfArray array = new PdfArray();
array.Add(new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
array.Add(new PdfNumber(2).MakeIndirect(doc).GetIndirectReference());
array.Add(new PdfNumber(3).MakeIndirect(doc));
array.Add(new PdfNumber(4).MakeIndirect(doc));
array.Add(new PdfNumber(5));
array.Add(new PdfNumber(6));
PdfArray array2 = new PdfArray();
array2.Add(new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
array2.Add(new PdfNumber(2).MakeIndirect(doc).GetIndirectReference());
array2.Add(new PdfNumber(3).MakeIndirect(doc));
array2.Add(new PdfNumber(4).MakeIndirect(doc));
array2.Add(new PdfNumber(5));
array2.Add(new PdfNumber(6));
for (int i = 0; i < array2.Size(); i++) {
NUnit.Framework.Assert.AreEqual(i, array.IndexOf(array2.Get(i)));
}
}
[NUnit.Framework.Test]
public virtual void PdfUncoloredPatternColorSize1Test() {
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
String contentColorSpace = "/Cs1 cs\n";
PdfDictionary pageDictionary = (PdfDictionary)new PdfDictionary().MakeIndirect(pdfDocument);
PdfStream contentStream = new PdfStream(contentColorSpace.GetBytes());
pageDictionary.Put(PdfName.Contents, contentStream);
PdfPage page = pdfDocument.AddNewPage();
page.GetPdfObject().Put(PdfName.Contents, contentStream);
PdfArray pdfArray = new PdfArray();
pdfArray.Add(PdfName.Pattern);
PdfColorSpace space = PdfColorSpace.MakeColorSpace(pdfArray);
page.GetResources().AddColorSpace(space);
Rectangle rectangle = new Rectangle(50, 50, 1000, 1000);
page.SetMediaBox(rectangle);
PdfCanvasProcessor processor = new PdfCanvasProcessor(new PdfArrayTest.NoOpListener());
processor.ProcessPageContent(page);
// Check if we reach the end of the test without failings together with verifying expected color space instance
NUnit.Framework.Assert.IsTrue(processor.GetGraphicsState().GetFillColor().GetColorSpace() is PdfSpecialCs.Pattern
);
}
private class NoOpListener : IEventListener {
public virtual void EventOccurred(IEventData data, EventType type) {
}
public virtual ICollection<EventType> GetSupportedEvents() {
return null;
}
}
}
}

View File

@@ -0,0 +1,78 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.Kernel.Exceptions;
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("UnitTest")]
public class PdfArrayUnitTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void CannotConvertArrayOfPdfStringsToArrayOfBooleansTest() {
PdfArray pdfArray = new PdfArray(new PdfString(""));
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfArray.ToBooleanArray());
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.CANNOT_CONVERT_PDF_ARRAY_TO_AN_ARRAY_OF_BOOLEANS
, exception.Message);
}
[NUnit.Framework.Test]
public virtual void CannotConvertArrayOfPdfStringsToDoubleArrayTest() {
PdfArray pdfArray = new PdfArray(new PdfString(""));
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfArray.ToDoubleArray());
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.CANNOT_CONVERT_PDF_ARRAY_TO_DOUBLE_ARRAY, exception
.Message);
}
[NUnit.Framework.Test]
public virtual void CannotConvertArrayOfPdfStringsToIntArrayTest() {
PdfArray pdfArray = new PdfArray(new PdfString(""));
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfArray.ToIntArray());
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.CANNOT_CONVERT_PDF_ARRAY_TO_INT_ARRAY, exception
.Message);
}
[NUnit.Framework.Test]
public virtual void CannotConvertArrayOfPdfStringsToFloatArrayTest() {
PdfArray pdfArray = new PdfArray(new PdfString(""));
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfArray.ToFloatArray());
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.CANNOT_CONVERT_PDF_ARRAY_TO_FLOAT_ARRAY, exception
.Message);
}
[NUnit.Framework.Test]
public virtual void CannotConvertArrayOfPdfStringsToLongArrayTest() {
PdfArray pdfArray = new PdfArray(new PdfString(""));
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfArray.ToLongArray());
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.CANNOT_CONVERT_PDF_ARRAY_TO_LONG_ARRAY, exception
.Message);
}
[NUnit.Framework.Test]
public virtual void CannotConvertArrayOfPdfStringsToRectangleTest() {
PdfArray pdfArray = new PdfArray(new PdfString(""));
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfArray.ToRectangle());
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.CANNOT_CONVERT_PDF_ARRAY_TO_RECTANGLE, exception
.Message);
}
}
}

View File

@@ -0,0 +1,341 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.Collections.Generic;
using System.IO;
using TSpdf.Commons.Utils;
using TSpdf.IO.Source;
using TSpdf.Kernel.Pdf.Annot;
using TSpdf.Kernel.Utils;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("IntegrationTest")]
public class PdfCopyTest : ExtendedTSpdfTest {
public static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/pdf/PdfCopyTest/";
public static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/pdf/PdfCopyTest/";
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
CreateOrClearDestinationFolder(destinationFolder);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.SOURCE_DOCUMENT_HAS_ACROFORM_DICTIONARY)]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.MAKE_COPY_OF_CATALOG_DICTIONARY_IS_FORBIDDEN)]
public virtual void CopySignedDocuments() {
PdfDocument pdfDoc1 = new PdfDocument(new PdfReader(sourceFolder + "hello_signed.pdf"));
PdfDocument pdfDoc2 = new PdfDocument(new PdfWriter(destinationFolder + "copySignedDocuments.pdf"));
pdfDoc1.CopyPagesTo(1, 1, pdfDoc2);
pdfDoc2.Close();
pdfDoc1.Close();
PdfDocument pdfDocument = new PdfDocument(new PdfReader(destinationFolder + "copySignedDocuments.pdf"));
PdfDictionary sig = (PdfDictionary)pdfDocument.GetPdfObject(13);
PdfDictionary sigRef = sig.GetAsArray(PdfName.Reference).GetAsDictionary(0);
NUnit.Framework.Assert.IsTrue(PdfName.SigRef.Equals(sigRef.GetAsName(PdfName.Type)));
NUnit.Framework.Assert.IsTrue(sigRef.Get(PdfName.Data).IsNull());
}
[NUnit.Framework.Test]
public virtual void Copying1() {
PdfDocument pdfDoc1 = new PdfDocument(new PdfWriter(destinationFolder + "copying1_1.pdf"));
pdfDoc1.GetDocumentInfo().SetAuthor("Alexander Chingarev").SetCreator("TSpdf 6").SetTitle("Empty TSpdf 6 Document"
);
pdfDoc1.GetCatalog().Put(new PdfName("a"), new PdfName("b").MakeIndirect(pdfDoc1));
PdfPage page1 = pdfDoc1.AddNewPage();
page1.Flush();
pdfDoc1.Close();
pdfDoc1 = new PdfDocument(new PdfReader(destinationFolder + "copying1_1.pdf"));
PdfDocument pdfDoc2 = new PdfDocument(new PdfWriter(destinationFolder + "copying1_2.pdf"));
pdfDoc2.AddNewPage();
pdfDoc2.GetDocumentInfo().GetPdfObject().Put(new PdfName("a"), pdfDoc1.GetCatalog().GetPdfObject().Get(new
PdfName("a")).CopyTo(pdfDoc2));
pdfDoc2.Close();
pdfDoc1.Close();
PdfReader reader = new PdfReader(destinationFolder + "copying1_2.pdf");
PdfDocument pdfDocument = new PdfDocument(reader);
NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt");
PdfDictionary trailer = pdfDocument.GetTrailer();
PdfDictionary info = trailer.GetAsDictionary(PdfName.Info);
PdfName b = info.GetAsName(new PdfName("a"));
NUnit.Framework.Assert.AreEqual("/b", b.ToString());
pdfDocument.Close();
}
[NUnit.Framework.Test]
public virtual void Copying2() {
PdfDocument pdfDoc1 = new PdfDocument(new PdfWriter(destinationFolder + "copying2_1.pdf"));
for (int i = 0; i < 10; i++) {
PdfPage page1 = pdfDoc1.AddNewPage();
page1.GetContentStream(0).GetOutputStream().Write(ByteUtils.GetIsoBytes("%page " + (i + 1).ToString() + "\n"
));
page1.Flush();
}
pdfDoc1.Close();
pdfDoc1 = new PdfDocument(new PdfReader(destinationFolder + "copying2_1.pdf"));
PdfDocument pdfDoc2 = new PdfDocument(new PdfWriter(destinationFolder + "copying2_2.pdf"));
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
pdfDoc2.AddPage(pdfDoc1.GetPage(i + 1).CopyTo(pdfDoc2));
}
}
pdfDoc2.Close();
pdfDoc1.Close();
PdfReader reader = new PdfReader(destinationFolder + "copying2_2.pdf");
PdfDocument pdfDocument = new PdfDocument(reader);
NUnit.Framework.Assert.AreEqual(false, 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", TSpdf.Commons.Utils.JavaUtil.GetStringForBytes
(bytes));
}
pdfDocument.Close();
}
[NUnit.Framework.Test]
public virtual void Copying3() {
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(destinationFolder + "copying3_1.pdf"));
PdfDictionary helloWorld = (PdfDictionary)new PdfDictionary().MakeIndirect(pdfDoc);
PdfDictionary helloWorld1 = (PdfDictionary)new PdfDictionary().MakeIndirect(pdfDoc);
helloWorld.Put(new PdfName("Hello"), new PdfString("World"));
helloWorld.Put(new PdfName("HelloWrld"), helloWorld);
helloWorld.Put(new PdfName("HelloWrld1"), helloWorld1);
PdfPage page = pdfDoc.AddNewPage();
page.GetPdfObject().Put(new PdfName("HelloWorld"), helloWorld);
page.GetPdfObject().Put(new PdfName("HelloWorldClone"), (PdfObject)helloWorld.Clone());
pdfDoc.Close();
PdfReader reader = new PdfReader(destinationFolder + "copying3_1.pdf");
pdfDoc = new PdfDocument(reader);
NUnit.Framework.Assert.AreEqual(false, 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());
PdfDictionary dic1 = pdfDoc.GetPage(1).GetPdfObject().GetAsDictionary(new PdfName("HelloWorldClone"));
NUnit.Framework.Assert.AreEqual(8, dic1.GetIndirectReference().GetObjNumber());
NUnit.Framework.Assert.AreEqual(0, dic1.GetIndirectReference().GetGenNumber());
PdfString str0 = dic0.GetAsString(new PdfName("Hello"));
PdfString str1 = dic1.GetAsString(new PdfName("Hello"));
NUnit.Framework.Assert.AreEqual(str0.GetValue(), str1.GetValue());
NUnit.Framework.Assert.AreEqual(str0.GetValue(), "World");
PdfDictionary dic01 = dic0.GetAsDictionary(new PdfName("HelloWrld"));
PdfDictionary dic11 = dic1.GetAsDictionary(new PdfName("HelloWrld"));
NUnit.Framework.Assert.AreEqual(dic01.GetIndirectReference().GetObjNumber(), dic11.GetIndirectReference().
GetObjNumber());
NUnit.Framework.Assert.AreEqual(dic01.GetIndirectReference().GetGenNumber(), dic11.GetIndirectReference().
GetGenNumber());
NUnit.Framework.Assert.AreEqual(dic01.GetIndirectReference().GetObjNumber(), 4);
NUnit.Framework.Assert.AreEqual(dic01.GetIndirectReference().GetGenNumber(), 0);
PdfDictionary dic02 = dic0.GetAsDictionary(new PdfName("HelloWrld1"));
PdfDictionary dic12 = dic1.GetAsDictionary(new PdfName("HelloWrld1"));
NUnit.Framework.Assert.AreEqual(dic02.GetIndirectReference().GetObjNumber(), dic12.GetIndirectReference().
GetObjNumber());
NUnit.Framework.Assert.AreEqual(dic02.GetIndirectReference().GetGenNumber(), dic12.GetIndirectReference().
GetGenNumber());
NUnit.Framework.Assert.AreEqual(dic12.GetIndirectReference().GetObjNumber(), 5);
NUnit.Framework.Assert.AreEqual(dic12.GetIndirectReference().GetGenNumber(), 0);
pdfDoc.Close();
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.SOURCE_DOCUMENT_HAS_ACROFORM_DICTIONARY)]
public virtual void CopyDocumentsWithFormFieldsTest() {
String filename = sourceFolder + "fieldsOn2-sPage.pdf";
PdfDocument sourceDoc = new PdfDocument(new PdfReader(filename));
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(destinationFolder + "copyDocumentsWithFormFields.pdf"));
sourceDoc.InitializeOutlines();
sourceDoc.CopyPagesTo(1, sourceDoc.GetNumberOfPages(), pdfDoc);
sourceDoc.Close();
pdfDoc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + "copyDocumentsWithFormFields.pdf"
, sourceFolder + "cmp_copyDocumentsWithFormFields.pdf", destinationFolder, "diff_"));
}
[NUnit.Framework.Test]
public virtual void CopySamePageWithAnnotationsSeveralTimes() {
String filename = sourceFolder + "rotated_annotation.pdf";
PdfDocument sourceDoc = new PdfDocument(new PdfReader(filename));
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(destinationFolder + "copySamePageWithAnnotationsSeveralTimes.pdf"
));
sourceDoc.InitializeOutlines();
sourceDoc.CopyPagesTo(JavaUtil.ArraysAsList(1, 1, 1), pdfDoc);
sourceDoc.Close();
pdfDoc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + "copySamePageWithAnnotationsSeveralTimes.pdf"
, sourceFolder + "cmp_copySamePageWithAnnotationsSeveralTimes.pdf", destinationFolder, "diff_"));
}
[NUnit.Framework.Test]
public virtual void CopyIndirectInheritablePageEntriesTest01() {
String src = sourceFolder + "indirectPageProps.pdf";
String filename = "copyIndirectInheritablePageEntriesTest01.pdf";
String dest = destinationFolder + filename;
String cmp = sourceFolder + "cmp_" + filename;
PdfDocument outputDoc = new PdfDocument(new PdfWriter(dest));
PdfDocument sourceDoc = new PdfDocument(new PdfReader(src));
sourceDoc.CopyPagesTo(1, 1, outputDoc);
sourceDoc.Close();
outputDoc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(dest, cmp, destinationFolder, "diff_"));
}
[NUnit.Framework.Test]
public virtual void CopyPageNoRotationToDocWithRotationInKidsPageTest() {
String src = sourceFolder + "srcFileWithSetRotation.pdf";
String dest = destinationFolder + "copyPageNoRotationToDocWithRotationInKidsPage.pdf";
String cmp = sourceFolder + "cmp_copyPageNoRotationToDocWithRotationInKidsPage.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
PdfDocument sourceDoc = new PdfDocument(new PdfReader(sourceFolder + "noRotationProp.pdf"));
sourceDoc.CopyPagesTo(1, sourceDoc.GetNumberOfPages(), pdfDoc);
sourceDoc.Close();
pdfDoc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(dest, cmp, destinationFolder));
}
[NUnit.Framework.Test]
public virtual void CopyPageNoRotationToDocWithRotationInPagesDictTest() {
//TODO: update cmp-files when DEVSIX-3635 will be fixed
String src = sourceFolder + "indirectPageProps.pdf";
String dest = destinationFolder + "copyPageNoRotationToDocWithRotationInPagesDict.pdf";
String cmp = sourceFolder + "cmp_copyPageNoRotationToDocWithRotationInPagesDict.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
PdfDocument sourceDoc = new PdfDocument(new PdfReader(sourceFolder + "noRotationProp.pdf"));
sourceDoc.CopyPagesTo(1, sourceDoc.GetNumberOfPages(), pdfDoc);
sourceDoc.Close();
pdfDoc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(dest, cmp, destinationFolder));
}
[NUnit.Framework.Test]
public virtual void CopyPageWithRotationInPageToDocWithRotationInPagesDictTest() {
String src = sourceFolder + "indirectPageProps.pdf";
String dest = destinationFolder + "copyPageWithRotationInPageToDocWithRotationInPagesDict.pdf";
String cmp = sourceFolder + "cmp_copyPageWithRotationInPageToDocWithRotationInPagesDict.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
PdfDocument sourceDoc = new PdfDocument(new PdfReader(sourceFolder + "srcFileCopyPageWithSetRotationValueInKids.pdf"
));
sourceDoc.CopyPagesTo(1, sourceDoc.GetNumberOfPages(), pdfDoc);
sourceDoc.Close();
pdfDoc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(dest, cmp, destinationFolder));
}
[NUnit.Framework.Test]
public virtual void CopySelfContainedObject() {
ByteArrayOutputStream inputBytes = new ByteArrayOutputStream();
PdfDocument prepInputDoc = new PdfDocument(new PdfWriter(inputBytes));
PdfDictionary selfContainedDict = new PdfDictionary();
PdfName randDictName = PdfName.Sound;
PdfName randEntry1 = PdfName.R;
PdfName randEntry2 = PdfName.S;
selfContainedDict.Put(randEntry1, selfContainedDict);
selfContainedDict.Put(randEntry2, selfContainedDict);
prepInputDoc.AddNewPage().Put(randDictName, selfContainedDict.MakeIndirect(prepInputDoc));
prepInputDoc.Close();
PdfDocument srcDoc = new PdfDocument(new PdfReader(new MemoryStream(inputBytes.ToArray())));
PdfDocument destDoc = new PdfDocument(new PdfWriter(destinationFolder + "copySelfContainedObject.pdf"));
srcDoc.CopyPagesTo(1, 1, destDoc);
PdfDictionary destPageObj = destDoc.GetFirstPage().GetPdfObject();
PdfDictionary destSelfContainedDict = destPageObj.GetAsDictionary(randDictName);
PdfDictionary destSelfContainedDictR = destSelfContainedDict.GetAsDictionary(randEntry1);
PdfDictionary destSelfContainedDictS = destSelfContainedDict.GetAsDictionary(randEntry2);
NUnit.Framework.Assert.AreEqual(destSelfContainedDict.GetIndirectReference(), destSelfContainedDictR.GetIndirectReference
());
NUnit.Framework.Assert.AreEqual(destSelfContainedDict.GetIndirectReference(), destSelfContainedDictS.GetIndirectReference
());
destDoc.Close();
srcDoc.Close();
}
[NUnit.Framework.Test]
public virtual void CopyDifferentRangesOfPagesWithBookmarksTest() {
String outFileName = destinationFolder + "copyDifferentRangesOfPagesWithBookmarksTest.pdf";
String cmpFileName = sourceFolder + "cmp_copyDifferentRangesOfPagesWithBookmarksTest.pdf";
PdfDocument targetPdf = new PdfDocument(new PdfWriter(outFileName));
targetPdf.InitializeOutlines();
PdfDocument sourcePdf = new PdfDocument(new PdfReader(sourceFolder + "sameDocWithBookmarksPdf.pdf"));
sourcePdf.InitializeOutlines();
int sourcePdfLength = sourcePdf.GetNumberOfPages();
int sourcePdfOutlines = sourcePdf.GetOutlines(false).GetAllChildren().Count;
sourcePdf.CopyPagesTo(3, sourcePdfLength, targetPdf);
sourcePdf.CopyPagesTo(1, 2, targetPdf);
int targetOutlines = targetPdf.GetOutlines(false).GetAllChildren().Count;
NUnit.Framework.Assert.AreEqual(sourcePdfOutlines, targetOutlines);
sourcePdf.Close();
targetPdf.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder
));
}
[NUnit.Framework.Test]
public virtual void CopyPagesLinkAnnotationTest() {
// TODO DEVSIX-577. Update cmp
String outFileName = destinationFolder + "copyPagesLinkAnnotationTest.pdf";
String cmpFileName = sourceFolder + "cmp_copyPagesLinkAnnotationTest.pdf";
PdfDocument targetPdf = new PdfDocument(new PdfWriter(outFileName));
PdfDocument linkAnotPdf = new PdfDocument(new PdfReader(sourceFolder + "pdfLinkAnnotationTest.pdf"));
int linkPdfLength = linkAnotPdf.GetNumberOfPages();
linkAnotPdf.CopyPagesTo(3, linkPdfLength, targetPdf);
linkAnotPdf.CopyPagesTo(1, 2, targetPdf);
IList<PdfAnnotation> annotations = GetPdfAnnotations(targetPdf);
NUnit.Framework.Assert.AreEqual(0, annotations.Count, "The number of merged annotations are not the same."
);
linkAnotPdf.Close();
targetPdf.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder
));
}
private IList<PdfAnnotation> GetPdfAnnotations(PdfDocument pdfDoc) {
int number = pdfDoc.GetNumberOfPages();
List<PdfAnnotation> annotations = new List<PdfAnnotation>();
for (int i = 1; i <= number; i++) {
annotations.AddAll(pdfDoc.GetPage(i).GetAnnotations());
}
return annotations;
}
}
}

View File

@@ -0,0 +1,80 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("UnitTest")]
public class PdfDashPatternTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void ConstructorNoParamTest() {
PdfDashPattern dashPattern = new PdfDashPattern();
NUnit.Framework.Assert.AreEqual(-1, dashPattern.GetDash(), 0.0001);
NUnit.Framework.Assert.AreEqual(-1, dashPattern.GetGap(), 0.0001);
NUnit.Framework.Assert.AreEqual(-1, dashPattern.GetPhase(), 0.0001);
}
[NUnit.Framework.Test]
public virtual void ConstructorOneParamTest() {
PdfDashPattern dashPattern = new PdfDashPattern(10);
NUnit.Framework.Assert.AreEqual(10, dashPattern.GetDash(), 0.0001);
NUnit.Framework.Assert.AreEqual(-1, dashPattern.GetGap(), 0.0001);
NUnit.Framework.Assert.AreEqual(-1, dashPattern.GetPhase(), 0.0001);
}
[NUnit.Framework.Test]
public virtual void ConstructorTwoParamsTest() {
PdfDashPattern dashPattern = new PdfDashPattern(10, 20);
NUnit.Framework.Assert.AreEqual(10, dashPattern.GetDash(), 0.0001);
NUnit.Framework.Assert.AreEqual(20, dashPattern.GetGap(), 0.0001);
NUnit.Framework.Assert.AreEqual(-1, dashPattern.GetPhase(), 0.0001);
}
[NUnit.Framework.Test]
public virtual void ConstructorThreeParamsTest() {
PdfDashPattern dashPattern = new PdfDashPattern(10, 20, 30);
NUnit.Framework.Assert.AreEqual(10, dashPattern.GetDash(), 0.0001);
NUnit.Framework.Assert.AreEqual(20, dashPattern.GetGap(), 0.0001);
NUnit.Framework.Assert.AreEqual(30, dashPattern.GetPhase(), 0.0001);
}
}
}

View File

@@ -0,0 +1,375 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.Collections.Generic;
using System.IO;
using TSpdf.Commons.Utils;
using TSpdf.Kernel.Geom;
using TSpdf.Kernel.Pdf.Action;
using TSpdf.Kernel.Pdf.Annot;
using TSpdf.Kernel.Pdf.Filespec;
using TSpdf.Kernel.Pdf.Navigation;
using TSpdf.Kernel.Pdf.Tagging;
using TSpdf.Kernel.Utils;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("IntegrationTest")]
public class PdfDestinationTest : ExtendedTSpdfTest {
public static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/pdf/PdfDestinationTest/";
public static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/pdf/PdfDestinationTest/";
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
CreateOrClearDestinationFolder(destinationFolder);
}
[NUnit.Framework.Test]
public virtual void DestTest01() {
String srcFile = sourceFolder + "simpleNoLinks.pdf";
String outFile = destinationFolder + "destTest01.pdf";
String cmpFile = sourceFolder + "cmp_destTest01.pdf";
PdfDocument document = new PdfDocument(new PdfReader(srcFile), new PdfWriter(outFile));
PdfPage firstPage = document.GetPage(1);
PdfLinkAnnotation linkExplicitDest = new PdfLinkAnnotation(new Rectangle(35, 785, 160, 15));
linkExplicitDest.SetAction(PdfAction.CreateGoTo(PdfExplicitDestination.CreateFit(document.GetPage(2))));
firstPage.AddAnnotation(linkExplicitDest);
PdfLinkAnnotation linkStringDest = new PdfLinkAnnotation(new Rectangle(35, 760, 160, 15));
PdfExplicitDestination destToPage3 = PdfExplicitDestination.CreateFit(document.GetPage(3));
String stringDest = "thirdPageDest";
document.AddNamedDestination(stringDest, destToPage3.GetPdfObject());
linkStringDest.SetAction(PdfAction.CreateGoTo(new PdfStringDestination(stringDest)));
firstPage.AddAnnotation(linkStringDest);
document.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFile, cmpFile, destinationFolder, "diff_"
));
}
[NUnit.Framework.Test]
public virtual void DestCopyingTest01() {
String srcFile = sourceFolder + "simpleWithLinks.pdf";
String outFile = destinationFolder + "destCopyingTest01.pdf";
String cmpFile = sourceFolder + "cmp_destCopyingTest01.pdf";
PdfDocument srcDoc = new PdfDocument(new PdfReader(srcFile));
PdfDocument destDoc = new PdfDocument(new PdfWriter(outFile));
srcDoc.CopyPagesTo(JavaUtil.ArraysAsList(1, 2, 3), destDoc);
destDoc.Close();
srcDoc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFile, cmpFile, destinationFolder, "diff_"
));
}
[NUnit.Framework.Test]
public virtual void DestCopyingTest02() {
String srcFile = sourceFolder + "simpleWithLinks.pdf";
String outFile = destinationFolder + "destCopyingTest02.pdf";
String cmpFile = sourceFolder + "cmp_destCopyingTest02.pdf";
PdfDocument srcDoc = new PdfDocument(new PdfReader(srcFile));
PdfDocument destDoc = new PdfDocument(new PdfWriter(outFile));
srcDoc.CopyPagesTo(JavaUtil.ArraysAsList(1), destDoc);
destDoc.Close();
srcDoc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFile, cmpFile, destinationFolder, "diff_"
));
}
[NUnit.Framework.Test]
public virtual void DestCopyingTest03() {
String srcFile = sourceFolder + "simpleWithLinks.pdf";
String outFile = destinationFolder + "destCopyingTest03.pdf";
String cmpFile = sourceFolder + "cmp_destCopyingTest03.pdf";
PdfDocument srcDoc = new PdfDocument(new PdfReader(srcFile));
PdfDocument destDoc = new PdfDocument(new PdfWriter(outFile));
srcDoc.CopyPagesTo(JavaUtil.ArraysAsList(1, 2), destDoc);
destDoc.Close();
srcDoc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFile, cmpFile, destinationFolder, "diff_"
));
}
[NUnit.Framework.Test]
public virtual void DestCopyingTest04() {
String srcFile = sourceFolder + "simpleWithLinks.pdf";
String outFile = destinationFolder + "destCopyingTest04.pdf";
String cmpFile = sourceFolder + "cmp_destCopyingTest04.pdf";
PdfDocument srcDoc = new PdfDocument(new PdfReader(srcFile));
PdfDocument destDoc = new PdfDocument(new PdfWriter(outFile));
srcDoc.CopyPagesTo(JavaUtil.ArraysAsList(1, 3), destDoc);
destDoc.Close();
srcDoc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFile, cmpFile, destinationFolder, "diff_"
));
}
[NUnit.Framework.Test]
public virtual void DestCopyingTest05() {
String srcFile = sourceFolder + "simpleWithLinks.pdf";
String outFile = destinationFolder + "destCopyingTest05.pdf";
String cmpFile = sourceFolder + "cmp_destCopyingTest05.pdf";
PdfDocument srcDoc = new PdfDocument(new PdfReader(srcFile));
PdfDocument destDoc = new PdfDocument(new PdfWriter(outFile));
srcDoc.CopyPagesTo(JavaUtil.ArraysAsList(1, 2, 3, 1), destDoc);
destDoc.Close();
srcDoc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFile, cmpFile, destinationFolder, "diff_"
));
}
[NUnit.Framework.Test]
public virtual void DestCopyingTest06() {
String srcFile = sourceFolder + "sourceWithNamedDestination.pdf";
String outFile = destinationFolder + "destCopyingTest06.pdf";
String cmpFile = sourceFolder + "cmp_destCopyingTest06.pdf";
PdfDocument srcDoc = new PdfDocument(new PdfReader(srcFile));
PdfDocument destDoc = new PdfDocument(new PdfWriter(outFile));
srcDoc.CopyPagesTo(JavaUtil.ArraysAsList(1, 2, 1), destDoc);
destDoc.Close();
srcDoc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFile, cmpFile, destinationFolder, "diff_"
));
}
[NUnit.Framework.Test]
public virtual void DestCopyingTest07() {
String srcFile = sourceFolder + "sourceStringDestWithPageNumber.pdf";
String outFile = destinationFolder + "destCopyingTest07.pdf";
String cmpFile = sourceFolder + "cmp_destCopyingTest07.pdf";
PdfDocument srcDoc = new PdfDocument(new PdfReader(srcFile));
PdfDocument destDoc = new PdfDocument(new PdfWriter(outFile));
srcDoc.CopyPagesTo(JavaUtil.ArraysAsList(1, 2, 1), destDoc);
destDoc.Close();
srcDoc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFile, cmpFile, destinationFolder, "diff_"
));
}
[NUnit.Framework.Test]
public virtual void StructureDestinationWithoutRemoteIdTest() {
String srcFile = sourceFolder + "customRolesMappingPdf2.pdf";
PdfDocument document = new PdfDocument(new PdfReader(srcFile), new PdfWriter(new MemoryStream()));
PdfStructElem imgElement = new PdfStructElem((PdfDictionary)document.GetPdfObject(13));
try {
PdfAction.CreateGoToR(new PdfStringFS("Some fake destination"), PdfStructureDestination.CreateFit(imgElement
));
NUnit.Framework.Assert.Fail("Exception not thrown");
}
catch (ArgumentException e) {
NUnit.Framework.Assert.AreEqual("Structure destinations shall specify structure element ID in remote go-to actions. Structure element that has no ID is specified instead"
, e.Message);
}
document.Close();
}
[NUnit.Framework.Test]
public virtual void StructureDestination01Test() {
String srcFile = sourceFolder + "customRolesMappingPdf2.pdf";
String outFile = destinationFolder + "structureDestination01Test.pdf";
String cmpFile = sourceFolder + "cmp_structureDestination01Test.pdf";
PdfDocument document = new PdfDocument(new PdfReader(srcFile), new PdfWriter(outFile));
PdfStructElem imgElement = new PdfStructElem((PdfDictionary)document.GetPdfObject(13));
PdfStructureDestination dest = PdfStructureDestination.CreateFit(imgElement);
PdfPage secondPage = document.AddNewPage();
PdfLinkAnnotation linkExplicitDest = new PdfLinkAnnotation(new Rectangle(35, 785, 160, 15));
linkExplicitDest.SetAction(PdfAction.CreateGoTo(dest));
secondPage.AddAnnotation(linkExplicitDest);
document.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFile, cmpFile, destinationFolder, "diff_"
));
}
[NUnit.Framework.Test]
public virtual void StructureDestination02Test() {
String srcFile = sourceFolder + "customRolesMappingPdf2.pdf";
String outFile = destinationFolder + "structureDestination02Test.pdf";
String cmpFile = sourceFolder + "cmp_structureDestination02Test.pdf";
PdfDocument document = new PdfDocument(new PdfReader(srcFile), new PdfWriter(outFile));
PdfStructElem imgElement = new PdfStructElem((PdfDictionary)document.GetPdfObject(13));
PdfStructureDestination dest = PdfStructureDestination.CreateFit(imgElement);
PdfPage secondPage = document.AddNewPage();
PdfPage thirdPage = document.AddNewPage();
PdfLinkAnnotation linkExplicitDest = new PdfLinkAnnotation(new Rectangle(35, 785, 160, 15));
PdfAction gotoStructAction = PdfAction.CreateGoTo(PdfExplicitDestination.CreateFit(thirdPage));
gotoStructAction.Put(PdfName.SD, dest.GetPdfObject());
linkExplicitDest.SetAction(gotoStructAction);
secondPage.AddAnnotation(linkExplicitDest);
document.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFile, cmpFile, destinationFolder, "diff_"
));
}
[NUnit.Framework.Test]
public virtual void MakeDestination01Test() {
String srcFile = sourceFolder + "cmp_structureDestination01Test.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(srcFile));
PdfObject destObj = ((PdfLinkAnnotation)pdfDocument.GetPage(2).GetAnnotations()[0]).GetAction().Get(PdfName
.D);
PdfDestination destWrapper = PdfDestination.MakeDestination(destObj);
NUnit.Framework.Assert.AreEqual(typeof(PdfStructureDestination), destWrapper.GetType());
}
[NUnit.Framework.Test]
public virtual void RemoteGoToDestinationTest01() {
String cmpFile = sourceFolder + "cmp_remoteGoToDestinationTest01.pdf";
String outFile = destinationFolder + "remoteGoToDestinationTest01.pdf";
PdfDocument @out = new PdfDocument(new PdfWriter(outFile));
@out.AddNewPage();
IList<PdfDestination> destinations = new List<PdfDestination>(7);
destinations.Add(PdfExplicitRemoteGoToDestination.CreateFit(1));
destinations.Add(PdfExplicitRemoteGoToDestination.CreateFitH(1, 10));
destinations.Add(PdfExplicitRemoteGoToDestination.CreateFitV(1, 10));
destinations.Add(PdfExplicitRemoteGoToDestination.CreateFitR(1, 10, 10, 10, 10));
destinations.Add(PdfExplicitRemoteGoToDestination.CreateFitB(1));
destinations.Add(PdfExplicitRemoteGoToDestination.CreateFitBH(1, 10));
destinations.Add(PdfExplicitRemoteGoToDestination.CreateFitBV(1, 10));
int y = 785;
foreach (PdfDestination destination in destinations) {
PdfLinkAnnotation linkExplicitDest = new PdfLinkAnnotation(new Rectangle(35, y, 160, 15));
PdfAction action = PdfAction.CreateGoToR(new PdfStringFS("Some fake destination"), destination);
linkExplicitDest.SetAction(action);
@out.GetFirstPage().AddAnnotation(linkExplicitDest);
y -= 20;
}
@out.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFile, cmpFile, destinationFolder, "diff_"
));
}
[NUnit.Framework.Test]
public virtual void RemoteGoToDestinationTest02() {
String cmpFile = sourceFolder + "cmp_remoteGoToDestinationTest02.pdf";
String outFile = destinationFolder + "remoteGoToDestinationTest02.pdf";
PdfDocument @out = new PdfDocument(new PdfWriter(outFile));
@out.AddNewPage();
@out.AddNewPage();
PdfLinkAnnotation linkExplicitDest = new PdfLinkAnnotation(new Rectangle(35, 785, 160, 15));
PdfAction action = PdfAction.CreateGoToR(new PdfStringFS("Some fake destination"), PdfExplicitRemoteGoToDestination
.CreateFitR(2, 10, 10, 10, 10), true);
linkExplicitDest.SetAction(action);
@out.GetFirstPage().AddAnnotation(linkExplicitDest);
@out.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFile, cmpFile, destinationFolder, "diff_"
));
}
[NUnit.Framework.Test]
public virtual void RemoteGoToRIllegalDestinationTest() {
String outFile = destinationFolder + "remoteGoToDestinationTest01.pdf";
PdfDocument document = new PdfDocument(new PdfWriter(outFile));
document.AddNewPage();
document.AddNewPage();
try {
PdfAction.CreateGoToR(new PdfStringFS("Some fake destination"), PdfExplicitDestination.CreateFitB(document
.GetPage(1)));
NUnit.Framework.Assert.Fail("Exception not thrown");
}
catch (ArgumentException e) {
NUnit.Framework.Assert.AreEqual("Explicit destinations shall specify page number in remote go-to actions instead of page dictionary"
, e.Message);
}
document.Close();
}
[NUnit.Framework.Test]
public virtual void RemoteGoToRByIntDestinationTest() {
String cmpFile = sourceFolder + "cmp_remoteGoToRByIntDestinationTest.pdf";
String outFile = destinationFolder + "remoteGoToRByIntDestinationTest.pdf";
PdfDocument @out = new PdfDocument(new PdfWriter(outFile));
@out.AddNewPage();
@out.AddNewPage();
PdfLinkAnnotation linkExplicitDest = new PdfLinkAnnotation(new Rectangle(35, 785, 160, 15));
PdfAction action = PdfAction.CreateGoToR("Some fake destination", 2);
linkExplicitDest.SetAction(action);
@out.GetFirstPage().AddAnnotation(linkExplicitDest);
@out.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFile, cmpFile, destinationFolder, "diff_"
));
}
[NUnit.Framework.Test]
public virtual void RemoteGoToRByStringDestinationTest() {
String cmpFile = sourceFolder + "cmp_remoteGoToRByStringDestinationTest.pdf";
String outFile = destinationFolder + "remoteGoToRByStringDestinationTest.pdf";
PdfDocument @out = new PdfDocument(new PdfWriter(outFile));
@out.AddNewPage();
PdfLinkAnnotation linkExplicitDest = new PdfLinkAnnotation(new Rectangle(35, 785, 160, 15));
PdfAction action = PdfAction.CreateGoToR("Some fake destination", "1");
linkExplicitDest.SetAction(action);
@out.GetFirstPage().AddAnnotation(linkExplicitDest);
@out.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFile, cmpFile, destinationFolder, "diff_"
));
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.INVALID_DESTINATION_TYPE)]
public virtual void RemoteGoToNotValidExplicitDestinationTest() {
String cmpFile = sourceFolder + "cmp_remoteGoToNotValidExplicitDestinationTest.pdf";
String outFile = destinationFolder + "remoteGoToNotValidExplicitDestinationTest.pdf";
PdfDocument document = new PdfDocument(new PdfWriter(outFile));
document.AddNewPage();
PdfLinkAnnotation linkExplicitDest = new PdfLinkAnnotation(new Rectangle(35, 785, 160, 15));
linkExplicitDest.SetAction(PdfAction.CreateGoTo(PdfExplicitRemoteGoToDestination.CreateFit(1)));
document.GetFirstPage().AddAnnotation(linkExplicitDest);
document.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFile, cmpFile, destinationFolder, "diff_"
));
}
[NUnit.Framework.Test]
public virtual void CopyNullDestination() {
using (MemoryStream baos = new MemoryStream()) {
using (PdfDocument pdfDocument = new PdfDocument(new PdfWriter(baos))) {
pdfDocument.AddNewPage();
PdfDestination copiedDestination = pdfDocument.GetCatalog().CopyDestination(null, new Dictionary<PdfPage,
PdfPage>(), pdfDocument);
// We expect null to be returned if the destination to be copied is null
NUnit.Framework.Assert.IsNull(copiedDestination);
}
}
}
}
}

View File

@@ -0,0 +1,150 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: Bruno Lowagie, Paulo Soares, et al.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System.Collections.Generic;
using System.IO;
using TSpdf.Commons.Utils;
using TSpdf.IO.Source;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("IntegrationTest")]
public class PdfDeveloperExtensionTest {
public static readonly PdfDeveloperExtension SIMPLE_EXTENSION_L3 = new PdfDeveloperExtension(new PdfName("Test"
), PdfName.Pdf_Version_1_7, 3);
public static readonly PdfDeveloperExtension SIMPLE_EXTENSION_L5 = new PdfDeveloperExtension(new PdfName("Test"
), PdfName.Pdf_Version_1_7, 5);
public static readonly PdfDeveloperExtension MULTI_EXTENSION_1 = new PdfDeveloperExtension(new PdfName("Test"
), PdfName.Pdf_Version_2_0, 1, "https://example.com", ":2022", true);
public static readonly PdfDeveloperExtension MULTI_EXTENSION_2 = new PdfDeveloperExtension(new PdfName("Test"
), PdfName.Pdf_Version_2_0, 2, "https://example.com", ":2022", true);
[NUnit.Framework.Test]
public virtual void AddSingleValuedExtensionTest() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
using (PdfDocument pdfDoc = new PdfDocument(new PdfWriter(baos))) {
pdfDoc.GetCatalog().AddDeveloperExtension(SIMPLE_EXTENSION_L3);
}
AssertSimpleExtension(baos.ToArray(), SIMPLE_EXTENSION_L3.GetPrefix(), SIMPLE_EXTENSION_L3.GetExtensionLevel
());
}
[NUnit.Framework.Test]
public virtual void AddSingleValuedExtensionOverrideTest() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
using (PdfDocument pdfDoc = new PdfDocument(new PdfWriter(baos))) {
pdfDoc.GetCatalog().AddDeveloperExtension(SIMPLE_EXTENSION_L3);
pdfDoc.GetCatalog().AddDeveloperExtension(SIMPLE_EXTENSION_L5);
}
AssertSimpleExtension(baos.ToArray(), SIMPLE_EXTENSION_L5.GetPrefix(), SIMPLE_EXTENSION_L5.GetExtensionLevel
());
}
[NUnit.Framework.Test]
public virtual void AddSingleValuedExtensionNoOverrideTest() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
using (PdfDocument pdfDoc = new PdfDocument(new PdfWriter(baos))) {
pdfDoc.GetCatalog().AddDeveloperExtension(SIMPLE_EXTENSION_L5);
pdfDoc.GetCatalog().AddDeveloperExtension(SIMPLE_EXTENSION_L3);
}
AssertSimpleExtension(baos.ToArray(), SIMPLE_EXTENSION_L5.GetPrefix(), SIMPLE_EXTENSION_L5.GetExtensionLevel
());
}
[NUnit.Framework.Test]
public virtual void AddMultivaluedExtensionTest() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
using (PdfDocument pdfDoc = new PdfDocument(new PdfWriter(baos))) {
pdfDoc.GetCatalog().AddDeveloperExtension(MULTI_EXTENSION_1);
}
AssertMultiExtension(baos.ToArray(), MULTI_EXTENSION_1.GetPrefix(), JavaCollectionsUtil.SingletonList(MULTI_EXTENSION_1
.GetExtensionLevel()));
}
[NUnit.Framework.Test]
public virtual void AddMultivaluedExtensionNoDuplicateTest() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
using (PdfDocument pdfDoc = new PdfDocument(new PdfWriter(baos))) {
pdfDoc.GetCatalog().AddDeveloperExtension(MULTI_EXTENSION_1);
pdfDoc.GetCatalog().AddDeveloperExtension(MULTI_EXTENSION_1);
}
AssertMultiExtension(baos.ToArray(), MULTI_EXTENSION_1.GetPrefix(), JavaCollectionsUtil.SingletonList(MULTI_EXTENSION_1
.GetExtensionLevel()));
}
[NUnit.Framework.Test]
public virtual void AddMultivaluedExtensionNoOverrideTest() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
using (PdfDocument pdfDoc = new PdfDocument(new PdfWriter(baos))) {
pdfDoc.GetCatalog().AddDeveloperExtension(MULTI_EXTENSION_1);
pdfDoc.GetCatalog().AddDeveloperExtension(MULTI_EXTENSION_2);
}
AssertMultiExtension(baos.ToArray(), MULTI_EXTENSION_1.GetPrefix(), JavaUtil.ArraysAsList(MULTI_EXTENSION_1
.GetExtensionLevel(), MULTI_EXTENSION_2.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
(prefix);
NUnit.Framework.Assert.AreEqual(expectedLevel, extDict.GetAsNumber(PdfName.ExtensionLevel).IntValue());
}
}
private void AssertMultiExtension(byte[] docData, PdfName prefix, ICollection<int> expectedLevels) {
ICollection<int> seen = new HashSet<int>();
using (PdfDocument pdfDoc = new PdfDocument(new PdfReader(new MemoryStream(docData)))) {
PdfArray exts = pdfDoc.GetCatalog().GetPdfObject().GetAsDictionary(PdfName.Extensions).GetAsArray(prefix);
for (int i = 0; i < exts.Size(); i++) {
int level = exts.GetAsDictionary(i).GetAsInt(PdfName.ExtensionLevel).Value;
NUnit.Framework.Assert.IsTrue(expectedLevels.Contains(level), "Level " + level + " is not in expected level list"
);
NUnit.Framework.Assert.IsFalse(seen.Contains(level), "Level " + level + " appears multiple times");
seen.Add(level);
}
}
}
}
}

View File

@@ -0,0 +1,334 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.Collections.Generic;
using TSpdf.Commons.Utils;
using TSpdf.IO.Source;
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("UnitTest")]
public class PdfDictionaryTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void TestEntrySet() {
PdfDocument doc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
PdfDictionary dict = new PdfDictionary();
dict.Put(new PdfName("1"), new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
dict.Put(new PdfName("2"), new PdfNumber(2).MakeIndirect(doc).GetIndirectReference());
dict.Put(new PdfName("3"), new PdfNumber(3).MakeIndirect(doc));
dict.Put(new PdfName("4"), new PdfNumber(4).MakeIndirect(doc));
dict.Put(new PdfName("5"), new PdfNumber(5));
dict.Put(new PdfName("6"), new PdfNumber(6));
IList<int> nums = new List<int>(JavaUtil.ArraysAsList(1, 2, 3, 4, 5, 6));
foreach (KeyValuePair<PdfName, PdfObject> e in dict.EntrySet()) {
NUnit.Framework.Assert.AreEqual(e.Key.ToString(), "/" + e.Value);
if (!nums.Remove(Convert.ToInt32(((PdfNumber)e.Value).IntValue()))) {
NUnit.Framework.Assert.Fail("Element not found");
}
}
}
[NUnit.Framework.Test]
public virtual void TestEntrySetContains() {
PdfDocument doc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
PdfDictionary dict = new PdfDictionary();
dict.Put(new PdfName("1"), new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
dict.Put(new PdfName("2"), new PdfNumber(2).MakeIndirect(doc).GetIndirectReference());
dict.Put(new PdfName("3"), new PdfNumber(3).MakeIndirect(doc));
dict.Put(new PdfName("4"), new PdfNumber(4).MakeIndirect(doc));
dict.Put(new PdfName("5"), new PdfNumber(5));
dict.Put(new PdfName("6"), new PdfNumber(6));
foreach (KeyValuePair<PdfName, PdfObject> e in dict.EntrySet()) {
NUnit.Framework.Assert.IsTrue(dict.EntrySet().Contains(e));
}
}
[NUnit.Framework.Test]
public virtual void TestEntrySetRemove() {
PdfDocument doc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
PdfDictionary dict = new PdfDictionary();
dict.Put(new PdfName("1"), new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
dict.Put(new PdfName("2"), new PdfNumber(2).MakeIndirect(doc).GetIndirectReference());
dict.Put(new PdfName("3"), new PdfNumber(3).MakeIndirect(doc));
dict.Put(new PdfName("4"), new PdfNumber(4).MakeIndirect(doc));
dict.Put(new PdfName("5"), new PdfNumber(5));
dict.Put(new PdfName("6"), new PdfNumber(6));
IList<KeyValuePair<PdfName, PdfObject>> toRemove = new List<KeyValuePair<PdfName, PdfObject>>();
foreach (KeyValuePair<PdfName, PdfObject> e in dict.EntrySet()) {
toRemove.Add(e);
}
foreach (KeyValuePair<PdfName, PdfObject> e in toRemove) {
NUnit.Framework.Assert.IsTrue(dict.EntrySet().Remove(e));
}
NUnit.Framework.Assert.AreEqual(0, dict.EntrySet().Count);
NUnit.Framework.Assert.AreEqual(0, dict.Values().Count);
NUnit.Framework.Assert.AreEqual(0, dict.Size());
}
[NUnit.Framework.Test]
public virtual void TestEntrySetRemove2() {
PdfDocument doc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
PdfDictionary dict = new PdfDictionary();
dict.Put(new PdfName("1"), new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
dict.Put(new PdfName("2"), new PdfNumber(2).MakeIndirect(doc).GetIndirectReference());
dict.Put(new PdfName("3"), new PdfNumber(3).MakeIndirect(doc));
dict.Put(new PdfName("4"), new PdfNumber(4).MakeIndirect(doc));
dict.Put(new PdfName("5"), new PdfNumber(5));
dict.Put(new PdfName("6"), new PdfNumber(6));
PdfDictionary dict2 = new PdfDictionary();
dict2.Put(new PdfName("1"), new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
dict2.Put(new PdfName("2"), new PdfNumber(2).MakeIndirect(doc).GetIndirectReference());
dict2.Put(new PdfName("3"), new PdfNumber(3).MakeIndirect(doc));
dict2.Put(new PdfName("4"), new PdfNumber(4).MakeIndirect(doc));
dict2.Put(new PdfName("5"), new PdfNumber(5));
dict2.Put(new PdfName("6"), new PdfNumber(6));
foreach (KeyValuePair<PdfName, PdfObject> e in dict2.EntrySet()) {
NUnit.Framework.Assert.IsTrue(dict.EntrySet().Remove(e));
}
NUnit.Framework.Assert.AreEqual(0, dict.EntrySet().Count);
NUnit.Framework.Assert.AreEqual(0, dict.Values().Count);
NUnit.Framework.Assert.AreEqual(0, dict.Size());
}
[NUnit.Framework.Test]
public virtual void TestEntrySetRemoveAll() {
PdfDocument doc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
PdfDictionary dict = new PdfDictionary();
dict.Put(new PdfName("1"), new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
dict.Put(new PdfName("2"), new PdfNumber(2).MakeIndirect(doc).GetIndirectReference());
dict.Put(new PdfName("3"), new PdfNumber(3).MakeIndirect(doc));
dict.Put(new PdfName("4"), new PdfNumber(4).MakeIndirect(doc));
dict.Put(new PdfName("5"), new PdfNumber(5));
dict.Put(new PdfName("6"), new PdfNumber(6));
IList<KeyValuePair<PdfName, PdfObject>> toRemove = new List<KeyValuePair<PdfName, PdfObject>>();
foreach (KeyValuePair<PdfName, PdfObject> e in dict.EntrySet()) {
toRemove.Add(e);
}
dict.EntrySet().RemoveAll(toRemove);
NUnit.Framework.Assert.AreEqual(0, dict.EntrySet().Count);
NUnit.Framework.Assert.AreEqual(0, dict.Values().Count);
NUnit.Framework.Assert.AreEqual(0, dict.Size());
}
[NUnit.Framework.Test]
public virtual void TestEntrySetRemoveAll2() {
PdfDocument doc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
PdfDictionary dict = new PdfDictionary();
dict.Put(new PdfName("1"), new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
dict.Put(new PdfName("2"), new PdfNumber(2).MakeIndirect(doc).GetIndirectReference());
dict.Put(new PdfName("3"), new PdfNumber(3).MakeIndirect(doc));
dict.Put(new PdfName("4"), new PdfNumber(4).MakeIndirect(doc));
dict.Put(new PdfName("5"), new PdfNumber(5));
dict.Put(new PdfName("6"), new PdfNumber(6));
PdfDictionary dict2 = new PdfDictionary();
dict2.Put(new PdfName("1"), new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
dict2.Put(new PdfName("2"), new PdfNumber(2).MakeIndirect(doc).GetIndirectReference());
dict2.Put(new PdfName("3"), new PdfNumber(3).MakeIndirect(doc));
dict2.Put(new PdfName("4"), new PdfNumber(4).MakeIndirect(doc));
dict2.Put(new PdfName("5"), new PdfNumber(5));
dict2.Put(new PdfName("6"), new PdfNumber(6));
dict.EntrySet().RemoveAll(dict2.EntrySet());
NUnit.Framework.Assert.AreEqual(0, dict.EntrySet().Count);
NUnit.Framework.Assert.AreEqual(0, dict.Values().Count);
NUnit.Framework.Assert.AreEqual(0, dict.Size());
}
[NUnit.Framework.Test]
public virtual void TestEntrySetRetainAll() {
PdfDocument doc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
PdfDictionary dict = new PdfDictionary();
dict.Put(new PdfName("1"), new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
dict.Put(new PdfName("2"), new PdfNumber(2).MakeIndirect(doc).GetIndirectReference());
dict.Put(new PdfName("3"), new PdfNumber(3).MakeIndirect(doc));
dict.Put(new PdfName("4"), new PdfNumber(4).MakeIndirect(doc));
dict.Put(new PdfName("5"), new PdfNumber(5));
dict.Put(new PdfName("6"), new PdfNumber(6));
IList<KeyValuePair<PdfName, PdfObject>> toRemove = new List<KeyValuePair<PdfName, PdfObject>>();
int i = 0;
foreach (KeyValuePair<PdfName, PdfObject> e in dict.EntrySet()) {
toRemove.Add(e);
if (i++ > 2) {
break;
}
}
dict.EntrySet().RetainAll(toRemove);
NUnit.Framework.Assert.AreEqual(4, dict.EntrySet().Count);
NUnit.Framework.Assert.AreEqual(4, dict.Values().Count);
NUnit.Framework.Assert.AreEqual(4, dict.Size());
}
[NUnit.Framework.Test]
public virtual void TestEntrySetClear() {
PdfDocument doc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
PdfDictionary dict = new PdfDictionary();
dict.Put(new PdfName("1"), new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
dict.Put(new PdfName("2"), new PdfNumber(2).MakeIndirect(doc).GetIndirectReference());
dict.Put(new PdfName("3"), new PdfNumber(3).MakeIndirect(doc));
dict.Put(new PdfName("4"), new PdfNumber(4).MakeIndirect(doc));
dict.Put(new PdfName("5"), new PdfNumber(5));
dict.Put(new PdfName("6"), new PdfNumber(6));
dict.EntrySet().Clear();
NUnit.Framework.Assert.AreEqual(0, dict.EntrySet().Count);
NUnit.Framework.Assert.AreEqual(0, dict.Values().Count);
NUnit.Framework.Assert.AreEqual(0, dict.Size());
}
[NUnit.Framework.Test]
public virtual void TestValues() {
PdfDocument doc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
PdfDictionary dict = new PdfDictionary();
dict.Put(new PdfName("1"), new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
dict.Put(new PdfName("2"), new PdfNumber(2).MakeIndirect(doc).GetIndirectReference());
dict.Put(new PdfName("3"), new PdfNumber(3).MakeIndirect(doc));
dict.Put(new PdfName("4"), new PdfNumber(4).MakeIndirect(doc));
dict.Put(new PdfName("5"), new PdfNumber(5));
dict.Put(new PdfName("6"), new PdfNumber(6));
IList<int> nums = new List<int>(JavaUtil.ArraysAsList(1, 2, 3, 4, 5, 6));
foreach (KeyValuePair<PdfName, PdfObject> e in dict.EntrySet()) {
NUnit.Framework.Assert.AreEqual(e.Key.ToString(), "/" + e.Value);
if (!nums.Remove(Convert.ToInt32(((PdfNumber)e.Value).IntValue()))) {
NUnit.Framework.Assert.Fail("Element not found");
}
}
}
[NUnit.Framework.Test]
public virtual void TestValuesContains() {
PdfDocument doc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
PdfDictionary dict = new PdfDictionary();
dict.Put(new PdfName("1"), new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
dict.Put(new PdfName("2"), new PdfNumber(2).MakeIndirect(doc).GetIndirectReference());
dict.Put(new PdfName("3"), new PdfNumber(3).MakeIndirect(doc));
dict.Put(new PdfName("4"), new PdfNumber(4).MakeIndirect(doc));
dict.Put(new PdfName("5"), new PdfNumber(5));
dict.Put(new PdfName("6"), new PdfNumber(6));
foreach (PdfObject v in dict.Values()) {
NUnit.Framework.Assert.IsTrue(dict.Values().Contains(v));
}
}
[NUnit.Framework.Test]
public virtual void TestValuesIndirectContains() {
PdfDocument doc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
PdfDictionary dict = new PdfDictionary();
dict.Put(new PdfName("1"), new PdfNumber(1).MakeIndirect(doc).GetIndirectReference());
dict.Put(new PdfName("2"), new PdfNumber(2).MakeIndirect(doc).GetIndirectReference());
dict.Put(new PdfName("3"), new PdfNumber(3).MakeIndirect(doc));
dict.Put(new PdfName("4"), new PdfNumber(4).MakeIndirect(doc));
dict.Put(new PdfName("5"), new PdfNumber(5));
dict.Put(new PdfName("6"), new PdfNumber(6));
NUnit.Framework.Assert.IsTrue(dict.Values().Contains(dict.Get(new PdfName("1"), false)));
NUnit.Framework.Assert.IsTrue(dict.Values().Contains(dict.Get(new PdfName("2"), false)));
NUnit.Framework.Assert.IsTrue(dict.Values().Contains(dict.Get(new PdfName("3")).GetIndirectReference()));
NUnit.Framework.Assert.IsTrue(dict.Values().Contains(dict.Get(new PdfName("4")).GetIndirectReference()));
}
[NUnit.Framework.Test]
public virtual void TestPdfNamesFetching() {
byte[][] namesBytes = new byte[][] { new byte[] {
// /#C3#9Cberschrift_1
35, 67, 51, 35, 57, 67, 98, 101, 114, 115, 99, 104, 114, 105, 102, 116, 95, 49 }, new byte[] {
// /#C3#9Cberschrift_2
35, 67, 51, 35, 57, 67, 98, 101, 114, 115, 99, 104, 114, 105, 102, 116, 95, 50 }, new byte[] {
// /Article
65, 114, 116, 105, 99, 108, 101 }, new byte[] {
// /Bildunterschrift
66, 105, 108, 100, 117, 110, 116, 101, 114, 115, 99, 104, 114, 105, 102, 116 }, new byte[] {
// /NormalParagraphStyle
78, 111, 114, 109, 97, 108, 80, 97, 114, 97, 103, 114, 97, 112, 104, 83, 116, 121, 108, 101 }, new byte[]
{
// /Story
83, 116, 111, 114, 121 }, new byte[] {
// /TOC-1
84, 79, 67, 45, 49 }, new byte[] {
// /TOC-2-2
84, 79, 67, 45, 50, 45, 50 }, new byte[] {
// /TOC-Head
84, 79, 67, 45, 72, 101, 97, 100 }, new byte[] {
// /Tabelle
84, 97, 98, 101, 108, 108, 101 }, new byte[] {
// /Tabelle_Head
84, 97, 98, 101, 108, 108, 101, 95, 72, 101, 97, 100 }, new byte[] {
// /Tabelle_fett
84, 97, 98, 101, 108, 108, 101, 95, 102, 101, 116, 116 }, new byte[] {
// /Text_INFO
84, 101, 120, 116, 95, 73, 78, 70, 79 }, new byte[] {
// /Text_Info_Head
84, 101, 120, 116, 95, 73, 110, 102, 111, 95, 72, 101, 97, 100 }, new byte[] {
// /Textk#C3#B6rper
84, 101, 120, 116, 107, 35, 67, 51, 35, 66, 54, 114, 112, 101, 114 }, new byte[] {
// /Textk#C3#B6rper-Erstzeile
84, 101, 120, 116, 107, 35, 67, 51, 35, 66, 54, 114, 112, 101, 114, 45, 69, 114, 115, 116, 122, 101, 105,
108, 101 }, new byte[] {
// /Textk#C3#B6rper_Back
84, 101, 120, 116, 107, 35, 67, 51, 35, 66, 54, 114, 112, 101, 114, 95, 66, 97, 99, 107 }, new byte[] {
// /_No_paragraph_style_
95, 78, 111, 95, 112, 97, 114, 97, 103, 114, 97, 112, 104, 95, 115, 116, 121, 108, 101, 95 } };
bool[] haveValue = new bool[] { true, true, false, true, true, true, false, false, false, false, false, false
, false, false, false, false, false, false };
IList<PdfName> names = new List<PdfName>();
for (int i = 0; i < namesBytes.Length; i++) {
byte[] b = namesBytes[i];
PdfName n = new PdfName(b);
names.Add(n);
if (haveValue[i]) {
n.GenerateValue();
}
}
PdfDictionary dict = new PdfDictionary();
foreach (PdfName name in names) {
dict.Put(name, new PdfName("dummy"));
}
PdfName expectedToContain = new PdfName("Article");
bool found = false;
foreach (PdfName pdfName in dict.KeySet()) {
found = pdfName.Equals(expectedToContain);
if (found) {
break;
}
}
NUnit.Framework.Assert.IsTrue(found);
NUnit.Framework.Assert.IsTrue(dict.ContainsKey(expectedToContain));
}
}
}

View File

@@ -0,0 +1,130 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("IntegrationTest")]
public class PdfDictionaryTokenizerTest : ExtendedTSpdfTest {
public static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/pdf/PdfDictionaryTokenizerTest/";
public static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/pdf/PdfDictionaryTokenizerTest/";
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
CreateOrClearDestinationFolder(destinationFolder);
}
[NUnit.Framework.Test]
public virtual void ReaderTurnsCorrectlyNotWellFormattedValueInDictionary_01() {
String inPath = sourceFolder + "documentWithMalformedNumberOnDictionary.pdf";
String EXPECTED = "-12.";
/*
The following is the content included in the pdf file
<</Ascent 800
/CapHeight 700
/Descent -200
/Flags 32
/FontBBox[-631 -462 1632 1230]
/FontFamily(FreeSans)
/FontFile2 8 0 R
/FontName/XVVAXW+FreeSans
/FontWeight 400
/ItalicAngle -12.-23
/StemV 80
/Type/FontDescriptor>>
*/
// ItalicAngle -12.-23 turns into -12.
String result = GetItalicAngleValue(inPath);
NUnit.Framework.Assert.AreEqual(EXPECTED, result);
}
[NUnit.Framework.Test]
public virtual void ReaderTurnsCorrectlyNotWellFormattedValueInDictionary_02() {
String inPath = sourceFolder + "documentWithMalformedNumberOnDictionary2.pdf";
String EXPECTED = "-12.";
/*
The following is the content included in the pdf file
<</Ascent 800
/CapHeight 700
/Descent -200
/Flags 32
/FontBBox[-631 -462 1632 1230]
/FontFamily(FreeSans)
/FontFile2 8 0 R
/FontName/XVVAXW+FreeSans
/FontWeight 400
/StemV 80
/Type/FontDescriptor
/ItalicAngle -12.-23>>
*/
// ItalicAngle -12.-23 turns into -12.
String result = GetItalicAngleValue(inPath);
NUnit.Framework.Assert.AreEqual(EXPECTED, result);
}
private String GetItalicAngleValue(String inPath) {
String result = "";
PdfReader pdfR = new PdfReader(inPath);
PdfDocument attachmentPDF = new PdfDocument(pdfR);
int max = attachmentPDF.GetNumberOfPdfObjects();
for (int i = 0; i < max; i++) {
PdfObject obj = attachmentPDF.GetPdfObject(i);
if (obj != null) {
PdfDictionary pdfDict = (PdfDictionary)obj;
PdfObject x = pdfDict.Get(PdfName.Type);
if (x != null && x.Equals(PdfName.FontDescriptor)) {
PdfObject italicAngle = pdfDict.Get(PdfName.ItalicAngle);
result = italicAngle.ToString();
}
}
}
attachmentPDF.Close();
return result;
}
}
}

View File

@@ -0,0 +1,69 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.Kernel.Logs;
using TSpdf.Kernel.Utils;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("IntegrationTest")]
public class PdfDocumentAppendModeTest : ExtendedTSpdfTest {
public static readonly String DESTINATION_FOLDER = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/pdf/PdfDocumentAppendModeTest/";
public static readonly String SOURCE_FOLDER = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/pdf/PdfDocumentAppendModeTest/";
[NUnit.Framework.OneTimeSetUp]
public static void SetUp() {
CreateDestinationFolder(DESTINATION_FOLDER);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.FULL_COMPRESSION_APPEND_MODE_XREF_TABLE_INCONSISTENCY)]
public virtual void TestAppendModeWithFullCompressionRequestedWhenOriginalDocumentHasXrefTable() {
String inFile = SOURCE_FOLDER + "documentWithXrefTable.pdf";
String outFile = DESTINATION_FOLDER + "documentWithXrefTableAfterAppending.pdf";
String cmpFile = SOURCE_FOLDER + "cmp_documentWithXrefTableAfterAppending.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(inFile), new PdfWriter(outFile, new WriterProperties
().SetFullCompressionMode(true)), new StampingProperties().UseAppendMode());
pdfDocument.AddNewPage();
pdfDocument.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFile, cmpFile, DESTINATION_FOLDER));
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.FULL_COMPRESSION_APPEND_MODE_XREF_STREAM_INCONSISTENCY)]
public virtual void TestAppendModeWithFullCompressionSetToFalseWhenOriginalDocumentHasXrefStream() {
String inFile = SOURCE_FOLDER + "documentWithXrefStream.pdf";
String outFile = DESTINATION_FOLDER + "documentWithXrefStreamAfterAppending.pdf";
String cmpFile = SOURCE_FOLDER + "cmp_documentWithXrefStreamAfterAppending.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(inFile), new PdfWriter(outFile, new WriterProperties
().SetFullCompressionMode(false)), new StampingProperties().UseAppendMode());
pdfDocument.AddNewPage();
pdfDocument.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFile, cmpFile, DESTINATION_FOLDER));
}
}
}

View File

@@ -0,0 +1,355 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.IO;
using TSpdf.Commons.Bouncycastle.Crypto;
using TSpdf.IO.Source;
using TSpdf.Kernel.Exceptions;
using TSpdf.Kernel.Pdf.Canvas;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.Kernel.Pdf {
/// <author>Michael Demey</author>
[NUnit.Framework.Category("IntegrationTest")]
public class PdfDocumentIdTest : ExtendedTSpdfTest {
public static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/pdf/PdfDocumentTestID/";
public static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/pdf/PdfDocumentTestID/";
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
CreateOrClearDestinationFolder(destinationFolder);
}
[NUnit.Framework.Test]
public virtual void ChangeIdTest() {
MemoryStream baos = new MemoryStream();
String value = "Modified ID 1234";
WriterProperties writerProperties = new WriterProperties();
writerProperties.SetModifiedDocumentId(new PdfString((value)));
PdfWriter writer = new PdfWriter(baos, writerProperties);
PdfDocument pdfDocument = new PdfDocument(writer);
pdfDocument.AddNewPage();
pdfDocument.Close();
byte[] documentBytes = baos.ToArray();
baos.Dispose();
PdfReader reader = new PdfReader(new MemoryStream(documentBytes));
pdfDocument = new PdfDocument(reader);
PdfArray idArray = pdfDocument.GetTrailer().GetAsArray(PdfName.ID);
NUnit.Framework.Assert.IsNotNull(idArray);
String extractedValue = idArray.GetAsString(1).GetValue();
pdfDocument.Close();
NUnit.Framework.Assert.AreEqual(value, extractedValue);
}
[NUnit.Framework.Test]
public virtual void ChangeIdTest02() {
MemoryStream baos = new MemoryStream();
IIDigest md5;
try {
md5 = TSpdf.Bouncycastleconnector.BouncyCastleFactoryCreator.GetFactory().CreateIDigest("MD5");
}
catch (Exception e) {
throw new PdfException(e);
}
PdfString initialId = new PdfString(md5.Digest("Initial ID 56789".GetBytes()));
PdfWriter writer = new PdfWriter(baos, new WriterProperties().SetInitialDocumentId(initialId));
PdfDocument pdfDocument = new PdfDocument(writer);
pdfDocument.AddNewPage();
pdfDocument.Close();
byte[] documentBytes = baos.ToArray();
baos.Dispose();
PdfReader reader = new PdfReader(new MemoryStream(documentBytes));
pdfDocument = new PdfDocument(reader);
PdfArray idArray = pdfDocument.GetTrailer().GetAsArray(PdfName.ID);
NUnit.Framework.Assert.IsNotNull(idArray);
PdfString extractedString = idArray.GetAsString(1);
pdfDocument.Close();
NUnit.Framework.Assert.AreEqual(initialId, extractedString);
}
[NUnit.Framework.Test]
public virtual void ChangeIdTest03() {
MemoryStream baosInitial = new MemoryStream();
MemoryStream baosModified = new MemoryStream();
IIDigest md5;
try {
md5 = TSpdf.Bouncycastleconnector.BouncyCastleFactoryCreator.GetFactory().CreateIDigest("MD5");
}
catch (Exception e) {
throw new PdfException(e);
}
PdfString initialId = new PdfString(md5.Digest("Initial ID 56789".GetBytes()));
PdfString modifiedId = new PdfString("Modified ID 56789");
PdfWriter writer = new PdfWriter(baosInitial, new WriterProperties().SetInitialDocumentId(initialId).SetModifiedDocumentId
(modifiedId));
PdfDocument pdfDocument = new PdfDocument(writer);
pdfDocument.AddNewPage();
pdfDocument.Close();
PdfReader reader = new PdfReader(new RandomAccessSourceFactory().CreateSource(baosInitial.ToArray()), new
ReaderProperties());
pdfDocument = new PdfDocument(reader);
PdfArray idArray = pdfDocument.GetTrailer().GetAsArray(PdfName.ID);
pdfDocument.Close();
NUnit.Framework.Assert.IsNotNull(idArray);
PdfString extractedInitialValue = idArray.GetAsString(0);
NUnit.Framework.Assert.AreEqual(initialId, extractedInitialValue);
PdfString extractedModifiedValue = idArray.GetAsString(1);
NUnit.Framework.Assert.AreEqual(modifiedId, extractedModifiedValue);
pdfDocument = new PdfDocument(new PdfReader(new RandomAccessSourceFactory().CreateSource(baosInitial.ToArray
()), new ReaderProperties()), new PdfWriter(baosModified));
new PdfCanvas(pdfDocument.AddNewPage()).SaveState().LineTo(100, 100).MoveTo(100, 100).Stroke().RestoreState
();
pdfDocument.Close();
reader = new PdfReader(new RandomAccessSourceFactory().CreateSource(baosModified.ToArray()), new ReaderProperties
());
pdfDocument = new PdfDocument(reader);
idArray = pdfDocument.GetTrailer().GetAsArray(PdfName.ID);
pdfDocument.Close();
NUnit.Framework.Assert.IsNotNull(idArray);
extractedInitialValue = idArray.GetAsString(0);
NUnit.Framework.Assert.AreEqual(initialId, extractedInitialValue);
extractedModifiedValue = idArray.GetAsString(1);
NUnit.Framework.Assert.AreNotEqual(modifiedId, extractedModifiedValue);
}
[NUnit.Framework.Test]
public virtual void FetchReaderIdTest() {
MemoryStream baos = new MemoryStream();
IIDigest md5;
try {
md5 = TSpdf.Bouncycastleconnector.BouncyCastleFactoryCreator.GetFactory().CreateIDigest("MD5");
}
catch (Exception e) {
throw new PdfException(e);
}
PdfString initialId = new PdfString(md5.Digest("Initial ID 56789".GetBytes()));
PdfWriter writer = new PdfWriter(baos, new WriterProperties().SetInitialDocumentId(initialId));
PdfDocument pdfDocument = new PdfDocument(writer);
pdfDocument.AddNewPage();
pdfDocument.Close();
byte[] documentBytes = baos.ToArray();
baos.Dispose();
PdfReader reader = new PdfReader(new MemoryStream(documentBytes));
pdfDocument = new PdfDocument(reader);
String firstOriginalId = TSpdf.Commons.Utils.JavaUtil.GetStringForBytes(reader.GetOriginalFileId());
String secondOriginalId = TSpdf.Commons.Utils.JavaUtil.GetStringForBytes(reader.GetOriginalFileId());
String firstModifiedId = TSpdf.Commons.Utils.JavaUtil.GetStringForBytes(reader.GetModifiedFileId());
String secondModifiedId = TSpdf.Commons.Utils.JavaUtil.GetStringForBytes(reader.GetModifiedFileId());
NUnit.Framework.Assert.AreEqual(firstOriginalId, secondOriginalId);
NUnit.Framework.Assert.AreEqual(firstModifiedId, secondModifiedId);
}
[NUnit.Framework.Test]
public virtual void WriterPropertiesPriorityTest() {
MemoryStream baos = new MemoryStream();
IIDigest md5;
try {
md5 = TSpdf.Bouncycastleconnector.BouncyCastleFactoryCreator.GetFactory().CreateIDigest("MD5");
}
catch (Exception e) {
throw new PdfException(e);
}
PdfString originalId = new PdfString(md5.Digest("Initial ID 01234".GetBytes()));
PdfString modifiedId = new PdfString(md5.Digest("Modified ID 56789".GetBytes()));
PdfWriter writer = new PdfWriter(baos, new WriterProperties().SetInitialDocumentId(originalId).SetModifiedDocumentId
(modifiedId));
PdfDocument pdfDocument = new PdfDocument(writer);
pdfDocument.AddNewPage();
pdfDocument.Close();
byte[] documentBytes = baos.ToArray();
baos.Dispose();
PdfString newOriginalId = new PdfString(md5.Digest("Initial ID 98765".GetBytes()));
PdfString newModifiedId = new PdfString(md5.Digest("Modified ID 43210".GetBytes()));
PdfReader reader = new PdfReader(new MemoryStream(documentBytes));
PdfWriter newWriter = new PdfWriter(new MemoryStream(), new WriterProperties().SetInitialDocumentId(newOriginalId
).SetModifiedDocumentId(newModifiedId));
pdfDocument = new PdfDocument(reader, newWriter);
String extractedOriginalId = pdfDocument.GetOriginalDocumentId().GetValue();
String extractedModifiedId = pdfDocument.GetModifiedDocumentId().GetValue();
pdfDocument.Close();
NUnit.Framework.Assert.AreEqual(extractedOriginalId, newOriginalId.GetValue());
NUnit.Framework.Assert.AreEqual(extractedModifiedId, newModifiedId.GetValue());
}
[NUnit.Framework.Test]
public virtual void ReadPdfWithTwoStringIdsTest() {
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + "pdfWithTwoStringIds.pdf"));
String originalId = null;
String modifiedId = null;
if (pdfDocument.GetOriginalDocumentId() != null) {
originalId = pdfDocument.GetOriginalDocumentId().GetValue();
}
if (pdfDocument.GetModifiedDocumentId() != null) {
modifiedId = pdfDocument.GetModifiedDocumentId().GetValue();
}
pdfDocument.Close();
NUnit.Framework.Assert.IsNotNull(originalId);
NUnit.Framework.Assert.IsNotNull(modifiedId);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.DOCUMENT_IDS_ARE_CORRUPTED)]
public virtual void ReadPdfWithTwoNumberIdsTest() {
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + "pdfWithTwoNumberIds.pdf"));
String originalId = null;
String modifiedId = null;
if (pdfDocument.GetOriginalDocumentId() != null) {
originalId = pdfDocument.GetOriginalDocumentId().GetValue();
}
if (pdfDocument.GetModifiedDocumentId() != null) {
modifiedId = pdfDocument.GetModifiedDocumentId().GetValue();
}
pdfDocument.Close();
NUnit.Framework.Assert.IsNull(originalId);
NUnit.Framework.Assert.IsNull(modifiedId);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.DOCUMENT_IDS_ARE_CORRUPTED)]
public virtual void ReadPdfWithOneNumberOneStringIdsTest() {
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + "pdfWithOneNumberOneStringIds.pdf")
);
String originalId = null;
String modifiedId = null;
if (pdfDocument.GetOriginalDocumentId() != null) {
originalId = pdfDocument.GetOriginalDocumentId().GetValue();
}
if (pdfDocument.GetModifiedDocumentId() != null) {
modifiedId = pdfDocument.GetModifiedDocumentId().GetValue();
}
pdfDocument.Close();
NUnit.Framework.Assert.IsNull(originalId);
NUnit.Framework.Assert.IsNotNull(modifiedId);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.DOCUMENT_IDS_ARE_CORRUPTED)]
public virtual void ReadPdfWithOneStringIdValueTest() {
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + "pdfWithOneStringId.pdf"));
String originalId = null;
String modifiedId = null;
if (pdfDocument.GetOriginalDocumentId() != null) {
originalId = pdfDocument.GetOriginalDocumentId().GetValue();
}
if (pdfDocument.GetModifiedDocumentId() != null) {
modifiedId = pdfDocument.GetModifiedDocumentId().GetValue();
}
pdfDocument.Close();
NUnit.Framework.Assert.IsNull(originalId);
NUnit.Framework.Assert.IsNull(modifiedId);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.DOCUMENT_IDS_ARE_CORRUPTED)]
public virtual void ReadPdfWithOneNumberIdValueTest() {
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + "pdfWithOneNumberId.pdf"));
String originalId = null;
String modifiedId = null;
if (pdfDocument.GetOriginalDocumentId() != null) {
originalId = pdfDocument.GetOriginalDocumentId().GetValue();
}
if (pdfDocument.GetModifiedDocumentId() != null) {
modifiedId = pdfDocument.GetModifiedDocumentId().GetValue();
}
pdfDocument.Close();
NUnit.Framework.Assert.IsNull(originalId);
NUnit.Framework.Assert.IsNull(modifiedId);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.DOCUMENT_IDS_ARE_CORRUPTED)]
public virtual void ReadPdfWithNoIdTest() {
PdfReader reader = new PdfReader(sourceFolder + "pdfWithNoId.pdf");
PdfDocument pdfDocument = new PdfDocument(reader);
String originalId = null;
String modifiedId = null;
if (pdfDocument.GetOriginalDocumentId() != null) {
originalId = pdfDocument.GetOriginalDocumentId().GetValue();
}
if (pdfDocument.GetModifiedDocumentId() != null) {
modifiedId = pdfDocument.GetModifiedDocumentId().GetValue();
}
pdfDocument.Close();
NUnit.Framework.Assert.IsNull(originalId);
NUnit.Framework.Assert.IsNull(modifiedId);
NUnit.Framework.Assert.AreEqual(0, reader.GetOriginalFileId().Length);
NUnit.Framework.Assert.AreEqual(0, reader.GetModifiedFileId().Length);
}
[NUnit.Framework.Test]
public virtual void ReadPdfWithNoIdAndConservativeReadingTest() {
using (PdfReader reader = new PdfReader(sourceFolder + "pdfWithNoId.pdf").SetStrictnessLevel(PdfReader.StrictnessLevel
.CONSERVATIVE)) {
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => new PdfDocument(reader));
NUnit.Framework.Assert.AreEqual(TSpdf.IO.Logs.IoLogMessageConstant.DOCUMENT_IDS_ARE_CORRUPTED, e.Message);
}
}
// @Test
// public void appendModeTest() {
// String originalId;
// String newOriginalId;
// String appendModeNewOriginalId;
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// PdfWriter initialWriter = new PdfWriter(baos, new WriterProperties().setInitialDocumentId(originalId));
// PdfWriter newWriter = new PdfWriter(baos, new WriterProperties().setInitialDocumentId(newOriginalId));
// PdfWriter appendModeWriter = new PdfWriter(baos, new WriterProperties().setInitialDocumentId(appendModeNewOriginalId));
//
//
// }
//
// @Test
// public void encryptionAes128Test() {
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// PdfString originalId = new PdfString("Original ID 56789");
// PdfWriter initialWriter = new PdfWriter(baos, new WriterProperties().setInitialDocumentId(originalId));
//
// Assert.assertNotEquals();
// Assert.assertEquals();
//
// }
}
}

View File

@@ -0,0 +1,149 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using TSpdf.Kernel.Utils;
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("IntegrationTest")]
public class PdfDocumentInfoTest : ExtendedTSpdfTest {
public static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/pdf/PdfDocumentInfoTest/";
public static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/pdf/PdfDocumentInfoTest/";
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
CreateOrClearDestinationFolder(destinationFolder);
}
[NUnit.Framework.Test]
public virtual void DocumentInfoCreatePdf20() {
String outFile = destinationFolder + "test01.pdf";
String cmpFile = sourceFolder + "cmp_test01.pdf";
PdfDocument document = new PdfDocument(new PdfWriter(outFile, new WriterProperties().SetPdfVersion(PdfVersion
.PDF_2_0)));
document.AddNewPage();
document.GetDocumentInfo().SetAuthor("Alexey");
document.Close();
CompareTool ct = new CompareTool();
NUnit.Framework.Assert.IsNull(ct.CompareByContent(outFile, cmpFile, destinationFolder, "diff_"));
NUnit.Framework.Assert.IsNull(ct.CompareDocumentInfo(outFile, cmpFile));
NUnit.Framework.Assert.IsNull(ct.CompareXmp(outFile, cmpFile, true));
}
[NUnit.Framework.Test]
public virtual void DocumentInfoTransformPdf17ToPdf20() {
String inputFile = sourceFolder + "metadata_pdf.pdf";
String outFile = destinationFolder + "metadata_pdf_20.pdf";
String cmpFile = sourceFolder + "cmp_metadata_pdf_20.pdf";
PdfDocument document = new PdfDocument(new PdfReader(inputFile), new PdfWriter(outFile, new WriterProperties
().SetPdfVersion(PdfVersion.PDF_2_0)));
document.Close();
CompareTool ct = new CompareTool();
NUnit.Framework.Assert.IsNull(ct.CompareByContent(outFile, cmpFile, destinationFolder, "diff_"));
NUnit.Framework.Assert.IsNull(ct.CompareDocumentInfo(outFile, cmpFile));
NUnit.Framework.Assert.IsNull(ct.CompareXmp(outFile, cmpFile, true));
}
[NUnit.Framework.Test]
public virtual void ChangeDocumentVersionAndInfoInAppendMode() {
String inputFile = sourceFolder + "metadata_pdf.pdf";
String outFile = destinationFolder + "metadata_pdf_20_append.pdf";
String cmpFile = sourceFolder + "cmp_metadata_pdf_20_append.pdf";
PdfDocument document = new PdfDocument(new PdfReader(inputFile), new PdfWriter(outFile, new WriterProperties
().SetPdfVersion(PdfVersion.PDF_2_0)), new StampingProperties().UseAppendMode());
document.GetDocumentInfo().SetAuthor("Alexey Subach");
document.Close();
CompareTool ct = new CompareTool();
NUnit.Framework.Assert.IsNull(ct.CompareByContent(outFile, cmpFile, destinationFolder, "diff_"));
NUnit.Framework.Assert.IsNull(ct.CompareDocumentInfo(outFile, cmpFile));
NUnit.Framework.Assert.IsNull(ct.CompareXmp(outFile, cmpFile, true));
}
[NUnit.Framework.Test]
public virtual void ReadInfoFromMetadata() {
String inputFile = sourceFolder + "cmp_metadata_pdf_20.pdf";
PdfDocument document = new PdfDocument(new PdfReader(inputFile));
String author = document.GetDocumentInfo().GetAuthor();
String subject = document.GetDocumentInfo().GetSubject();
String title = document.GetDocumentInfo().GetTitle();
document.Close();
NUnit.Framework.Assert.AreEqual("Bruno Lowagie", author, "Author");
NUnit.Framework.Assert.AreEqual("Hello World example", title, "Title");
NUnit.Framework.Assert.AreEqual("This example shows how to add metadata", subject, "Subject");
}
[NUnit.Framework.Test]
public virtual void ChangeMetadataInAppendMode() {
String inputFile = sourceFolder + "cmp_metadata_pdf_20.pdf";
String outFile = destinationFolder + "metadata_pdf_20_changed_append.pdf";
String cmpFile = sourceFolder + "cmp_metadata_pdf_20_changed_append.pdf";
PdfDocument document = new PdfDocument(new PdfReader(inputFile), new PdfWriter(outFile), new StampingProperties
().UseAppendMode());
document.GetDocumentInfo().SetAuthor("Alexey Subach");
document.Close();
CompareTool ct = new CompareTool();
NUnit.Framework.Assert.IsNull(ct.CompareByContent(outFile, cmpFile, destinationFolder, "diff_"));
NUnit.Framework.Assert.IsNull(ct.CompareDocumentInfo(outFile, cmpFile));
NUnit.Framework.Assert.IsNull(ct.CompareXmp(outFile, cmpFile, true));
}
[NUnit.Framework.Test]
public virtual void SimpleStampingMetadataLeaveUnchanged() {
String inputFile = sourceFolder + "cmp_metadata_pdf_20_changed_append.pdf";
String outFile = destinationFolder + "metadata_pdf_20_unchanged_stamper.pdf";
String cmpFile = sourceFolder + "cmp_metadata_pdf_20_unchanged_append.pdf";
PdfDocument document = new PdfDocument(new PdfReader(inputFile), new PdfWriter(outFile), new StampingProperties
());
String author = document.GetDocumentInfo().GetAuthor();
document.Close();
NUnit.Framework.Assert.AreEqual("Bruno Lowagie; Alexey Subach", author, "Author");
CompareTool ct = new CompareTool();
NUnit.Framework.Assert.IsNull(ct.CompareByContent(outFile, cmpFile, destinationFolder, "diff_"));
NUnit.Framework.Assert.IsNull(ct.CompareDocumentInfo(outFile, cmpFile));
NUnit.Framework.Assert.IsNull(ct.CompareXmp(outFile, cmpFile, true));
}
}
}

View File

@@ -0,0 +1,534 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.IO;
using TSpdf.IO.Image;
using TSpdf.IO.Source;
using TSpdf.Kernel.Colors;
using TSpdf.Kernel.Exceptions;
using TSpdf.Kernel.Geom;
using TSpdf.Kernel.Logs;
using TSpdf.Kernel.Pdf.Annot;
using TSpdf.Kernel.Pdf.Canvas;
using TSpdf.Kernel.Pdf.Filespec;
using TSpdf.Kernel.Pdf.Navigation;
using TSpdf.Kernel.Pdf.Tagging;
using TSpdf.Kernel.Pdf.Xobject;
using TSpdf.Kernel.Utils;
using TSpdf.Kernel.XMP.Options;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("BouncyCastleIntegrationTest")]
public class PdfDocumentTest : ExtendedTSpdfTest {
public static readonly String SOURCE_FOLDER = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/pdf/PdfDocumentTest/";
public static readonly String DESTINATION_FOLDER = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/pdf/PdfDocumentTest/";
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
CreateOrClearDestinationFolder(DESTINATION_FOLDER);
}
[NUnit.Framework.Test]
public virtual void MissingProducerTest() {
String inputFile = SOURCE_FOLDER + "missingProducer.pdf";
MemoryStream outputStream = new MemoryStream();
using (PdfDocument document = new PdfDocument(new PdfReader(inputFile), new PdfWriter(outputStream))) {
PdfDocumentInfo documentInfo = document.GetDocumentInfo();
NUnit.Framework.Assert.IsNull(documentInfo.GetPdfObject().Get(PdfName.Producer));
NUnit.Framework.Assert.IsNull(documentInfo.GetProducer());
}
MemoryStream inputStream = new MemoryStream(outputStream.ToArray());
using (PdfDocument document_1 = new PdfDocument(new PdfReader(inputStream), new PdfWriter(new MemoryStream
()))) {
PdfDocumentInfo documentInfo = document_1.GetDocumentInfo();
NUnit.Framework.Assert.IsNotNull(documentInfo.GetPdfObject().Get(PdfName.Producer));
NUnit.Framework.Assert.IsNotNull(document_1.GetDocumentInfo().GetProducer());
}
}
[NUnit.Framework.Test]
public virtual void NullProducerTest() {
String inputFile = SOURCE_FOLDER + "nullProducer.pdf";
MemoryStream outputStream = new MemoryStream();
using (PdfDocument document = new PdfDocument(new PdfReader(inputFile), new PdfWriter(outputStream))) {
PdfDocumentInfo documentInfo = document.GetDocumentInfo();
NUnit.Framework.Assert.AreEqual(PdfNull.PDF_NULL, documentInfo.GetPdfObject().Get(PdfName.Producer));
NUnit.Framework.Assert.IsNull(documentInfo.GetProducer());
}
MemoryStream inputStream = new MemoryStream(outputStream.ToArray());
using (PdfDocument document_1 = new PdfDocument(new PdfReader(inputStream), new PdfWriter(new MemoryStream
()))) {
PdfDocumentInfo documentInfo = document_1.GetDocumentInfo();
NUnit.Framework.Assert.IsNotNull(documentInfo.GetPdfObject().Get(PdfName.Producer));
NUnit.Framework.Assert.IsNotNull(document_1.GetDocumentInfo().GetProducer());
}
}
[NUnit.Framework.Test]
public virtual void NameProducerTest() {
String inputFile = SOURCE_FOLDER + "nameProducer.pdf";
MemoryStream outputStream = new MemoryStream();
using (PdfDocument document = new PdfDocument(new PdfReader(inputFile), new PdfWriter(outputStream))) {
PdfDocumentInfo documentInfo = document.GetDocumentInfo();
NUnit.Framework.Assert.AreEqual(new PdfName("producerAsName"), documentInfo.GetPdfObject().Get(PdfName.Producer
));
NUnit.Framework.Assert.IsNull(documentInfo.GetProducer());
}
MemoryStream inputStream = new MemoryStream(outputStream.ToArray());
using (PdfDocument document_1 = new PdfDocument(new PdfReader(inputStream), new PdfWriter(new MemoryStream
()))) {
PdfDocumentInfo documentInfo = document_1.GetDocumentInfo();
NUnit.Framework.Assert.IsNotNull(documentInfo.GetPdfObject().Get(PdfName.Producer));
NUnit.Framework.Assert.IsNotNull(document_1.GetDocumentInfo().GetProducer());
}
}
[NUnit.Framework.Test]
public virtual void WritingVersionTest01() {
// There is a possibility to override version in stamping mode
String @out = DESTINATION_FOLDER + "writing_pdf_version.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(@out, new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0
)));
NUnit.Framework.Assert.AreEqual(PdfVersion.PDF_2_0, pdfDoc.GetPdfVersion());
pdfDoc.AddNewPage();
pdfDoc.Close();
PdfDocument assertPdfDoc = new PdfDocument(new PdfReader(@out));
NUnit.Framework.Assert.AreEqual(PdfVersion.PDF_2_0, assertPdfDoc.GetPdfVersion());
assertPdfDoc.Close();
}
//We have this test in PdfOutlineTest as well, because we had some issues with outlines before. One test worked
// fine, while another one failed.
[NUnit.Framework.Test]
public virtual void AddOutlinesWithNamedDestinations01() {
String filename = DESTINATION_FOLDER + "outlinesWithNamedDestinations01.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfReader(SOURCE_FOLDER + "iphone_user_guide.pdf"), new PdfWriter
(filename));
PdfArray array1 = new PdfArray();
array1.Add(pdfDoc.GetPage(2).GetPdfObject());
array1.Add(PdfName.XYZ);
array1.Add(new PdfNumber(36));
array1.Add(new PdfNumber(806));
array1.Add(new PdfNumber(0));
PdfArray array2 = new PdfArray();
array2.Add(pdfDoc.GetPage(3).GetPdfObject());
array2.Add(PdfName.XYZ);
array2.Add(new PdfNumber(36));
array2.Add(new PdfNumber(806));
array2.Add(new PdfNumber(1.25));
PdfArray array3 = new PdfArray();
array3.Add(pdfDoc.GetPage(4).GetPdfObject());
array3.Add(PdfName.XYZ);
array3.Add(new PdfNumber(36));
array3.Add(new PdfNumber(806));
array3.Add(new PdfNumber(1));
pdfDoc.AddNamedDestination("test1", array2);
pdfDoc.AddNamedDestination("test2", array3);
pdfDoc.AddNamedDestination("test3", array1);
PdfOutline root = pdfDoc.GetOutlines(false);
PdfOutline firstOutline = root.AddOutline("Test1");
firstOutline.AddDestination(PdfDestination.MakeDestination(new PdfString("test1")));
PdfOutline secondOutline = root.AddOutline("Test2");
secondOutline.AddDestination(PdfDestination.MakeDestination(new PdfString("test2")));
PdfOutline thirdOutline = root.AddOutline("Test3");
thirdOutline.AddDestination(PdfDestination.MakeDestination(new PdfString("test3")));
pdfDoc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, SOURCE_FOLDER + "cmp_outlinesWithNamedDestinations01.pdf"
, DESTINATION_FOLDER, "diff_"));
}
[NUnit.Framework.Test]
public virtual void FreeReferencesInObjectStream() {
PdfReader reader = new PdfReader(SOURCE_FOLDER + "styledLineArts_Redacted.pdf");
PdfWriter writer = new PdfWriter(new MemoryStream());
PdfDocument document = new PdfDocument(reader, writer, new StampingProperties().UseAppendMode());
PdfDictionary dict = new PdfDictionary();
dict.MakeIndirect(document);
NUnit.Framework.Assert.IsTrue(dict.GetIndirectReference().GetObjNumber() > 0);
}
[NUnit.Framework.Test]
public virtual void RemoveUnusedObjectsInWriterModeTest() {
String filename = "removeUnusedObjectsInWriter.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(DESTINATION_FOLDER + filename));
pdfDocument.AddNewPage();
PdfDictionary unusedDictionary = new PdfDictionary();
PdfArray unusedArray = (PdfArray)new PdfArray().MakeIndirect(pdfDocument);
unusedArray.Add(new PdfNumber(42));
unusedDictionary.Put(new PdfName("testName"), unusedArray);
unusedDictionary.MakeIndirect(pdfDocument);
NUnit.Framework.Assert.AreEqual(pdfDocument.GetXref().Size(), 8);
//on closing, all unused objects shall not be written to resultant document
pdfDocument.Close();
PdfDocument testerDocument = new PdfDocument(new PdfReader(DESTINATION_FOLDER + filename));
NUnit.Framework.Assert.AreEqual(testerDocument.GetXref().Size(), 6);
testerDocument.Close();
}
[NUnit.Framework.Test]
public virtual void RemoveUnusedObjectsInStampingModeTest() {
String filenameIn = "docWithUnusedObjects_1.pdf";
String filenameOut = "removeUnusedObjectsInStamping.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(DESTINATION_FOLDER + filenameIn));
pdfDocument.AddNewPage();
PdfDictionary unusedDictionary = new PdfDictionary();
PdfArray unusedArray = (PdfArray)new PdfArray().MakeIndirect(pdfDocument);
unusedArray.Add(new PdfNumber(42));
unusedDictionary.Put(new PdfName("testName"), unusedArray);
unusedDictionary.MakeIndirect(pdfDocument).Flush();
pdfDocument.Close();
PdfDocument doc = new PdfDocument(new PdfReader(DESTINATION_FOLDER + filenameIn), new PdfWriter(DESTINATION_FOLDER
+ filenameOut));
NUnit.Framework.Assert.AreEqual(doc.GetXref().Size(), 8);
//on closing, all unused objects shall not be written to resultant document
doc.Close();
PdfDocument testerDocument = new PdfDocument(new PdfReader(DESTINATION_FOLDER + filenameOut));
NUnit.Framework.Assert.AreEqual(testerDocument.GetXref().Size(), 6);
testerDocument.Close();
}
[NUnit.Framework.Test]
public virtual void AddUnusedObjectsInWriterModeTest() {
String filename = "addUnusedObjectsInWriter.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(DESTINATION_FOLDER + filename));
pdfDocument.AddNewPage();
PdfDictionary unusedDictionary = new PdfDictionary();
PdfArray unusedArray = (PdfArray)new PdfArray().MakeIndirect(pdfDocument);
unusedArray.Add(new PdfNumber(42));
unusedDictionary.Put(new PdfName("testName"), unusedArray);
unusedDictionary.MakeIndirect(pdfDocument);
NUnit.Framework.Assert.AreEqual(pdfDocument.GetXref().Size(), 8);
pdfDocument.SetFlushUnusedObjects(true);
pdfDocument.Close();
PdfDocument testerDocument = new PdfDocument(new PdfReader(DESTINATION_FOLDER + filename));
NUnit.Framework.Assert.AreEqual(testerDocument.GetXref().Size(), 8);
testerDocument.Close();
}
[NUnit.Framework.Test]
public virtual void AddUnusedObjectsInStampingModeTest() {
String filenameIn = "docWithUnusedObjects_2.pdf";
String filenameOut = "addUnusedObjectsInStamping.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(DESTINATION_FOLDER + filenameIn));
pdfDocument.AddNewPage();
PdfDictionary unusedDictionary = new PdfDictionary();
PdfArray unusedArray = (PdfArray)new PdfArray().MakeIndirect(pdfDocument);
unusedArray.Add(new PdfNumber(42));
unusedDictionary.Put(new PdfName("testName"), unusedArray);
unusedDictionary.MakeIndirect(pdfDocument).Flush();
pdfDocument.Close();
PdfDocument doc = new PdfDocument(new PdfReader(DESTINATION_FOLDER + filenameIn), new PdfWriter(DESTINATION_FOLDER
+ filenameOut));
NUnit.Framework.Assert.AreEqual(doc.GetXref().Size(), 8);
doc.SetFlushUnusedObjects(true);
doc.Close();
PdfDocument testerDocument = new PdfDocument(new PdfReader(DESTINATION_FOLDER + filenameOut));
NUnit.Framework.Assert.AreEqual(testerDocument.GetXref().Size(), 8);
testerDocument.Close();
}
[NUnit.Framework.Test]
public virtual void AddUnusedStreamObjectsTest() {
String filenameIn = "docWithUnusedObjects_3.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(DESTINATION_FOLDER + filenameIn));
pdfDocument.AddNewPage();
PdfDictionary unusedDictionary = new PdfDictionary();
PdfArray unusedArray = (PdfArray)new PdfArray().MakeIndirect(pdfDocument);
unusedArray.Add(new PdfNumber(42));
PdfStream stream = new PdfStream(new byte[] { 1, 2, 34, 45 }, 0);
unusedArray.Add(stream);
unusedDictionary.Put(new PdfName("testName"), unusedArray);
unusedDictionary.MakeIndirect(pdfDocument).Flush();
pdfDocument.SetFlushUnusedObjects(true);
pdfDocument.Close();
PdfDocument testerDocument = new PdfDocument(new PdfReader(DESTINATION_FOLDER + filenameIn));
NUnit.Framework.Assert.AreEqual(testerDocument.GetXref().Size(), 9);
testerDocument.Close();
}
[NUnit.Framework.Test]
public virtual void TestImageCompressLevel() {
byte[] b = ImageDataFactory.Create(SOURCE_FOLDER + "berlin2013.jpg").GetData();
ByteArrayOutputStream image = new ByteArrayOutputStream();
image.AssignBytes(b, b.Length);
MemoryStream byteArrayStream1 = new ByteArrayOutputStream();
DeflaterOutputStream zip = new DeflaterOutputStream(byteArrayStream1, 9);
image.WriteTo(zip);
MemoryStream byteArrayStream2 = new ByteArrayOutputStream();
DeflaterOutputStream zip2 = new DeflaterOutputStream(byteArrayStream2, -1);
image.WriteTo(zip2);
NUnit.Framework.Assert.IsTrue(byteArrayStream1.Length == byteArrayStream2.Length);
zip.Dispose();
zip2.Dispose();
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.FLUSHED_OBJECT_CONTAINS_FREE_REFERENCE)]
public virtual void TestFreeReference() {
PdfWriter writer = new PdfWriter(DESTINATION_FOLDER + "freeReference.pdf", new WriterProperties().SetFullCompressionMode
(false));
PdfDocument pdfDocument = new PdfDocument(new PdfReader(SOURCE_FOLDER + "baseFreeReference.pdf"), writer);
pdfDocument.GetPage(1).GetResources().GetPdfObject().GetAsArray(new PdfName("d")).Get(0).GetIndirectReference
().SetFree();
PdfStream pdfStream = new PdfStream();
pdfStream.SetData(new byte[] { 24, 23, 67 });
pdfStream.MakeIndirect(pdfDocument);
pdfDocument.GetPage(1).GetResources().GetPdfObject().GetAsArray(new PdfName("d")).Add(pdfStream);
pdfDocument.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(DESTINATION_FOLDER + "freeReference.pdf",
SOURCE_FOLDER + "cmp_freeReference.pdf", DESTINATION_FOLDER, "diff_"));
}
[NUnit.Framework.Test]
public virtual void FullCompressionAppendMode() {
PdfWriter writer = new PdfWriter(DESTINATION_FOLDER + "fullCompressionAppendMode.pdf", new WriterProperties
().SetFullCompressionMode(true).SetCompressionLevel(CompressionConstants.NO_COMPRESSION));
PdfDocument pdfDocument = new PdfDocument(new PdfReader(SOURCE_FOLDER + "fullCompressionDoc.pdf"), writer,
new StampingProperties().UseAppendMode());
PdfPage page = pdfDocument.GetPage(1);
PdfStream contentStream = new PdfStream();
String contentStr = TSpdf.Commons.Utils.JavaUtil.GetStringForBytes(pdfDocument.GetPage(1).GetFirstContentStream
().GetBytes(), System.Text.Encoding.ASCII);
contentStream.SetData(contentStr.Replace("/F1 16", "/F1 24").GetBytes(System.Text.Encoding.ASCII));
page.GetPdfObject().Put(PdfName.Contents, contentStream);
page.SetModified();
pdfDocument.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(DESTINATION_FOLDER + "fullCompressionAppendMode.pdf"
, SOURCE_FOLDER + "cmp_fullCompressionAppendMode.pdf", DESTINATION_FOLDER, "diff_"));
PdfDocument assertDoc = new PdfDocument(new PdfReader(DESTINATION_FOLDER + "fullCompressionAppendMode.pdf"
));
NUnit.Framework.Assert.IsTrue(assertDoc.GetPdfObject(9).IsStream());
NUnit.Framework.Assert.AreEqual(1, ((PdfDictionary)assertDoc.GetPdfObject(9)).GetAsNumber(PdfName.N).IntValue
());
}
[NUnit.Framework.Test]
public virtual void CheckAndResolveCircularReferences() {
PdfDocument pdfDocument = new PdfDocument(new PdfReader(SOURCE_FOLDER + "datasheet.pdf"), new PdfWriter(DESTINATION_FOLDER
+ "datasheet_mode.pdf"));
PdfDictionary pdfObject = (PdfDictionary)pdfDocument.GetPdfObject(53);
pdfDocument.GetPage(1).GetResources().AddForm((PdfStream)pdfObject);
pdfDocument.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(DESTINATION_FOLDER + "datasheet_mode.pdf"
, SOURCE_FOLDER + "cmp_datasheet_mode.pdf", DESTINATION_FOLDER, "diff_"));
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void ReadEncryptedDocumentWithFullCompression() {
PdfReader reader = new PdfReader(SOURCE_FOLDER + "source.pdf", new ReaderProperties().SetPassword("123".GetBytes
()));
PdfDocument pdfDocument = new PdfDocument(reader);
PdfDictionary form = pdfDocument.GetCatalog().GetPdfObject().GetAsDictionary(PdfName.AcroForm);
PdfDictionary field = form.GetAsArray(PdfName.Fields).GetAsDictionary(0);
NUnit.Framework.Assert.AreEqual("ch", field.GetAsString(PdfName.T).ToUnicodeString());
NUnit.Framework.Assert.AreEqual("SomeStringValueInDictionary", field.GetAsDictionary(new PdfName("TestDic"
)).GetAsString(new PdfName("TestString")).ToUnicodeString());
NUnit.Framework.Assert.AreEqual("SomeStringValueInArray", field.GetAsArray(new PdfName("TestArray")).GetAsString
(0).ToUnicodeString());
pdfDocument.Close();
}
[NUnit.Framework.Test]
public virtual void AddAssociatedFilesTest01() {
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(DESTINATION_FOLDER + "add_associated_files01.pdf",
new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)));
pdfDocument.SetTagged();
pdfDocument.AddAssociatedFile("af_1", PdfFileSpec.CreateEmbeddedFileSpec(pdfDocument, "Associated File 1".
GetBytes(), "af_1.txt", PdfName.Data));
pdfDocument.AddNewPage();
pdfDocument.GetFirstPage().AddAssociatedFile("af_2", PdfFileSpec.CreateEmbeddedFileSpec(pdfDocument, "Associated File 2"
.GetBytes(), "af_2.txt", PdfName.Data));
PdfStructTreeRoot root = pdfDocument.GetStructTreeRoot();
root.AddAssociatedFile("af_3", PdfFileSpec.CreateEmbeddedFileSpec(pdfDocument, "Associated File 3".GetBytes
(), "af_3.txt", PdfName.Data));
PdfFileSpec af5 = PdfFileSpec.CreateEmbeddedFileSpec(pdfDocument, "Associated File 5".GetBytes(), "af_5",
"af_5.txt", PdfName.Data);
PdfTextAnnotation textannot = new PdfTextAnnotation(new Rectangle(100, 600, 50, 40));
textannot.SetText(new PdfString("Text Annotation 01")).SetContents(new PdfString("Some contents..."));
textannot.AddAssociatedFile(af5);
pdfDocument.GetFirstPage().AddAnnotation(textannot);
pdfDocument.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(DESTINATION_FOLDER + "add_associated_files01.pdf"
, SOURCE_FOLDER + "cmp_add_associated_files01.pdf", DESTINATION_FOLDER, "diff_"));
}
[NUnit.Framework.Test]
public virtual void AddAssociatedFilesTest02() {
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(DESTINATION_FOLDER + "add_associated_files02.pdf",
new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)));
pdfDocument.SetTagged();
PdfCanvas pageCanvas = new PdfCanvas(pdfDocument.AddNewPage());
PdfImageXObject imageXObject = new PdfImageXObject(ImageDataFactory.Create(SOURCE_FOLDER + "berlin2013.jpg"
));
imageXObject.AddAssociatedFile(PdfFileSpec.CreateEmbeddedFileSpec(pdfDocument, "Associated File 1".GetBytes
(), "af_1.txt", PdfName.Data));
pageCanvas.AddXObjectAt(imageXObject, 40, 400);
PdfFormXObject formXObject = new PdfFormXObject(new Rectangle(200, 200));
PdfCanvas formCanvas = new PdfCanvas(formXObject, pdfDocument);
formCanvas.SaveState().Circle(100, 100, 50).SetColor(ColorConstants.BLACK, true).Fill().RestoreState();
formCanvas.Release();
formXObject.AddAssociatedFile(PdfFileSpec.CreateEmbeddedFileSpec(pdfDocument, "Associated File 2".GetBytes
(), "af_2.txt", PdfName.Data));
pageCanvas.AddXObjectAt(formXObject, 40, 100);
pdfDocument.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(DESTINATION_FOLDER + "add_associated_files02.pdf"
, SOURCE_FOLDER + "cmp_add_associated_files02.pdf", DESTINATION_FOLDER, "diff_"));
}
[NUnit.Framework.Test]
public virtual void IgnoreTagStructureTest() {
String srcFile = SOURCE_FOLDER + "ignoreTagStructureTest.pdf";
PdfDocument doNotIgnoreTagStructureDocument = new PdfDocument(new PdfReader(srcFile));
PdfDocumentTest.IgnoreTagStructurePdfDocument ignoreTagStructureDocument = new PdfDocumentTest.IgnoreTagStructurePdfDocument
(new PdfReader(srcFile));
NUnit.Framework.Assert.IsTrue(doNotIgnoreTagStructureDocument.IsTagged());
NUnit.Framework.Assert.IsFalse(ignoreTagStructureDocument.IsTagged());
doNotIgnoreTagStructureDocument.Close();
ignoreTagStructureDocument.Close();
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.OUTLINE_DESTINATION_PAGE_NUMBER_IS_OUT_OF_BOUNDS, LogLevel =
LogLevelConstants.WARN)]
public virtual void RemovePageWithInvalidOutlineTest() {
String source = SOURCE_FOLDER + "invalid_outline.pdf";
String destination = DESTINATION_FOLDER + "invalid_outline.pdf";
String cmp = SOURCE_FOLDER + "cmp_invalid_outline.pdf";
PdfDocument document = new PdfDocument(new PdfReader(new FileStream(source, FileMode.Open, FileAccess.Read
)), new PdfWriter(new FileStream(destination, FileMode.Create)));
document.RemovePage(4);
document.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destination, cmp, DESTINATION_FOLDER, "diff_"
));
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.DOCUMENT_VERSION_IN_CATALOG_CORRUPTED, LogLevel = LogLevelConstants
.ERROR)]
public virtual void OpenDocumentWithInvalidCatalogVersionTest() {
using (PdfReader reader = new PdfReader(SOURCE_FOLDER + "sample-with-invalid-catalog-version.pdf")) {
using (PdfDocument pdfDocument = new PdfDocument(reader)) {
NUnit.Framework.Assert.IsNotNull(pdfDocument);
}
}
}
[NUnit.Framework.Test]
public virtual void OpenDocumentWithInvalidCatalogVersionAndConservativeStrictnessReadingTest() {
using (PdfReader reader = new PdfReader(SOURCE_FOLDER + "sample-with-invalid-catalog-version.pdf").SetStrictnessLevel
(PdfReader.StrictnessLevel.CONSERVATIVE)) {
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => new PdfDocument(reader));
NUnit.Framework.Assert.AreEqual(TSpdf.IO.Logs.IoLogMessageConstant.DOCUMENT_VERSION_IN_CATALOG_CORRUPTED,
e.Message);
}
}
[NUnit.Framework.Test]
public virtual void WidgetDaEntryRemovePageTest() {
String testName = "widgetDaEntryRemovePage.pdf";
String outPdf = DESTINATION_FOLDER + testName;
using (PdfDocument pdfDocument = new PdfDocument(new PdfReader(SOURCE_FOLDER + "widgetWithDaEntry.pdf"), new
PdfWriter(outPdf))) {
pdfDocument.RemovePage(3);
}
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, SOURCE_FOLDER + "cmp_" + testName
, DESTINATION_FOLDER));
}
[NUnit.Framework.Test]
public virtual void MergedAndSimpleWidgetsRemovePageTest() {
String testName = "mergedAndSimpleWidgetsRemovePage.pdf";
String outPdf = DESTINATION_FOLDER + testName;
using (PdfDocument pdfDocument = new PdfDocument(new PdfReader(SOURCE_FOLDER + "mergedAndSimpleWidgets.pdf"
), new PdfWriter(outPdf))) {
pdfDocument.RemovePage(1);
}
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, SOURCE_FOLDER + "cmp_" + testName
, DESTINATION_FOLDER));
}
[NUnit.Framework.Test]
public virtual void MergedSiblingWidgetsRemovePageTest() {
String testName = "mergedSiblingWidgetsRemovePage.pdf";
String outPdf = DESTINATION_FOLDER + testName;
using (PdfDocument pdfDocument = new PdfDocument(new PdfReader(SOURCE_FOLDER + "mergedSiblingWidgets.pdf")
, new PdfWriter(outPdf))) {
pdfDocument.RemovePage(2);
}
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, SOURCE_FOLDER + "cmp_" + testName
, DESTINATION_FOLDER));
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)]
public virtual void RootCannotBeReferenceFromTrailerTest() {
String filename = SOURCE_FOLDER + "rootCannotBeReferenceFromTrailerTest.pdf";
PdfReader corruptedReader = new PdfReader(filename);
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => new PdfDocument(corruptedReader));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.CORRUPTED_ROOT_ENTRY_IN_TRAILER, e.Message);
}
[NUnit.Framework.Test]
public virtual void SetSerializeOptionsTest() {
PdfDocument document = new PdfDocument(new PdfWriter(new MemoryStream()));
SerializeOptions options = new SerializeOptions().SetUseCanonicalFormat(true);
document.SetSerializeOptions(options);
NUnit.Framework.Assert.AreEqual(options, document.GetSerializeOptions());
}
private class IgnoreTagStructurePdfDocument : PdfDocument {
internal IgnoreTagStructurePdfDocument(PdfReader reader)
: base(reader) {
}
protected internal override void TryInitTagStructure(PdfDictionary str) {
}
}
}
}

View File

@@ -0,0 +1,409 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.IO;
using TSpdf.Commons.Utils;
using TSpdf.IO.Font;
using TSpdf.IO.Source;
using TSpdf.Kernel.Exceptions;
using TSpdf.Kernel.Font;
using TSpdf.Kernel.Logs;
using TSpdf.Kernel.Pdf.Filespec;
using TSpdf.Kernel.Pdf.Layer;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("BouncyCastleUnitTest")]
public class PdfDocumentUnitTest : ExtendedTSpdfTest {
private static readonly String SOURCE_FOLDER = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/pdf/PdfDocumentUnitTest/";
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.TYPE3_FONT_INITIALIZATION_ISSUE)]
public virtual void GetFontWithDirectFontDictionaryTest() {
PdfDictionary initialFontDict = new PdfDictionary();
initialFontDict.Put(PdfName.Subtype, PdfName.Type3);
initialFontDict.Put(PdfName.FontMatrix, new PdfArray(new float[] { 0.001F, 0, 0, 0.001F, 0, 0 }));
initialFontDict.Put(PdfName.Widths, new PdfArray());
PdfDictionary encoding = new PdfDictionary();
initialFontDict.Put(PdfName.Encoding, encoding);
PdfArray differences = new PdfArray();
differences.Add(new PdfNumber(AdobeGlyphList.NameToUnicode("a")));
differences.Add(new PdfName("a"));
encoding.Put(PdfName.Differences, differences);
NUnit.Framework.Assert.IsNull(initialFontDict.GetIndirectReference());
using (PdfDocument doc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()))) {
// prevent no pages exception on close
doc.AddNewPage();
PdfType3Font font1 = (PdfType3Font)doc.GetFont(initialFontDict);
NUnit.Framework.Assert.IsNotNull(font1);
// prevent no glyphs for type3 font on close
font1.AddGlyph('a', 0, 0, 0, 0, 0);
}
}
[NUnit.Framework.Test]
public virtual void CopyPagesWithOCGDifferentNames() {
IList<IList<String>> ocgNames = new List<IList<String>>();
IList<String> ocgNames1 = new List<String>();
ocgNames1.Add("Name1");
IList<String> ocgNames2 = new List<String>();
ocgNames2.Add("Name2");
ocgNames.Add(ocgNames1);
ocgNames.Add(ocgNames2);
IList<byte[]> sourceDocuments = PdfDocumentUnitTest.InitSourceDocuments(ocgNames);
using (PdfDocument outDocument = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()))) {
foreach (byte[] docBytes in sourceDocuments) {
using (PdfDocument fromDocument = new PdfDocument(new PdfReader(new MemoryStream(docBytes)))) {
for (int i = 1; i <= fromDocument.GetNumberOfPages(); i++) {
fromDocument.CopyPagesTo(i, i, outDocument);
}
}
}
IList<String> layerNames = new List<String>();
layerNames.Add("Name1");
layerNames.Add("Name2");
PdfDocumentUnitTest.AssertLayerNames(outDocument, layerNames);
}
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.DOCUMENT_HAS_CONFLICTING_OCG_NAMES, Count = 3)]
public virtual void CopyPagesWithOCGSameName() {
IList<IList<String>> ocgNames = new List<IList<String>>();
IList<String> ocgNames1 = new List<String>();
ocgNames1.Add("Name1");
ocgNames.Add(ocgNames1);
ocgNames.Add(ocgNames1);
ocgNames.Add(ocgNames1);
ocgNames.Add(ocgNames1);
IList<byte[]> sourceDocuments = PdfDocumentUnitTest.InitSourceDocuments(ocgNames);
using (PdfDocument outDocument = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()))) {
foreach (byte[] docBytes in sourceDocuments) {
using (PdfDocument fromDocument = new PdfDocument(new PdfReader(new MemoryStream(docBytes)))) {
for (int i = 1; i <= fromDocument.GetNumberOfPages(); i++) {
fromDocument.CopyPagesTo(i, i, outDocument);
}
}
}
IList<String> layerNames = new List<String>();
layerNames.Add("Name1");
layerNames.Add("Name1_0");
layerNames.Add("Name1_1");
layerNames.Add("Name1_2");
PdfDocumentUnitTest.AssertLayerNames(outDocument, layerNames);
}
}
[NUnit.Framework.Test]
public virtual void CopyPagesWithOCGSameObject() {
byte[] docBytes;
using (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
using (PdfDocument document = new PdfDocument(new PdfWriter(outputStream))) {
PdfPage page = document.AddNewPage();
PdfResources pdfResource = page.GetResources();
PdfDictionary ocg = new PdfDictionary();
ocg.Put(PdfName.Type, PdfName.OCG);
ocg.Put(PdfName.Name, new PdfString("name1"));
ocg.MakeIndirect(document);
pdfResource.AddProperties(ocg);
PdfPage page2 = document.AddNewPage();
PdfResources pdfResource2 = page2.GetResources();
pdfResource2.AddProperties(ocg);
document.GetCatalog().GetOCProperties(true);
}
docBytes = outputStream.ToArray();
}
using (PdfDocument outDocument = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()))) {
using (PdfDocument fromDocument = new PdfDocument(new PdfReader(new MemoryStream(docBytes)))) {
fromDocument.CopyPagesTo(1, fromDocument.GetNumberOfPages(), outDocument);
}
IList<String> layerNames = new List<String>();
layerNames.Add("name1");
PdfDocumentUnitTest.AssertLayerNames(outDocument, layerNames);
}
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.OCG_COPYING_ERROR, LogLevel = LogLevelConstants.ERROR)]
public virtual void CopyPagesFlushedResources() {
byte[] docBytes;
using (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
using (PdfDocument document = new PdfDocument(new PdfWriter(outputStream))) {
PdfPage page = document.AddNewPage();
PdfResources pdfResource = page.GetResources();
PdfDictionary ocg = new PdfDictionary();
ocg.Put(PdfName.Type, PdfName.OCG);
ocg.Put(PdfName.Name, new PdfString("name1"));
ocg.MakeIndirect(document);
pdfResource.AddProperties(ocg);
pdfResource.MakeIndirect(document);
PdfPage page2 = document.AddNewPage();
page2.SetResources(pdfResource);
document.GetCatalog().GetOCProperties(true);
}
docBytes = outputStream.ToArray();
}
PdfWriter writer = new PdfWriter(new ByteArrayOutputStream());
using (PdfDocument outDocument = new PdfDocument(writer)) {
using (PdfDocument fromDocument = new PdfDocument(new PdfReader(new MemoryStream(docBytes)))) {
fromDocument.CopyPagesTo(1, 1, outDocument);
IList<String> layerNames = new List<String>();
layerNames.Add("name1");
PdfDocumentUnitTest.AssertLayerNames(outDocument, layerNames);
outDocument.FlushCopiedObjects(fromDocument);
fromDocument.CopyPagesTo(2, 2, outDocument);
NUnit.Framework.Assert.IsNotNull(outDocument.GetCatalog());
PdfOCProperties ocProperties = outDocument.GetCatalog().GetOCProperties(false);
NUnit.Framework.Assert.IsNotNull(ocProperties);
NUnit.Framework.Assert.AreEqual(1, ocProperties.GetLayers().Count);
PdfLayer layer = ocProperties.GetLayers()[0];
NUnit.Framework.Assert.IsTrue(layer.GetPdfObject().IsFlushed());
}
}
}
[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_248(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_248 : PdfDocument {
public _PdfDocument_248(PdfReader baseArg1)
: base(baseArg1) {
}
}
[NUnit.Framework.Test]
public virtual void ExtendedPdfDocumentWriterInfoAndConformanceLevelInitialization() {
PdfDocument pdfDocument = new _PdfDocument_265(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_265 : PdfDocument {
public _PdfDocument_265(PdfReader baseArg1, PdfWriter baseArg2)
: base(baseArg1, baseArg2) {
}
}
[NUnit.Framework.Test]
public virtual void GetDocumentInfoAlreadyClosedTest() {
PdfDocument pdfDocument = new PdfDocument(new PdfReader(SOURCE_FOLDER + "pdfWithMetadata.pdf"));
pdfDocument.Close();
NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfDocument.GetDocumentInfo());
}
[NUnit.Framework.Test]
public virtual void GetDocumentInfoNotInitializedTest() {
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() {
PdfDocument pdfDocument = new PdfDocument(new PdfReader(SOURCE_FOLDER + "pdfWithMetadata.pdf"));
NUnit.Framework.Assert.IsNull(pdfDocument.reader.pdfAConformanceLevel);
NUnit.Framework.Assert.IsNotNull(pdfDocument.reader.GetPdfAConformanceLevel());
pdfDocument.Close();
}
private static void AssertLayerNames(PdfDocument outDocument, IList<String> layerNames) {
NUnit.Framework.Assert.IsNotNull(outDocument.GetCatalog());
PdfOCProperties ocProperties = outDocument.GetCatalog().GetOCProperties(true);
NUnit.Framework.Assert.IsNotNull(ocProperties);
NUnit.Framework.Assert.AreEqual(layerNames.Count, ocProperties.GetLayers().Count);
for (int i = 0; i < layerNames.Count; i++) {
PdfLayer layer = ocProperties.GetLayers()[i];
NUnit.Framework.Assert.IsNotNull(layer);
PdfDocumentUnitTest.AssertLayerNameEqual(layerNames[i], layer);
}
}
private static IList<byte[]> InitSourceDocuments(IList<IList<String>> ocgNames) {
IList<byte[]> result = new List<byte[]>();
foreach (IList<String> names in ocgNames) {
result.Add(PdfDocumentUnitTest.InitDocument(names));
}
return result;
}
private static byte[] InitDocument(IList<String> names) {
using (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
using (PdfDocument document = new PdfDocument(new PdfWriter(outputStream))) {
PdfPage page = document.AddNewPage();
PdfResources pdfResource = page.GetResources();
foreach (String name in names) {
PdfDictionary ocg = new PdfDictionary();
ocg.Put(PdfName.Type, PdfName.OCG);
ocg.Put(PdfName.Name, new PdfString(name));
ocg.MakeIndirect(document);
pdfResource.AddProperties(ocg);
}
document.GetCatalog().GetOCProperties(true);
}
return outputStream.ToArray();
}
}
private static void AssertLayerNameEqual(String name, PdfLayer layer) {
PdfDictionary layerDictionary = layer.GetPdfObject();
NUnit.Framework.Assert.IsNotNull(layerDictionary);
NUnit.Framework.Assert.IsNotNull(layerDictionary.Get(PdfName.Name));
String layerNameString = layerDictionary.Get(PdfName.Name).ToString();
NUnit.Framework.Assert.AreEqual(name, layerNameString);
}
[NUnit.Framework.Test]
public virtual void CannotGetTagStructureForUntaggedDocumentTest() {
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfDoc.GetTagStructureContext
());
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.MUST_BE_A_TAGGED_DOCUMENT, exception.Message
);
}
[NUnit.Framework.Test]
public virtual void CannotAddPageAfterDocumentIsClosedTest() {
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
pdfDoc.AddNewPage(1);
pdfDoc.Close();
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfDoc.AddNewPage(2));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.DOCUMENT_CLOSED_IT_IS_IMPOSSIBLE_TO_EXECUTE_ACTION
, exception.Message);
}
[NUnit.Framework.Test]
public virtual void CannotMovePageToZeroPositionTest() {
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
pdfDoc.AddNewPage();
Exception exception = NUnit.Framework.Assert.Catch(typeof(IndexOutOfRangeException), () => pdfDoc.MovePage
(1, 0));
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(KernelExceptionMessageConstant.REQUESTED_PAGE_NUMBER_IS_OUT_OF_BOUNDS
, 0), exception.Message);
}
[NUnit.Framework.Test]
public virtual void CannotMovePageToNegativePosition() {
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
pdfDoc.AddNewPage();
Exception exception = NUnit.Framework.Assert.Catch(typeof(IndexOutOfRangeException), () => pdfDoc.MovePage
(1, -1));
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(KernelExceptionMessageConstant.REQUESTED_PAGE_NUMBER_IS_OUT_OF_BOUNDS
, -1), exception.Message);
}
[NUnit.Framework.Test]
public virtual void CannotMovePageToOneMorePositionThanPagesNumberTest() {
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
pdfDoc.AddNewPage();
Exception exception = NUnit.Framework.Assert.Catch(typeof(IndexOutOfRangeException), () => pdfDoc.MovePage
(1, 3));
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(KernelExceptionMessageConstant.REQUESTED_PAGE_NUMBER_IS_OUT_OF_BOUNDS
, 3), exception.Message);
}
[NUnit.Framework.Test]
public virtual void CannotAddPageToAnotherDocumentTest() {
PdfDocument pdfDoc1 = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
PdfDocument pdfDoc2 = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
pdfDoc1.AddNewPage(1);
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfDoc2.CheckAndAddPage(1,
pdfDoc1.GetPage(1)));
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(KernelExceptionMessageConstant.PAGE_CANNOT_BE_ADDED_TO_DOCUMENT_BECAUSE_IT_BELONGS_TO_ANOTHER_DOCUMENT
, pdfDoc1, 1, pdfDoc2), exception.Message);
}
[NUnit.Framework.Test]
public virtual void CannotAddPageToAnotherDocTest() {
PdfDocument pdfDoc1 = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
PdfDocument pdfDoc2 = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
pdfDoc1.AddNewPage(1);
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfDoc2.CheckAndAddPage(pdfDoc1
.GetPage(1)));
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(KernelExceptionMessageConstant.PAGE_CANNOT_BE_ADDED_TO_DOCUMENT_BECAUSE_IT_BELONGS_TO_ANOTHER_DOCUMENT
, pdfDoc1, 1, pdfDoc2), exception.Message);
}
[NUnit.Framework.Test]
public virtual void CannotSetEncryptedPayloadInReadingModeTest() {
PdfDocument pdfDoc = new PdfDocument(new PdfReader(SOURCE_FOLDER + "setEncryptedPayloadInReadingModeTest.pdf"
));
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfDoc.SetEncryptedPayload(
null));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.CANNOT_SET_ENCRYPTED_PAYLOAD_TO_DOCUMENT_OPENED_IN_READING_MODE
, exception.Message);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void CannotSetEncryptedPayloadToEncryptedDocTest() {
WriterProperties writerProperties = new WriterProperties();
writerProperties.SetStandardEncryption(new byte[] { }, new byte[] { }, 1, 1);
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream(), writerProperties));
PdfFileSpec fs = PdfFileSpec.CreateExternalFileSpec(pdfDoc, SOURCE_FOLDER + "testPath");
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfDoc.SetEncryptedPayload(
fs));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.CANNOT_SET_ENCRYPTED_PAYLOAD_TO_ENCRYPTED_DOCUMENT
, exception.Message);
}
}
}

View File

@@ -0,0 +1,88 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("UnitTest")]
public class PdfEncryptionUnitTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void ReadEncryptEmbeddedFilesOnlyFromPdfDocumentCorrectEntryTest() {
PdfDictionary cryptDictionary = new PdfDictionary();
cryptDictionary.Put(PdfName.EFF, PdfName.StdCF);
cryptDictionary.Put(PdfName.StmF, PdfName.Identity);
cryptDictionary.Put(PdfName.StrF, PdfName.Identity);
PdfDictionary cfDictionary = new PdfDictionary();
cfDictionary.Put(PdfName.StdCF, new PdfDictionary());
cryptDictionary.Put(PdfName.CF, cfDictionary);
NUnit.Framework.Assert.IsTrue(PdfEncryption.ReadEmbeddedFilesOnlyFromEncryptDictionary(cryptDictionary));
}
[NUnit.Framework.Test]
public virtual void ReadEncryptEmbeddedFilesOnlyFromPdfDocumentIncorrectEffTest() {
PdfDictionary cryptDictionary = new PdfDictionary();
cryptDictionary.Put(PdfName.EFF, PdfName.Identity);
cryptDictionary.Put(PdfName.StmF, PdfName.Identity);
cryptDictionary.Put(PdfName.StrF, PdfName.Identity);
PdfDictionary cfDictionary = new PdfDictionary();
cfDictionary.Put(PdfName.StdCF, new PdfDictionary());
cryptDictionary.Put(PdfName.CF, cfDictionary);
NUnit.Framework.Assert.IsFalse(PdfEncryption.ReadEmbeddedFilesOnlyFromEncryptDictionary(cryptDictionary));
}
[NUnit.Framework.Test]
public virtual void ReadEncryptEmbeddedFilesOnlyFromPdfDocumentIncorrectStmFTest() {
PdfDictionary cryptDictionary = new PdfDictionary();
cryptDictionary.Put(PdfName.EFF, PdfName.StdCF);
cryptDictionary.Put(PdfName.StmF, PdfName.StdCF);
cryptDictionary.Put(PdfName.StrF, PdfName.Identity);
PdfDictionary cfDictionary = new PdfDictionary();
cfDictionary.Put(PdfName.StdCF, new PdfDictionary());
cryptDictionary.Put(PdfName.CF, cfDictionary);
NUnit.Framework.Assert.IsFalse(PdfEncryption.ReadEmbeddedFilesOnlyFromEncryptDictionary(cryptDictionary));
}
[NUnit.Framework.Test]
public virtual void ReadEncryptEmbeddedFilesOnlyFromPdfDocumentIncorrectStrFTest() {
PdfDictionary cryptDictionary = new PdfDictionary();
cryptDictionary.Put(PdfName.EFF, PdfName.StdCF);
cryptDictionary.Put(PdfName.StmF, PdfName.Identity);
cryptDictionary.Put(PdfName.StrF, PdfName.StdCF);
PdfDictionary cfDictionary = new PdfDictionary();
cfDictionary.Put(PdfName.StdCF, new PdfDictionary());
cryptDictionary.Put(PdfName.CF, cfDictionary);
NUnit.Framework.Assert.IsFalse(PdfEncryption.ReadEmbeddedFilesOnlyFromEncryptDictionary(cryptDictionary));
}
[NUnit.Framework.Test]
public virtual void ReadEncryptEmbeddedFilesOnlyFromPdfDocumentIncorrectCfTest() {
PdfDictionary cryptDictionary = new PdfDictionary();
cryptDictionary.Put(PdfName.EFF, PdfName.StdCF);
cryptDictionary.Put(PdfName.StmF, PdfName.Identity);
cryptDictionary.Put(PdfName.StrF, PdfName.Identity);
PdfDictionary cfDictionary = new PdfDictionary();
cfDictionary.Put(PdfName.DefaultCryptFilter, new PdfDictionary());
cryptDictionary.Put(PdfName.CF, cfDictionary);
NUnit.Framework.Assert.IsFalse(PdfEncryption.ReadEmbeddedFilesOnlyFromEncryptDictionary(cryptDictionary));
}
}
}

View File

@@ -0,0 +1,85 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.IO;
using TSpdf.Kernel.Logs;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("BouncyCastleIntegrationTest")]
public class PdfEncryptorTest : ExtendedTSpdfTest {
public static readonly String SOURCE_FOLDER = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/pdf/PdfEncryptorTest/";
public static readonly String DESTINATION_FOLDER = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/pdf/PdfEncryptorTest/";
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
CreateDestinationFolder(DESTINATION_FOLDER);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void EncryptFileTest() {
String outFileName = DESTINATION_FOLDER + "encryptFileTest.pdf";
String initialFileName = SOURCE_FOLDER + "initial.pdf";
PdfEncryptor encryptor = new PdfEncryptor();
EncryptionProperties encryptionProperties = new EncryptionProperties();
encryptionProperties.SetStandardEncryption(new byte[16], new byte[16], 0, 0);
encryptor.SetEncryptionProperties(encryptionProperties);
using (PdfReader initialFile = new PdfReader(initialFileName)) {
using (FileStream outputStream = new FileStream(outFileName, FileMode.Create)) {
encryptor.Encrypt(initialFile, outputStream);
}
}
ReaderProperties readerProperties = new ReaderProperties();
readerProperties.SetPassword(new byte[16]);
PdfReader outFile = new PdfReader(outFileName, readerProperties);
PdfDocument doc = new PdfDocument(outFile);
doc.Close();
NUnit.Framework.Assert.IsTrue(outFile.IsEncrypted());
}
}
}

View File

@@ -0,0 +1,105 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using TSpdf.IO.Font.Constants;
using TSpdf.Kernel.Font;
using TSpdf.Kernel.Pdf.Canvas;
using TSpdf.Kernel.Pdf.Extgstate;
using TSpdf.Kernel.Utils;
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("IntegrationTest")]
public class PdfExtGStateTest : ExtendedTSpdfTest {
public static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/pdf/PdfExtGStateTest/";
public static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/PdfExtGStateTest/";
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
CreateDestinationFolder(destinationFolder);
}
[NUnit.Framework.Test]
public virtual void EgsTest1() {
String destinationDocument = destinationFolder + "egsTest1.pdf";
PdfDocument document = new PdfDocument(new PdfWriter(destinationDocument));
//Create page and canvas
PdfPage page = document.AddNewPage();
PdfCanvas canvas = new PdfCanvas(page);
//Create ExtGState and fill it with line width and font
PdfExtGState egs = new PdfExtGState();
egs.GetPdfObject().Put(PdfName.LW, new PdfNumber(5));
PdfArray font = new PdfArray();
PdfFont pdfFont = PdfFontFactory.CreateFont(StandardFonts.COURIER);
document.AddFont(pdfFont);
font.Add(pdfFont.GetPdfObject());
font.Add(new PdfNumber(24));
egs.GetPdfObject().Put(PdfName.Font, font);
//Write ExtGState
canvas.SetExtGState(egs);
//Write text to check that font from ExtGState is applied
canvas.BeginText();
canvas.MoveText(50, 600);
canvas.ShowText("Courier, 24pt");
canvas.EndText();
//Draw line to check if ine width is applied
canvas.MoveTo(50, 500);
canvas.LineTo(300, 500);
canvas.Stroke();
//Write text again to check that font from page resources and font from ExtGState is the same.
canvas.BeginText();
canvas.SetFontAndSize(pdfFont, 36);
canvas.MoveText(50, 400);
canvas.ShowText("Courier, 36pt");
canvas.EndText();
canvas.Release();
page.Flush();
document.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationDocument, sourceFolder + "cmp_egsTest1.pdf"
, destinationFolder, "diff_"));
}
}
}

View File

@@ -0,0 +1,663 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.Collections.Generic;
using TSpdf.IO.Font;
using TSpdf.IO.Font.Constants;
using TSpdf.Kernel.Font;
using TSpdf.Kernel.Pdf.Canvas;
using TSpdf.Kernel.Utils;
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("IntegrationTest")]
public class PdfFontCacheTest : ExtendedTSpdfTest {
public static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/pdf/PdfFontCacheTest/";
private static readonly String fontsFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/pdf/fonts/";
public static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/pdf/PdfFontCacheTest/";
internal const String pangramme = "Amazingly few discotheques provide jukeboxes " + "but it now while sayingly ABEFGHJKNOPQRSTUWYZ?";
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
CreateDestinationFolder(destinationFolder);
}
private static readonly String[] TextSetHelloWorld = new String[] { "Hello World" };
private static readonly String[] TextSetWithABC = new String[] { "Hello World", "ABC", "XYZ" };
private static readonly String[] TextSetInternational = new String[] { "Hello World", "Привет, мир", "你好,世界"
, "안녕 세상" };
private static readonly String[] TextSetChinese = new String[] { "Hello World", "你好", "世界" };
[NUnit.Framework.Test]
public virtual void CreateDocumentWithKozmin() {
String testName = "DocumentWithKozmin";
String filename = destinationFolder + testName + ".pdf";
String cmpFilename = sourceFolder + "cmp_" + testName + ".pdf";
PdfDocument pdfDoc = CreateDocument(filename);
AddPagesWithFonts(pdfDoc, "KozMinPro-Regular", "UniJIS-UCS2-H", TextSetChinese);
AddPagesWithFonts(pdfDoc, "KozMinPro-Regular", "Adobe-Japan1-0", TextSetChinese);
pdfDoc.Close();
NUnit.Framework.Assert.AreEqual(2, CountPdfFonts(filename));
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpFilename, destinationFolder,
"diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateDocumentWithHelveticaMixEncodings() {
String testName = "DocumentWithHelveticaMixEncodings";
String filename = destinationFolder + testName + ".pdf";
String cmpFilename = sourceFolder + "cmp_" + testName + ".pdf";
PdfDocument pdfDoc = CreateDocument(filename);
String font = StandardFonts.HELVETICA;
String encoding = null;
AddPagesWithFonts(pdfDoc, font, encoding, TextSetWithABC);
AddPagesWithFonts(pdfDoc, font, "MacRoman", TextSetWithABC);
pdfDoc.Close();
NUnit.Framework.Assert.AreEqual(2, CountPdfFonts(filename));
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpFilename, destinationFolder,
"diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateDocumentWithHelvetica() {
String testName = "DocumentWithHelvetica";
String filename = destinationFolder + testName + ".pdf";
String cmpFilename = sourceFolder + "cmp_" + testName + ".pdf";
PdfDocument pdfDoc = CreateDocument(filename);
String font = StandardFonts.HELVETICA;
String encoding = null;
AddPagesWithFonts(pdfDoc, font, encoding, TextSetWithABC);
AddPagesWithFonts(pdfDoc, font, encoding, TextSetWithABC);
AddPagesWithFonts(pdfDoc, font, encoding, TextSetWithABC);
pdfDoc.Close();
NUnit.Framework.Assert.AreEqual(1, CountPdfFonts(filename));
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpFilename, destinationFolder,
"diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateDocumentWithHelveticaFlushed() {
String testName = "DocumentWithHelveticaFlushed";
String filename = destinationFolder + testName + ".pdf";
String cmpFilename = sourceFolder + "cmp_" + testName + ".pdf";
PdfDocument pdfDoc = CreateDocument(filename);
String font = StandardFonts.HELVETICA;
String encoding = null;
AddPagesWithFonts(pdfDoc, font, encoding, TextSetWithABC);
pdfDoc.FlushFonts();
AddPagesWithFonts(pdfDoc, font, encoding, TextSetWithABC);
pdfDoc.FlushFonts();
AddPagesWithFonts(pdfDoc, font, encoding, TextSetWithABC);
pdfDoc.Close();
//Flushed fonts cannot be reused.
NUnit.Framework.Assert.AreEqual(3, CountPdfFonts(filename));
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpFilename, destinationFolder,
"diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateDocumentWithTimesAndCustomEncoding() {
String testName = "DocumentTimesAndCustomEncoding";
String filename = destinationFolder + testName + ".pdf";
String cmpFilename = sourceFolder + "cmp_" + testName + ".pdf";
PdfDocument pdfDoc = CreateDocument(filename);
String font = StandardFonts.TIMES_ROMAN;
String encoding = "# full 'A' Aring 0041 'E' Egrave 0045 32 space 0020";
String[] AE = new String[] { "A E" };
AddPagesWithFonts(pdfDoc, font, encoding, AE);
AddPagesWithFonts(pdfDoc, font, encoding, AE);
AddPagesWithFonts(pdfDoc, font, encoding, AE);
pdfDoc.Close();
NUnit.Framework.Assert.AreEqual(1, CountPdfFonts(filename));
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpFilename, destinationFolder,
"diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateDocumentWithCourierAndWinAnsiEncodings() {
String testName = "DocumentCourierAndWinAnsiEncodings";
String filename = destinationFolder + testName + ".pdf";
String cmpFilename = sourceFolder + "cmp_" + testName + ".pdf";
PdfDocument pdfDoc = CreateDocument(filename);
String font = StandardFonts.COURIER;
PdfFontFactory.EmbeddingStrategy embeddingStrategy = PdfFontFactory.EmbeddingStrategy.PREFER_NOT_EMBEDDED;
//All those encodings actually the same winansi.
AddPagesWithFonts(pdfDoc, font, null, embeddingStrategy, TextSetWithABC);
AddPagesWithFonts(pdfDoc, font, "", embeddingStrategy, TextSetWithABC);
AddPagesWithFonts(pdfDoc, font, "WinAnsi", embeddingStrategy, TextSetWithABC);
AddPagesWithFonts(pdfDoc, font, "WinAnsiEncoding", embeddingStrategy, TextSetWithABC);
pdfDoc.Close();
NUnit.Framework.Assert.AreEqual(1, CountPdfFonts(filename));
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpFilename, destinationFolder,
"diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateDocumentWithAbserifAndIdentityHEncodings() {
String testName = "DocumentWithAbserifAndIdentityHEncodings";
String filename = destinationFolder + testName + ".pdf";
String cmpFilename = sourceFolder + "cmp_" + testName + ".pdf";
PdfDocument pdfDoc = CreateDocument(filename);
String font = fontsFolder + "abserif4_5.ttf";
//All those encodings actually the same Identity-H.
AddPagesWithFonts(pdfDoc, font, null, TextSetWithABC);
AddPagesWithFonts(pdfDoc, font, "", TextSetWithABC);
AddPagesWithFonts(pdfDoc, font, PdfEncodings.IDENTITY_H, TextSetWithABC);
pdfDoc.Close();
NUnit.Framework.Assert.AreEqual(1, CountPdfFonts(filename));
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpFilename, destinationFolder,
"diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateDocumentWithEmbeddedAbserifFirstWinAnsiThenIdentityHEncodings() {
String testName = "DocumentWithEmbeddedAbserifFirstWinAnsiThenIdentityHEncodings";
String filename = destinationFolder + testName + ".pdf";
String cmpFilename = sourceFolder + "cmp_" + testName + ".pdf";
PdfDocument pdfDoc = CreateDocument(filename);
String font = fontsFolder + "abserif4_5.ttf";
AddPagesWithFonts(pdfDoc, font, PdfEncodings.WINANSI, TextSetWithABC);
AddPagesWithFonts(pdfDoc, font, "", TextSetWithABC);
pdfDoc.Close();
NUnit.Framework.Assert.AreEqual(2, CountPdfFonts(filename));
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpFilename, destinationFolder,
"diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateDocumentWithEmbeddedAbserifFirstIdentityHThenWinAnsiEncodings() {
String testName = "DocumentWithEmbeddedAbserifFirstIdentityHThenWinAnsiEncodings";
String filename = destinationFolder + testName + ".pdf";
String cmpFilename = sourceFolder + "cmp_" + testName + ".pdf";
PdfDocument pdfDoc = CreateDocument(filename);
String font = fontsFolder + "abserif4_5.ttf";
AddPagesWithFonts(pdfDoc, font, "", TextSetWithABC);
AddPagesWithFonts(pdfDoc, font, PdfEncodings.WINANSI, TextSetWithABC);
pdfDoc.Close();
NUnit.Framework.Assert.AreEqual(2, CountPdfFonts(filename));
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpFilename, destinationFolder,
"diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateDocumentWithNotEmbeddedAbserifFirstWinAnsiThenIdentityHEncodings() {
String testName = "DocumentWithNotEmbeddedAbserifFirstWinAnsiThenIdentityHEncodings";
String filename = destinationFolder + testName + ".pdf";
String cmpFilename = sourceFolder + "cmp_" + testName + ".pdf";
PdfDocument pdfDoc = CreateDocument(filename);
String font = fontsFolder + "abserif4_5.ttf";
PdfFontFactory.EmbeddingStrategy embeddingStrategy = PdfFontFactory.EmbeddingStrategy.PREFER_NOT_EMBEDDED;
AddPagesWithFonts(pdfDoc, font, PdfEncodings.WINANSI, embeddingStrategy, TextSetWithABC);
AddPagesWithFonts(pdfDoc, font, "", embeddingStrategy, TextSetWithABC);
pdfDoc.Close();
NUnit.Framework.Assert.AreEqual(2, CountPdfFonts(filename));
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpFilename, destinationFolder,
"diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateDocumentWithNotEmbeddedAbserifFirstIdentityHThenWinAnsiEncodings() {
String testName = "DocumentWithNotEmbeddedAbserifFirstIdentityHThenWinAnsiEncodings";
String filename = destinationFolder + testName + ".pdf";
String cmpFilename = sourceFolder + "cmp_" + testName + ".pdf";
PdfDocument pdfDoc = CreateDocument(filename);
String font = fontsFolder + "abserif4_5.ttf";
PdfFontFactory.EmbeddingStrategy embeddingStrategy = PdfFontFactory.EmbeddingStrategy.PREFER_NOT_EMBEDDED;
AddPagesWithFonts(pdfDoc, font, "", embeddingStrategy, TextSetWithABC);
AddPagesWithFonts(pdfDoc, font, PdfEncodings.WINANSI, embeddingStrategy, TextSetWithABC);
pdfDoc.Close();
NUnit.Framework.Assert.AreEqual(2, CountPdfFonts(filename));
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpFilename, destinationFolder,
"diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateDocumentWithTimesBoldAndMacRomanEncodings() {
String testName = "DocumentTimesBoldAndMacRomanEncodings";
String filename = destinationFolder + testName + ".pdf";
String cmpFilename = sourceFolder + "cmp_" + testName + ".pdf";
PdfDocument pdfDoc = CreateDocument(filename);
String font = StandardFonts.TIMES_BOLD;
//All those encodings actually the same MacRoman.
AddPagesWithFonts(pdfDoc, font, "MacRoman", TextSetWithABC);
AddPagesWithFonts(pdfDoc, font, "MacRomanEncoding", TextSetWithABC);
pdfDoc.Close();
NUnit.Framework.Assert.AreEqual(1, CountPdfFonts(filename));
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpFilename, destinationFolder,
"diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateDocumentWithTrueTypeAsType0DefaultEncoding() {
String testName = "DocumentWithTrueTypeAsType0DefaultEncoding";
String filename = destinationFolder + testName + ".pdf";
String cmpFilename = sourceFolder + "cmp_" + testName + ".pdf";
PdfDocument pdfDoc = CreateDocument(filename);
String font = fontsFolder + "abserif4_5.ttf";
String encoding = null;
AddPagesWithFonts(pdfDoc, font, encoding, TextSetWithABC);
AddPagesWithFonts(pdfDoc, font, encoding, TextSetWithABC);
AddPagesWithFonts(pdfDoc, font, encoding, TextSetWithABC);
pdfDoc.Close();
NUnit.Framework.Assert.AreEqual(1, CountPdfFonts(filename));
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpFilename, destinationFolder,
"diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateDocumentWithTrueTypeAsTrueType() {
String testName = "DocumentWithTrueType";
String filename = destinationFolder + testName + ".pdf";
String cmpFilename = sourceFolder + "cmp_" + testName + ".pdf";
PdfDocument pdfDoc = CreateDocument(filename);
String font = fontsFolder + "abserif4_5.ttf";
String encoding = PdfEncodings.WINANSI;
AddPagesWithFonts(pdfDoc, font, encoding, TextSetWithABC);
AddPagesWithFonts(pdfDoc, font, encoding, TextSetWithABC);
AddPagesWithFonts(pdfDoc, font, encoding, TextSetWithABC);
pdfDoc.Close();
NUnit.Framework.Assert.AreEqual(1, CountPdfFonts(filename));
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpFilename, destinationFolder,
"diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateDocumentWithTrueTypeFlushed() {
String testName = "DocumentWithTrueTypeFlushed";
String filename = destinationFolder + testName + ".pdf";
String cmpFilename = sourceFolder + "cmp_" + testName + ".pdf";
PdfDocument pdfDoc = CreateDocument(filename);
String font = fontsFolder + "abserif4_5.ttf";
String encoding = null;
AddPagesWithFonts(pdfDoc, font, encoding, TextSetWithABC);
pdfDoc.FlushFonts();
AddPagesWithFonts(pdfDoc, font, encoding, TextSetWithABC);
pdfDoc.FlushFonts();
AddPagesWithFonts(pdfDoc, font, encoding, TextSetWithABC);
pdfDoc.Close();
//Flushed fonts cannot be reused.
//For some reason Acrobat shows only one font in Properties.
//RUPS shows 3 instances of the same font.
NUnit.Framework.Assert.AreEqual(3, CountPdfFonts(filename));
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpFilename, destinationFolder,
"diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateDocumentWithTrueTypeAsType0() {
String testName = "DocumentWithTrueTypeAsType0";
String filename = destinationFolder + testName + ".pdf";
String cmpFilename = sourceFolder + "cmp_" + testName + ".pdf";
PdfDocument pdfDoc = CreateDocument(filename);
String font = fontsFolder + "abserif4_5.ttf";
String encoding = "Identity-H";
AddPagesWithFonts(pdfDoc, font, encoding, TextSetWithABC);
AddPagesWithFonts(pdfDoc, font, encoding, TextSetWithABC);
AddPagesWithFonts(pdfDoc, font, encoding, TextSetWithABC);
pdfDoc.Close();
NUnit.Framework.Assert.AreEqual(1, CountPdfFonts(filename));
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpFilename, destinationFolder,
"diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateDocumentWithTrueTypeAsType0Flushed() {
String testName = "DocumentWithTrueTypeAsType0Flushed";
String filename = destinationFolder + testName + ".pdf";
String cmpFilename = sourceFolder + "cmp_" + testName + ".pdf";
PdfDocument pdfDoc = CreateDocument(filename);
String font = fontsFolder + "abserif4_5.ttf";
String encoding = "Identity-H";
AddPagesWithFonts(pdfDoc, font, encoding, TextSetWithABC);
pdfDoc.FlushFonts();
AddPagesWithFonts(pdfDoc, font, encoding, TextSetWithABC);
pdfDoc.FlushFonts();
AddPagesWithFonts(pdfDoc, font, encoding, TextSetWithABC);
pdfDoc.Close();
//Flushed fonts cannot be reused.
NUnit.Framework.Assert.AreEqual(3, CountPdfFonts(filename));
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpFilename, destinationFolder,
"diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateDocumentWithOpenTypeAsType0() {
String testName = "DocumentWithOpenTypeAsType0";
String filename = destinationFolder + testName + ".pdf";
String cmpFilename = sourceFolder + "cmp_" + testName + ".pdf";
PdfDocument pdfDoc = CreateDocument(filename);
String font = fontsFolder + "NotoSansCJKjp-Bold.otf";
String encoding = "Identity-H";
AddPagesWithFonts(pdfDoc, font, encoding, TextSetInternational);
AddPagesWithFonts(pdfDoc, font, encoding, TextSetInternational);
AddPagesWithFonts(pdfDoc, font, encoding, TextSetInternational);
pdfDoc.Close();
NUnit.Framework.Assert.AreEqual(1, CountPdfFonts(filename));
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpFilename, destinationFolder,
"diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateDocumentWithOpenTypeAsType0Flushed() {
String testName = "DocumentWithOpenTypeAsType0Flushed";
String filename = destinationFolder + testName + ".pdf";
String cmpFilename = sourceFolder + "cmp_" + testName + ".pdf";
PdfDocument pdfDoc = CreateDocument(filename);
String font = fontsFolder + "NotoSansCJKjp-Bold.otf";
String encoding = "Identity-H";
AddPagesWithFonts(pdfDoc, font, encoding, TextSetInternational);
pdfDoc.FlushFonts();
AddPagesWithFonts(pdfDoc, font, encoding, TextSetInternational);
pdfDoc.FlushFonts();
AddPagesWithFonts(pdfDoc, font, encoding, TextSetInternational);
pdfDoc.Close();
//Flushed fonts cannot be reused.
NUnit.Framework.Assert.AreEqual(3, CountPdfFonts(filename));
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpFilename, destinationFolder,
"diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateDocumentWithHelveticaFromDocument() {
String testName = "DocumentWithHelveticaFromDocument";
String input = sourceFolder + "DocumentWithHelvetica.pdf";
String filename = destinationFolder + testName + ".pdf";
String cmpFilename = sourceFolder + "cmp_" + testName + ".pdf";
PdfReader reader = new PdfReader(input);
PdfWriter writer = new PdfWriter(filename).SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
PdfDocument pdfDoc = new PdfDocument(reader, writer);
String font = StandardFonts.HELVETICA;
String encoding = "WinAnsiEncoding";
PdfDictionary fontDict = (PdfDictionary)pdfDoc.GetPdfObject(6);
NUnit.Framework.Assert.AreEqual(font, fontDict.GetAsName(PdfName.BaseFont).GetValue());
NUnit.Framework.Assert.AreEqual(encoding, fontDict.GetAsName(PdfName.Encoding).GetValue());
PdfFont documentFont = PdfFontFactory.CreateFont(fontDict);
//Add it to PdfDocument#documentFonts via PdfCanvas.
PdfCanvas canvas = new PdfCanvas(pdfDoc.AddNewPage());
canvas.BeginText().MoveText(36, 700).SetFontAndSize(documentFont, 20).ShowText(pangramme.JSubstring(0, pangramme
.Length / 2)).EndText().BeginText().SetFontAndSize(documentFont, 20).MoveText(36, 670).ShowText(pangramme
.Substring(pangramme.Length / 2)).EndText().Release();
//There is only one just loaded and used document font.
NUnit.Framework.Assert.AreEqual(1, pdfDoc.GetDocumentFonts().Count);
AddPagesWithFonts(pdfDoc, font, "WinAnsi", TextSetWithABC);
AddPagesWithFonts(pdfDoc, font, null, TextSetWithABC);
pdfDoc.Close();
//We cannot rely on font name for a document font, so we treat them as two different fonts.
//However we're trying to detect standard fonts in this case, so it will work.
NUnit.Framework.Assert.AreEqual(1, CountPdfFonts(filename));
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpFilename, destinationFolder,
"diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateDocumentWithHelveticaFromDocumentWithWrongEncoding() {
String testName = "DocumentWithHelveticaFromDocumentWithWrongEncoding";
String input = sourceFolder + "DocumentWithHelvetica.pdf";
String filename = destinationFolder + testName + ".pdf";
String cmpFilename = sourceFolder + "cmp_" + testName + ".pdf";
PdfReader reader = new PdfReader(input);
PdfWriter writer = new PdfWriter(filename).SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
PdfDocument pdfDoc = new PdfDocument(reader, writer);
String font = StandardFonts.HELVETICA;
String encoding = "WinAnsiEncoding";
PdfDictionary fontDict = (PdfDictionary)pdfDoc.GetPdfObject(6);
NUnit.Framework.Assert.AreEqual(font, fontDict.GetAsName(PdfName.BaseFont).GetValue());
NUnit.Framework.Assert.AreEqual(encoding, fontDict.GetAsName(PdfName.Encoding).GetValue());
PdfFont documentFont = PdfFontFactory.CreateFont(fontDict);
//Add it to PdfDocument#documentFonts via PdfCanvas.
PdfCanvas canvas = new PdfCanvas(pdfDoc.AddNewPage());
canvas.BeginText().MoveText(36, 700).SetFontAndSize(documentFont, 20).ShowText(pangramme.JSubstring(0, pangramme
.Length / 2)).EndText().BeginText().SetFontAndSize(documentFont, 20).MoveText(36, 670).ShowText(pangramme
.Substring(pangramme.Length / 2)).EndText().Release();
//There is only one just loaded and used document font.
NUnit.Framework.Assert.AreEqual(1, pdfDoc.GetDocumentFonts().Count);
AddPagesWithFonts(pdfDoc, font, null, TextSetWithABC);
AddPagesWithFonts(pdfDoc, font, "MacRoman", TextSetWithABC);
pdfDoc.Close();
//Two different encodings were used -> two fonts are expected.
NUnit.Framework.Assert.AreEqual(2, CountPdfFonts(filename));
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpFilename, destinationFolder,
"diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateDocumentWithTrueTypeAboriginalFromDocument() {
String testName = "DocumentWithTrueTypeAboriginalFromDocument";
String input = sourceFolder + "DocumentWithTrueTypeAboriginalSerif.pdf";
String filename = destinationFolder + testName + ".pdf";
String cmpFilename = sourceFolder + "cmp_" + testName + ".pdf";
PdfReader reader = new PdfReader(input);
PdfWriter writer = new PdfWriter(filename).SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
PdfDocument pdfDoc = new PdfDocument(reader, writer);
String font = "AboriginalSerif";
String encoding = "WinAnsiEncoding";
PdfDictionary fontDict = (PdfDictionary)pdfDoc.GetPdfObject(6);
NUnit.Framework.Assert.AreEqual(font, fontDict.GetAsName(PdfName.BaseFont).GetValue());
NUnit.Framework.Assert.AreEqual(encoding, fontDict.GetAsName(PdfName.Encoding).GetValue());
PdfFont documentFont = PdfFontFactory.CreateFont(fontDict);
//Add it to PdfDocument#documentFonts via PdfCanvas.
PdfCanvas canvas = new PdfCanvas(pdfDoc.AddNewPage());
canvas.BeginText().MoveText(36, 700).SetFontAndSize(documentFont, 20).ShowText(pangramme.JSubstring(0, pangramme
.Length / 2)).EndText().BeginText().SetFontAndSize(documentFont, 20).MoveText(36, 670).ShowText(pangramme
.Substring(pangramme.Length / 2)).EndText().Release();
//There is only one just loaded and used document font.
NUnit.Framework.Assert.AreEqual(1, pdfDoc.GetDocumentFonts().Count);
AddPagesWithFonts(pdfDoc, fontsFolder + "abserif4_5.ttf", "WinAnsi", TextSetWithABC);
pdfDoc.Close();
//We cannot rely on font name for a document font, so we treat them as two different fonts.
NUnit.Framework.Assert.AreEqual(2, CountPdfFonts(filename));
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpFilename, destinationFolder,
"diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateDocumentWithType1NotoFromDocument() {
String testName = "DocumentWithType1NotoFromDocument";
String input = sourceFolder + "DocumentWithType1Noto.pdf";
String filename = destinationFolder + testName + ".pdf";
String cmpFilename = sourceFolder + "cmp_" + testName + ".pdf";
PdfReader reader = new PdfReader(input);
PdfWriter writer = new PdfWriter(filename).SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
PdfDocument pdfDoc = new PdfDocument(reader, writer);
String font = "NotoSansCJKjp-Bold";
String encoding = "WinAnsiEncoding";
PdfDictionary fontDict = (PdfDictionary)pdfDoc.GetPdfObject(6);
NUnit.Framework.Assert.AreEqual(font, fontDict.GetAsName(PdfName.BaseFont).GetValue());
NUnit.Framework.Assert.AreEqual(encoding, fontDict.GetAsName(PdfName.Encoding).GetValue());
PdfFont documentFont = PdfFontFactory.CreateFont(fontDict);
//Add it to PdfDocument#documentFonts via PdfCanvas.
PdfCanvas canvas = new PdfCanvas(pdfDoc.AddNewPage());
canvas.BeginText().MoveText(36, 700).SetFontAndSize(documentFont, 20).ShowText(pangramme.JSubstring(0, pangramme
.Length / 2)).EndText().BeginText().SetFontAndSize(documentFont, 20).MoveText(36, 670).ShowText(pangramme
.Substring(pangramme.Length / 2)).EndText().Release();
//There is only one just loaded and used document font.
NUnit.Framework.Assert.AreEqual(1, pdfDoc.GetDocumentFonts().Count);
AddPagesWithFonts(pdfDoc, fontsFolder + "NotoSansCJKjp-Bold.otf", encoding, PdfFontFactory.EmbeddingStrategy
.FORCE_NOT_EMBEDDED, TextSetWithABC);
pdfDoc.Close();
//We cannot rely on font name for a document font, so we treat them as two different fonts.
NUnit.Framework.Assert.AreEqual(2, CountPdfFonts(filename));
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpFilename, destinationFolder,
"diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateDocumentWithType0AboriginalFromDocument1() {
String testName = "DocumentWithType0AboriginalFromDocument";
String input = sourceFolder + "DocumentWithType0AboriginalSerif.pdf";
String filename = destinationFolder + testName + ".pdf";
String cmpFilename = sourceFolder + "cmp_" + testName + ".pdf";
PdfReader reader = new PdfReader(input);
PdfWriter writer = new PdfWriter(filename).SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
PdfDocument pdfDoc = new PdfDocument(reader, writer);
String font = "AboriginalSerif";
String encoding = "Identity-H";
PdfDictionary fontDict = (PdfDictionary)pdfDoc.GetPdfObject(6);
NUnit.Framework.Assert.AreEqual(font, fontDict.GetAsName(PdfName.BaseFont).GetValue());
NUnit.Framework.Assert.AreEqual(encoding, fontDict.GetAsName(PdfName.Encoding).GetValue());
PdfFont documentFont = PdfFontFactory.CreateFont(fontDict);
//Add it to PdfDocument#documentFonts via PdfCanvas.
PdfCanvas canvas = new PdfCanvas(pdfDoc.AddNewPage());
canvas.BeginText().MoveText(36, 700).SetFontAndSize(documentFont, 20).ShowText(pangramme.JSubstring(0, pangramme
.Length / 2)).EndText().BeginText().SetFontAndSize(documentFont, 20).MoveText(36, 670).ShowText(pangramme
.Substring(pangramme.Length / 2)).EndText().Release();
//There is only one just loaded and used document font.
NUnit.Framework.Assert.AreEqual(1, pdfDoc.GetDocumentFonts().Count);
AddPagesWithFonts(pdfDoc, fontsFolder + "abserif4_5.ttf", encoding, TextSetWithABC);
pdfDoc.Close();
//We cannot rely on font name for a document font, so we treat them as two different fonts.
NUnit.Framework.Assert.AreEqual(2, CountPdfFonts(filename));
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpFilename, destinationFolder,
"diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateDocumentWithType0NotoFromDocument1() {
String testName = "DocumentWithType0NotoFromDocument";
String input = sourceFolder + "DocumentWithType0Noto.pdf";
String filename = destinationFolder + testName + ".pdf";
String cmpFilename = sourceFolder + "cmp_" + testName + ".pdf";
PdfReader reader = new PdfReader(input);
PdfWriter writer = new PdfWriter(filename).SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
PdfDocument pdfDoc = new PdfDocument(reader, writer);
String encoding = "Identity-H";
String font = "NotoSansCJKjp-Bold-" + encoding;
PdfDictionary fontDict = (PdfDictionary)pdfDoc.GetPdfObject(6);
NUnit.Framework.Assert.AreEqual(font, fontDict.GetAsName(PdfName.BaseFont).GetValue());
NUnit.Framework.Assert.AreEqual(encoding, fontDict.GetAsName(PdfName.Encoding).GetValue());
PdfFont documentFont = PdfFontFactory.CreateFont(fontDict);
//Add it to PdfDocument#documentFonts via PdfCanvas.
PdfCanvas canvas = new PdfCanvas(pdfDoc.AddNewPage());
canvas.BeginText().MoveText(36, 700).SetFontAndSize(documentFont, 20).ShowText(pangramme.JSubstring(0, pangramme
.Length / 2)).EndText().BeginText().SetFontAndSize(documentFont, 20).MoveText(36, 670).ShowText(pangramme
.Substring(pangramme.Length / 2)).EndText().Release();
//There is only one just loaded and used document font.
NUnit.Framework.Assert.AreEqual(1, pdfDoc.GetDocumentFonts().Count);
AddPagesWithFonts(pdfDoc, fontsFolder + "NotoSansCJKjp-Bold.otf", PdfEncodings.WINANSI, PdfFontFactory.EmbeddingStrategy
.PREFER_NOT_EMBEDDED, TextSetWithABC);
pdfDoc.Close();
//We cannot rely on font name for a document font, so we treat them as two different fonts.
NUnit.Framework.Assert.AreEqual(2, CountPdfFonts(filename));
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpFilename, destinationFolder,
"diff_"));
}
[NUnit.Framework.Test]
public virtual void CreateDocumentWithType3Font() {
String testName = "DocumentWithType3Font";
String filename = destinationFolder + testName + ".pdf";
String cmpFilename = sourceFolder + "cmp_" + testName + ".pdf";
PdfDocument pdfDoc = CreateDocument(filename);
PdfType3Font type3Font = PdfFontFactory.CreateType3Font(pdfDoc, false);
Type3Glyph type3Glyph = type3Font.AddGlyph('A', 600, 0, 0, 600, 700);
type3Glyph.SetLineWidth(100);
type3Glyph.MoveTo(5, 5);
type3Glyph.LineTo(300, 695);
type3Glyph.LineTo(595, 5);
type3Glyph.ClosePathFillStroke();
PdfPage page = pdfDoc.AddNewPage();
PdfCanvas canvas = new PdfCanvas(page);
canvas.SaveState().BeginText().SetFontAndSize(type3Font, 36).MoveText(50, 700).ShowText("AA").EndText();
type3Font = PdfFontFactory.CreateType3Font(pdfDoc, false);
type3Glyph = type3Font.AddGlyph('A', 600, 0, 0, 600, 700);
type3Glyph.SetLineWidth(100);
type3Glyph.MoveTo(5, 5);
type3Glyph.LineTo(300, 695);
type3Glyph.LineTo(595, 5);
type3Glyph.ClosePathFillStroke();
canvas = new PdfCanvas(page);
canvas.SaveState().BeginText().SetFontAndSize(type3Font, 36).MoveText(50, 650).ShowText("AAA").EndText();
pdfDoc.Close();
//PdfType3Font comparing returns false;
NUnit.Framework.Assert.AreEqual(2, CountPdfFonts(filename));
// reading and comparing text
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, cmpFilename, destinationFolder,
"diff_"));
}
private void AddPagesWithFonts(PdfDocument pdfDoc, String fontProgram, String fontEncoding, String[] text) {
AddPagesWithFonts(pdfDoc, fontProgram, fontEncoding, PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED, text
);
}
private void AddPagesWithFonts(PdfDocument pdfDoc, String fontProgram, String fontEncoding, PdfFontFactory.EmbeddingStrategy
embeddingStrategy, String[] text) {
int top = 700;
foreach (String t in text) {
PdfPage page = pdfDoc.AddNewPage();
PdfCanvas canvas = new PdfCanvas(page);
canvas.SaveState().BeginText().MoveText(36, top).SetFontAndSize(PdfFontFactory.CreateFont(fontProgram, fontEncoding
, embeddingStrategy, pdfDoc), 72).ShowText(t).EndText().RestoreState();
canvas.Release();
page.Flush();
}
}
private int CountPdfFonts(String filename) {
PdfReader reader = new PdfReader(filename);
PdfDocument pdfDoc = new PdfDocument(reader);
ICollection<PdfIndirectReference> fonts = new HashSet<PdfIndirectReference>();
for (int i = 1; i <= pdfDoc.GetNumberOfPages(); i++) {
PdfPage page = pdfDoc.GetPage(i);
foreach (PdfObject value in page.GetResources().GetResource(PdfName.Font).Values()) {
fonts.Add(value.GetIndirectReference());
}
}
return fonts.Count;
}
private PdfDocument CreateDocument(String filename) {
PdfWriter writer = new PdfWriter(filename).SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
return new PdfDocument(writer);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,143 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System.IO;
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("UnitTest")]
public class PdfIndirectReferenceTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void BaseEqualsTest() {
PdfIndirectReference reference = new PdfIndirectReference(null, 41, 0);
NUnit.Framework.Assert.IsTrue(reference.Equals(reference));
NUnit.Framework.Assert.IsFalse(reference.Equals(null));
PdfIndirectReferenceTest.TestIndirectReference testIndirectReference = new PdfIndirectReferenceTest.TestIndirectReference
(null, 41, 0);
NUnit.Framework.Assert.IsFalse(reference.Equals(testIndirectReference));
NUnit.Framework.Assert.IsFalse(testIndirectReference.Equals(reference));
}
[NUnit.Framework.Test]
public virtual void EqualsWithDocTest() {
using (PdfDocument firstDoc = new PdfDocument(new PdfWriter(new MemoryStream()))) {
using (PdfDocument secondDoc = new PdfDocument(new PdfWriter(new MemoryStream()))) {
// add a page to avoid exception throwing on close
firstDoc.AddNewPage();
secondDoc.AddNewPage();
PdfIndirectReference obj41Gen0 = new PdfIndirectReference(firstDoc, 41, 0);
NUnit.Framework.Assert.IsTrue(obj41Gen0.Equals(new PdfIndirectReference(firstDoc, 41, 0)));
NUnit.Framework.Assert.IsFalse(obj41Gen0.Equals(new PdfIndirectReference(firstDoc, 42, 0)));
NUnit.Framework.Assert.IsFalse(obj41Gen0.Equals(new PdfIndirectReference(firstDoc, 41, 1)));
NUnit.Framework.Assert.IsFalse(obj41Gen0.Equals(new PdfIndirectReference(null, 41, 0)));
NUnit.Framework.Assert.IsFalse(obj41Gen0.Equals(new PdfIndirectReference(secondDoc, 41, 0)));
}
}
}
[NUnit.Framework.Test]
public virtual void EqualsWithNullDocsTest() {
PdfIndirectReference obj41Gen0 = new PdfIndirectReference(null, 41, 0);
NUnit.Framework.Assert.IsTrue(obj41Gen0.Equals(new PdfIndirectReference(null, 41, 0)));
NUnit.Framework.Assert.IsFalse(obj41Gen0.Equals(new PdfIndirectReference(null, 42, 0)));
NUnit.Framework.Assert.IsFalse(obj41Gen0.Equals(new PdfIndirectReference(null, 41, 1)));
using (PdfDocument doc = new PdfDocument(new PdfWriter(new MemoryStream()))) {
// add a page to avoid exception throwing on close
doc.AddNewPage();
NUnit.Framework.Assert.IsFalse(obj41Gen0.Equals(new PdfIndirectReference(doc, 41, 0)));
}
}
[NUnit.Framework.Test]
public virtual void HashCodeTest() {
PdfIndirectReference firstReference = new PdfIndirectReference(null, 41, 7);
PdfIndirectReference secondReference = new PdfIndirectReference(null, 41, 7);
NUnit.Framework.Assert.AreNotSame(firstReference, secondReference);
NUnit.Framework.Assert.AreEqual(firstReference.GetHashCode(), secondReference.GetHashCode());
NUnit.Framework.Assert.AreNotEqual(firstReference.GetHashCode(), new PdfIndirectReference(null, 42, 7).GetHashCode
());
NUnit.Framework.Assert.AreNotEqual(firstReference.GetHashCode(), new PdfIndirectReference(null, 41, 5).GetHashCode
());
using (PdfDocument firstDoc = new PdfDocument(new PdfWriter(new MemoryStream()))) {
using (PdfDocument secondDoc = new PdfDocument(new PdfWriter(new MemoryStream()))) {
// add a page to avoid exception throwing on close
firstDoc.AddNewPage();
secondDoc.AddNewPage();
PdfIndirectReference obj41Gen0 = new PdfIndirectReference(firstDoc, 41, 0);
NUnit.Framework.Assert.AreEqual(obj41Gen0.GetHashCode(), new PdfIndirectReference(firstDoc, 41, 0).GetHashCode
());
NUnit.Framework.Assert.AreNotEqual(obj41Gen0.GetHashCode(), new PdfIndirectReference(secondDoc, 41, 0).GetHashCode
());
NUnit.Framework.Assert.AreNotEqual(obj41Gen0.GetHashCode(), new PdfIndirectReference(null, 41, 0).GetHashCode
());
}
}
}
[NUnit.Framework.Test]
public virtual void CompareToWithDocTest() {
using (PdfDocument firstDoc = new PdfDocument(new PdfWriter(new MemoryStream()))) {
using (PdfDocument secondDoc = new PdfDocument(new PdfWriter(new MemoryStream()))) {
// add a page to avoid exception throwing on close
firstDoc.AddNewPage();
secondDoc.AddNewPage();
PdfIndirectReference obj41Gen7 = new PdfIndirectReference(firstDoc, 41, 7);
NUnit.Framework.Assert.AreEqual(0, obj41Gen7.CompareTo(new PdfIndirectReference(firstDoc, 41, 7)));
NUnit.Framework.Assert.AreEqual(1, obj41Gen7.CompareTo(new PdfIndirectReference(firstDoc, 11, 17)));
NUnit.Framework.Assert.AreEqual(-1, obj41Gen7.CompareTo(new PdfIndirectReference(firstDoc, 51, 0)));
NUnit.Framework.Assert.AreEqual(-1, obj41Gen7.CompareTo(new PdfIndirectReference(firstDoc, 41, 17)));
NUnit.Framework.Assert.AreEqual(1, obj41Gen7.CompareTo(new PdfIndirectReference(firstDoc, 41, 0)));
NUnit.Framework.Assert.AreEqual(1, obj41Gen7.CompareTo(new PdfIndirectReference(null, 41, 7)));
// we do not expect that ids could be equal
int docIdsCompareResult = firstDoc.GetDocumentId() > secondDoc.GetDocumentId() ? 1 : -1;
NUnit.Framework.Assert.AreEqual(docIdsCompareResult, obj41Gen7.CompareTo(new PdfIndirectReference(secondDoc
, 41, 7)));
NUnit.Framework.Assert.AreEqual(-docIdsCompareResult, new PdfIndirectReference(secondDoc, 41, 7).CompareTo
(obj41Gen7));
}
}
}
[NUnit.Framework.Test]
public virtual void CompareToWithNullDocsTest() {
PdfIndirectReference obj41Gen7 = new PdfIndirectReference(null, 41, 7);
NUnit.Framework.Assert.AreEqual(0, obj41Gen7.CompareTo(new PdfIndirectReference(null, 41, 7)));
NUnit.Framework.Assert.AreEqual(1, obj41Gen7.CompareTo(new PdfIndirectReference(null, 11, 17)));
NUnit.Framework.Assert.AreEqual(-1, obj41Gen7.CompareTo(new PdfIndirectReference(null, 51, 0)));
NUnit.Framework.Assert.AreEqual(-1, obj41Gen7.CompareTo(new PdfIndirectReference(null, 41, 17)));
NUnit.Framework.Assert.AreEqual(1, obj41Gen7.CompareTo(new PdfIndirectReference(null, 41, 0)));
using (PdfDocument doc = new PdfDocument(new PdfWriter(new MemoryStream()))) {
// add a page to avoid exception throwing on close
doc.AddNewPage();
NUnit.Framework.Assert.AreEqual(-1, obj41Gen7.CompareTo(new PdfIndirectReference(doc, 41, 7)));
NUnit.Framework.Assert.AreEqual(1, obj41Gen7.CompareTo(new PdfIndirectReference(doc, 11, 17)));
NUnit.Framework.Assert.AreEqual(1, obj41Gen7.CompareTo(new PdfIndirectReference(doc, 41, 0)));
}
}
private class TestIndirectReference : PdfIndirectReference {
public TestIndirectReference(PdfDocument doc, int objNr, int genNr)
: base(doc, objNr, genNr) {
}
}
}
}

View File

@@ -0,0 +1,92 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("UnitTest")]
public class PdfNameTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void SpecialCharactersTest() {
String str1 = " %()<>";
String str2 = "[]{}/#";
PdfName name1 = new PdfName(str1);
NUnit.Framework.Assert.AreEqual(str1, CreateStringByEscaped(name1.GetInternalContent()));
PdfName name2 = new PdfName(str2);
NUnit.Framework.Assert.AreEqual(str2, CreateStringByEscaped(name2.GetInternalContent()));
}
[NUnit.Framework.Test]
public virtual void BasicCompareToTest() {
// /#C3#9Cberschrift_1
byte[] name1Content = new byte[] { 35, 67, 51, 35, 57, 67, 98, 101, 114, 115, 99, 104, 114, 105, 102, 116,
95, 49 };
// /TOC-1
byte[] name2Content = new byte[] { 84, 79, 67, 45, 49 };
// /NormalParagraphStyle
byte[] name3Content = new byte[] { 78, 111, 114, 109, 97, 108, 80, 97, 114, 97, 103, 114, 97, 112, 104, 83
, 116, 121, 108, 101 };
// /#C3#9Cberschrift_1, Überschrift_1
PdfName name1 = new PdfName(name1Content);
PdfName name1ContentOnly = new PdfName(name1Content);
// /TOC-1, TOC-1
PdfName name2 = new PdfName(name2Content);
// /NormalParagraphStyle, NormalParagraphStyle
PdfName name3 = new PdfName(name3Content);
name1.GenerateValue();
name2.GenerateValue();
int oneToTwo = name1.CompareTo(name2);
int twoToOne = name2.CompareTo(name1);
int oneToThree = name1.CompareTo(name3);
int twoToThree = name2.CompareTo(name3);
int oneToOneContent = name1.CompareTo(name1ContentOnly);
int oneContentToTwo = name1ContentOnly.CompareTo(name2);
double delta = 1e-8;
NUnit.Framework.Assert.AreEqual(Math.Sign(oneToTwo), -Math.Sign(twoToOne), delta);
NUnit.Framework.Assert.AreEqual(Math.Sign(oneToTwo), Math.Sign(twoToThree), delta);
NUnit.Framework.Assert.AreEqual(Math.Sign(oneToTwo), Math.Sign(oneToThree), delta);
NUnit.Framework.Assert.AreEqual(oneToOneContent, 0);
NUnit.Framework.Assert.AreEqual(Math.Sign(oneToTwo), Math.Sign(oneContentToTwo), delta);
}
}
}

View File

@@ -0,0 +1,208 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.Collections.Generic;
using System.IO;
using TSpdf.IO.Font.Constants;
using TSpdf.Kernel.Colors;
using TSpdf.Kernel.Font;
using TSpdf.Kernel.Geom;
using TSpdf.Kernel.Pdf.Annot;
using TSpdf.Kernel.Pdf.Canvas;
using TSpdf.Kernel.Pdf.Filespec;
using TSpdf.Kernel.Pdf.Xobject;
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("IntegrationTest")]
public class PdfNameTreeTest : ExtendedTSpdfTest {
public static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/pdf/PdfNameTreeTest/";
public static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/pdf/PdfNameTreeTest/";
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
CreateOrClearDestinationFolder(destinationFolder);
}
[NUnit.Framework.Test]
public virtual void EmbeddedFileAndJavascriptTest() {
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourceFolder + "FileWithSingleAttachment.pdf"));
PdfNameTree embeddedFilesNameTree = pdfDocument.GetCatalog().GetNameTree(PdfName.EmbeddedFiles);
IDictionary<PdfString, PdfObject> objs = embeddedFilesNameTree.GetNames();
PdfNameTree javascript = pdfDocument.GetCatalog().GetNameTree(PdfName.JavaScript);
IDictionary<PdfString, PdfObject> objs2 = javascript.GetNames();
pdfDocument.Close();
NUnit.Framework.Assert.AreEqual(1, objs.Count);
NUnit.Framework.Assert.AreEqual(1, objs2.Count);
}
[NUnit.Framework.Test]
public virtual void EmbeddedFileAddedInAppendModeTest() {
//Create input document
MemoryStream boasEmpty = new MemoryStream();
PdfWriter emptyDocWriter = new PdfWriter(boasEmpty);
PdfDocument emptyDoc = new PdfDocument(emptyDocWriter);
emptyDoc.AddNewPage();
PdfDictionary emptyNamesDic = new PdfDictionary();
emptyNamesDic.MakeIndirect(emptyDoc);
emptyDoc.GetCatalog().GetPdfObject().Put(PdfName.Names, emptyNamesDic);
emptyDoc.Close();
//Create input document
MemoryStream boasAttached = new MemoryStream();
PdfWriter attachDocWriter = new PdfWriter(boasAttached);
PdfDocument attachDoc = new PdfDocument(attachDocWriter);
attachDoc.AddNewPage();
attachDoc.Close();
//Attach file in append mode
PdfReader appendReader = new PdfReader(new MemoryStream(boasEmpty.ToArray()));
MemoryStream boasAppend = new MemoryStream();
PdfWriter appendWriter = new PdfWriter(boasAppend);
PdfDocument appendDoc = new PdfDocument(appendReader, appendWriter, new StampingProperties().UseAppendMode
());
appendDoc.AddFileAttachment("Test File", PdfFileSpec.CreateEmbeddedFileSpec(appendDoc, boasAttached.ToArray
(), "Append Embedded File test", "Test file", null));
appendDoc.Close();
//Check final result
PdfReader finalReader = new PdfReader(new MemoryStream(boasAppend.ToArray()));
PdfDocument finalDoc = new PdfDocument(finalReader);
PdfNameTree embeddedFilesNameTree = finalDoc.GetCatalog().GetNameTree(PdfName.EmbeddedFiles);
IDictionary<PdfString, PdfObject> embeddedFilesMap = embeddedFilesNameTree.GetNames();
NUnit.Framework.Assert.IsTrue(embeddedFilesMap.Count > 0);
NUnit.Framework.Assert.IsTrue(embeddedFilesMap.ContainsKey(new PdfString("Test File")));
}
[NUnit.Framework.Test]
public virtual void AnnotationAppearanceTest() {
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(destinationFolder + "AnnotationAppearanceTest.pdf"
));
PdfPage page = pdfDocument.AddNewPage();
PdfCanvas canvas = new PdfCanvas(page);
canvas.SetFillColor(ColorConstants.MAGENTA).BeginText().SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts
.TIMES_ROMAN), 30).SetTextMatrix(25, 500).ShowText("This file has AP key in Names dictionary").EndText
();
PdfArray array = new PdfArray();
array.Add(new PdfString("normalAppearance"));
array.Add(new PdfAnnotationAppearance().SetState(PdfName.N, new PdfFormXObject(new Rectangle(50, 50, 50, 50
))).GetPdfObject());
PdfDictionary dict = new PdfDictionary();
dict.Put(PdfName.Names, array);
PdfDictionary dictionary = new PdfDictionary();
dictionary.Put(PdfName.AP, dict);
pdfDocument.GetCatalog().GetPdfObject().Put(PdfName.Names, dictionary);
PdfNameTree appearance = pdfDocument.GetCatalog().GetNameTree(PdfName.AP);
IDictionary<PdfString, PdfObject> objs = appearance.GetNames();
pdfDocument.Close();
NUnit.Framework.Assert.AreEqual(1, objs.Count);
}
[NUnit.Framework.Test]
public virtual void SetModifiedFlagTest() {
TestSetModified(false);
}
[NUnit.Framework.Test]
public virtual void SetModifiedFlagAppendModeTest() {
TestSetModified(true);
}
[NUnit.Framework.Test]
public virtual void CheckNamesOrder() {
PdfDocument doc = new PdfDocument(new PdfReader(sourceFolder + "namedDestinations.pdf"));
IList<String> expectedNames = new List<String>();
expectedNames.Add("Destination_1");
expectedNames.Add("Destination_2");
expectedNames.Add("Destination_3");
expectedNames.Add("Destination_4");
expectedNames.Add("Destination_5");
System.Console.Out.WriteLine("Expected names: " + expectedNames);
for (int i = 0; i < 10; i++) {
IPdfNameTreeAccess names = doc.GetCatalog().GetNameTree(PdfName.Dests);
IList<String> actualNames = new List<String>();
foreach (PdfString name in names.GetKeys()) {
actualNames.Add(name.ToUnicodeString());
}
System.Console.Out.WriteLine("Actual names: " + actualNames);
NUnit.Framework.Assert.AreEqual(expectedNames, actualNames);
}
doc.Close();
}
private static void TestSetModified(bool isAppendMode) {
PdfString[] expectedKeys = new PdfString[] { new PdfString("new_key1"), new PdfString("new_key2"), new PdfString
("new_key3") };
MemoryStream sourceFile = CreateDocumentInMemory();
MemoryStream modifiedFile = new MemoryStream();
PdfReader reader = new PdfReader(new MemoryStream(sourceFile.ToArray()));
PdfDocument pdfDoc = isAppendMode ? new PdfDocument(reader, new PdfWriter(modifiedFile), new StampingProperties
().UseAppendMode()) : new PdfDocument(reader, new PdfWriter(modifiedFile));
PdfNameTree nameTree = pdfDoc.GetCatalog().GetNameTree(PdfName.Dests);
IDictionary<PdfString, PdfObject> names = nameTree.GetNames();
IList<PdfString> keys = new List<PdfString>(names.Keys);
for (int i = 0; i < keys.Count; i++) {
names.Put(expectedKeys[i], names.Get(keys[i]));
names.JRemove(keys[i]);
}
nameTree.SetModified();
pdfDoc.Close();
reader = new PdfReader(new MemoryStream(modifiedFile.ToArray()));
pdfDoc = new PdfDocument(reader);
nameTree = pdfDoc.GetCatalog().GetNameTree(PdfName.Dests);
ICollection<PdfString> actualKeys = nameTree.GetNames().Keys;
NUnit.Framework.Assert.AreEqual(expectedKeys, actualKeys.ToArray());
}
private static MemoryStream CreateDocumentInMemory() {
MemoryStream boas = new MemoryStream();
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(boas));
pdfDoc.AddNewPage();
pdfDoc.GetCatalog().GetNameTree(PdfName.Dests).AddEntry("key1", new PdfArray(new float[] { 0, 0, 0, 0 }));
pdfDoc.GetCatalog().GetNameTree(PdfName.Dests).AddEntry("key2", new PdfArray(new float[] { 1, 1, 1, 1 }));
pdfDoc.GetCatalog().GetNameTree(PdfName.Dests).AddEntry("key3", new PdfArray(new float[] { 2, 2, 2, 2 }));
pdfDoc.Close();
return boas;
}
}
}

View File

@@ -0,0 +1,72 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("UnitTest")]
public class PdfNumberTest : ExtendedTSpdfTest {
private const double DELTA = 0.0001;
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.ATTEMPT_PROCESS_NAN)]
public virtual void TestNaN() {
PdfNumber number = new PdfNumber(double.NaN);
// code for "0"
byte[] expected = new byte[] { 48 };
NUnit.Framework.Assert.AreEqual(expected, number.GetInternalContent());
}
[NUnit.Framework.Test]
public virtual void IntValueInPdfNumberTest() {
double valueToSet = 3000000000d;
PdfNumber number = new PdfNumber(valueToSet);
NUnit.Framework.Assert.AreEqual(valueToSet, number.GetValue(), DELTA);
NUnit.Framework.Assert.AreEqual(valueToSet, number.DoubleValue(), DELTA);
NUnit.Framework.Assert.AreEqual(int.MaxValue, number.IntValue());
valueToSet = 50d;
number.SetValue(valueToSet + DELTA);
NUnit.Framework.Assert.AreEqual(50, number.IntValue());
}
}
}

View File

@@ -0,0 +1,150 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.Kernel.Exceptions;
using TSpdf.Kernel.Geom;
using TSpdf.Kernel.Pdf.Annot;
using TSpdf.Kernel.Utils;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("IntegrationTest")]
public class PdfObjectReleaseTest : ExtendedTSpdfTest {
public static readonly String SOURCE_FOLDER = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/pdf/PdfObjectReleaseTest/";
public static readonly String DESTINATION_FOLDER = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/pdf/PdfObjectReleaseTest/";
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
CreateOrClearDestinationFolder(DESTINATION_FOLDER);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.FORBID_RELEASE_IS_SET, Count = 108)]
public virtual void ReleaseObjectsInDocWithStructTreeRootTest() {
SinglePdfObjectReleaseTest("releaseObjectsInDocWithStructTreeRoot.pdf", "releaseObjectsInDocWithStructTreeRoot_stamping.pdf"
, "releaseObjectsInDocWithStructTreeRoot_stamping_release.pdf");
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.FORBID_RELEASE_IS_SET, Count = 5)]
public virtual void ReleaseObjectsInDocWithXfaTest() {
SinglePdfObjectReleaseTest("releaseObjectsInDocWithXfa.pdf", "releaseObjectsInDocWithXfa_stamping.pdf", "releaseObjectsInDocWithXfa_stamping_release.pdf"
);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.FORBID_RELEASE_IS_SET, Count = 3)]
public virtual void ReleaseObjectsInSimpleDocTest() {
SinglePdfObjectReleaseTest("releaseObjectsInSimpleDoc.pdf", "releaseObjectsInSimpleDoc_stamping.pdf", "releaseObjectsInSimpleDoc_stamping_release.pdf"
);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.FORBID_RELEASE_IS_SET)]
public virtual void ReleaseCatalogTest() {
String srcFile = SOURCE_FOLDER + "releaseObjectsInSimpleDoc.pdf";
String release = DESTINATION_FOLDER + "outReleaseObjectsInSimpleDoc.pdf";
using (PdfDocument doc = new PdfDocument(new PdfReader(srcFile), new PdfWriter(release))) {
doc.GetCatalog().GetPdfObject().Release();
}
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(release, srcFile, DESTINATION_FOLDER));
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.FORBID_RELEASE_IS_SET)]
public virtual void ReleasePagesTest() {
String srcFile = SOURCE_FOLDER + "releaseObjectsInSimpleDoc.pdf";
String release = DESTINATION_FOLDER + "outReleaseObjectsInSimpleDoc.pdf";
using (PdfDocument doc = new PdfDocument(new PdfReader(srcFile), new PdfWriter(release))) {
doc.GetCatalog().GetPdfObject().GetAsDictionary(PdfName.Pages).Release();
}
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(release, srcFile, DESTINATION_FOLDER));
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.FORBID_RELEASE_IS_SET)]
public virtual void ReleaseStructTreeRootTest() {
String srcFile = SOURCE_FOLDER + "releaseObjectsInDocWithStructTreeRoot.pdf";
String release = DESTINATION_FOLDER + "outReleaseObjectsInDocWithStructTreeRoot.pdf";
using (PdfDocument doc = new PdfDocument(new PdfReader(srcFile), new PdfWriter(release))) {
doc.GetStructTreeRoot().GetPdfObject().Release();
}
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(release, srcFile, DESTINATION_FOLDER));
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.FORBID_RELEASE_IS_SET)]
public virtual void ReleaseModifiedObjectTest() {
String srcFile = SOURCE_FOLDER + "releaseModifiedObject.pdf";
String cmpFile = SOURCE_FOLDER + "cmp_releaseModifiedObject.pdf";
String outFile = DESTINATION_FOLDER + "releaseModifiedObject.pdf";
using (PdfDocument doc = new PdfDocument(new PdfReader(srcFile), new PdfWriter(outFile))) {
PdfAnnotation annots = doc.GetPage(1).GetAnnotations()[0];
annots.SetRectangle(new PdfArray(new Rectangle(100, 100, 80, 50)));
annots.GetPdfObject().Release();
}
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFile, cmpFile, DESTINATION_FOLDER));
}
[NUnit.Framework.Test]
public virtual void AddingReleasedObjectToDocumentTest() {
String srcFile = SOURCE_FOLDER + "releaseObjectsInSimpleDoc.pdf";
PdfDocument doc = new PdfDocument(new PdfReader(srcFile), new PdfWriter(SOURCE_FOLDER + "addingReleasedObjectToDocument.pdf"
));
try {
PdfObject releasedObj = doc.GetPdfObject(1);
releasedObj.Release();
doc.GetCatalog().Put(PdfName.Outlines, releasedObj);
}
finally {
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => doc.Close());
NUnit.Framework.Assert.AreEqual("Cannot write object after it was released." + " In normal situation the object must be read once again before being written."
, e.Message);
}
}
private void SinglePdfObjectReleaseTest(String inputFilename, String outStampingFilename, String outStampingReleaseFilename
) {
String srcFile = SOURCE_FOLDER + inputFilename;
String outPureStamping = DESTINATION_FOLDER + outStampingFilename;
String outStampingRelease = DESTINATION_FOLDER + outStampingReleaseFilename;
PdfDocument doc = new PdfDocument(new PdfReader(srcFile), new PdfWriter(outPureStamping));
// We open/close document to make sure that the results of release logic and simple overwriting coincide.
doc.Close();
PdfDocument stamperRelease = new PdfDocument(new PdfReader(srcFile), new PdfWriter(outStampingRelease));
for (int i = 0; i < stamperRelease.GetNumberOfPdfObjects(); i++) {
PdfObject pdfObject = stamperRelease.GetPdfObject(i);
if (pdfObject != null) {
stamperRelease.GetPdfObject(i).Release();
}
}
stamperRelease.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outStampingRelease, outPureStamping, DESTINATION_FOLDER
));
}
}
}

View File

@@ -0,0 +1,60 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.IO.Source;
using TSpdf.Kernel.Exceptions;
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("UnitTest")]
public class PdfObjectStreamUnitTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void CannotAddMoreObjectsThanMaxStreamSizeTest() {
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
PdfObjectStream pdfObjectStream = new PdfObjectStream(pdfDocument);
PdfNumber number = new PdfNumber(1);
number.MakeIndirect(pdfDocument);
//Here we add the maximum number of objects, so that adding the next one will cause an exception
for (int i = 0; i < PdfObjectStream.MAX_OBJ_STREAM_SIZE; i++) {
pdfObjectStream.AddObject(number);
}
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfObjectStream.AddObject(number
));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.PDF_OBJECT_STREAM_REACH_MAX_SIZE, exception
.Message);
}
[NUnit.Framework.Test]
public virtual void ObjectCanBeAddedToObjectStreamWithSizeLessThenMaxStreamSizeTest() {
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
PdfObjectStream pdfObjectStream = new PdfObjectStream(pdfDocument);
PdfNumber number = new PdfNumber(1);
number.MakeIndirect(pdfDocument);
for (int i = 0; i <= PdfObjectStream.MAX_OBJ_STREAM_SIZE - 1; i++) {
pdfObjectStream.AddObject(number);
}
NUnit.Framework.Assert.IsTrue(true, "We don't expect to reach this line, since no exception should have been thrown"
);
}
}
}

View File

@@ -0,0 +1,243 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System.Collections.Generic;
using System.IO;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("IntegrationTest")]
public class PdfObjectTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void IndirectsChain1() {
PdfDocument document = new PdfDocument(new PdfWriter(new MemoryStream()));
document.AddNewPage();
PdfDictionary catalog = document.GetCatalog().GetPdfObject();
catalog.Put(new PdfName("a"), GetTestPdfDictionary().MakeIndirect(document).GetIndirectReference().MakeIndirect
(document).GetIndirectReference().MakeIndirect(document));
PdfObject @object = ((PdfIndirectReference)catalog.Get(new PdfName("a"), false)).GetRefersTo(true);
NUnit.Framework.Assert.IsTrue(@object is PdfDictionary);
document.Close();
}
[NUnit.Framework.Test]
public virtual void IndirectsChain2() {
PdfDocument document = new PdfDocument(new PdfWriter(new MemoryStream()));
document.AddNewPage();
PdfDictionary catalog = document.GetCatalog().GetPdfObject();
PdfDictionary dictionary = GetTestPdfDictionary();
PdfObject @object = dictionary;
for (int i = 0; i < 200; i++) {
@object = @object.MakeIndirect(document).GetIndirectReference();
}
catalog.Put(new PdfName("a"), @object);
((PdfIndirectReference)catalog.Get(new PdfName("a"))).GetRefersTo(true);
NUnit.Framework.Assert.IsNotNull(((PdfIndirectReference)catalog.Get(new PdfName("a"))).GetRefersTo(true));
document.Close();
}
[NUnit.Framework.Test]
public virtual void IndirectsChain3() {
PdfDocument document = new PdfDocument(new PdfWriter(new MemoryStream()));
document.AddNewPage();
PdfDictionary catalog = document.GetCatalog().GetPdfObject();
PdfDictionary dictionary = GetTestPdfDictionary();
PdfObject @object = dictionary;
for (int i = 0; i < 31; i++) {
@object = @object.MakeIndirect(document).GetIndirectReference();
}
catalog.Put(new PdfName("a"), @object);
@object = catalog.Get(new PdfName("a"), true);
NUnit.Framework.Assert.IsTrue(@object is PdfDictionary);
NUnit.Framework.Assert.AreEqual(new PdfName("c").ToString(), ((PdfDictionary)@object).Get(new PdfName("b")
).ToString());
document.Close();
}
[NUnit.Framework.Test]
public virtual void IndirectsChain4() {
PdfDocument document = new PdfDocument(new PdfWriter(new MemoryStream()));
document.AddNewPage();
PdfDictionary catalog = document.GetCatalog().GetPdfObject();
PdfDictionary dictionary = GetTestPdfDictionary();
PdfObject @object = dictionary;
for (int i = 0; i < 31; i++) {
@object = @object.MakeIndirect(document).GetIndirectReference();
}
PdfArray array = new PdfArray();
array.Add(@object);
catalog.Put(new PdfName("a"), array);
@object = ((PdfArray)catalog.Get(new PdfName("a"))).Get(0, true);
NUnit.Framework.Assert.IsTrue(@object is PdfDictionary);
NUnit.Framework.Assert.AreEqual(new PdfName("c").ToString(), ((PdfDictionary)@object).Get(new PdfName("b")
).ToString());
document.Close();
}
[NUnit.Framework.Test]
public virtual void PdfIndirectReferenceFlags() {
PdfIndirectReference reference = new PdfIndirectReference(null, 1);
reference.SetState(PdfObject.FREE);
reference.SetState(PdfObject.READING);
reference.SetState(PdfObject.MODIFIED);
NUnit.Framework.Assert.AreEqual(true, reference.CheckState(PdfObject.FREE), "Free");
NUnit.Framework.Assert.AreEqual(true, reference.CheckState(PdfObject.READING), "Reading");
NUnit.Framework.Assert.AreEqual(true, reference.CheckState(PdfObject.MODIFIED), "Modified");
NUnit.Framework.Assert.AreEqual(true, reference.CheckState((byte)(PdfObject.FREE | PdfObject.MODIFIED | PdfObject
.READING)), "Free|Reading|Modified");
reference.ClearState(PdfObject.FREE);
NUnit.Framework.Assert.AreEqual(false, reference.CheckState(PdfObject.FREE), "Free");
NUnit.Framework.Assert.AreEqual(true, reference.CheckState(PdfObject.READING), "Reading");
NUnit.Framework.Assert.AreEqual(true, reference.CheckState(PdfObject.MODIFIED), "Modified");
NUnit.Framework.Assert.AreEqual(true, reference.CheckState((byte)(PdfObject.READING | PdfObject.MODIFIED))
, "Reading|Modified");
NUnit.Framework.Assert.AreEqual(false, reference.CheckState((byte)(PdfObject.FREE | PdfObject.READING | PdfObject
.MODIFIED)), "Free|Reading|Modified");
reference.ClearState(PdfObject.READING);
NUnit.Framework.Assert.AreEqual(false, reference.CheckState(PdfObject.FREE), "Free");
NUnit.Framework.Assert.AreEqual(false, reference.CheckState(PdfObject.READING), "Reading");
NUnit.Framework.Assert.AreEqual(true, reference.CheckState(PdfObject.MODIFIED), "Modified");
NUnit.Framework.Assert.AreEqual(false, reference.CheckState((byte)(PdfObject.FREE | PdfObject.READING)), "Free|Reading"
);
reference.ClearState(PdfObject.MODIFIED);
NUnit.Framework.Assert.AreEqual(false, reference.CheckState(PdfObject.FREE), "Free");
NUnit.Framework.Assert.AreEqual(false, reference.CheckState(PdfObject.READING), "Reading");
NUnit.Framework.Assert.AreEqual(false, reference.CheckState(PdfObject.MODIFIED), "Modified");
NUnit.Framework.Assert.AreEqual(true, !reference.IsFree(), "Is InUse");
reference.SetState(PdfObject.FREE);
NUnit.Framework.Assert.AreEqual(false, !reference.IsFree(), "Not IsInUse");
}
[NUnit.Framework.Test]
public virtual void PdtIndirectReferenceLateInitializing1() {
MemoryStream baos = new MemoryStream();
PdfDocument document = new PdfDocument(new PdfWriter(baos));
document.AddNewPage();
PdfDictionary catalog = document.GetCatalog().GetPdfObject();
PdfIndirectReference indRef = document.CreateNextIndirectReference();
catalog.Put(new PdfName("Smth"), indRef);
PdfDictionary dictionary = new PdfDictionary();
dictionary.Put(new PdfName("A"), new PdfString("a"));
dictionary.MakeIndirect(document, indRef);
document.Close();
MemoryStream bais = new MemoryStream(baos.ToArray());
document = new PdfDocument(new PdfReader(bais));
PdfObject @object = document.GetCatalog().GetPdfObject().Get(new PdfName("Smth"));
NUnit.Framework.Assert.IsTrue(@object is PdfDictionary);
dictionary = (PdfDictionary)@object;
PdfString a = (PdfString)dictionary.Get(new PdfName("A"));
NUnit.Framework.Assert.IsTrue(a.GetValue().Equals("a"));
document.Close();
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.FLUSHED_OBJECT_CONTAINS_REFERENCE_WHICH_NOT_REFER_TO_ANY_OBJECT
)]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.INDIRECT_REFERENCE_USED_IN_FLUSHED_OBJECT_MADE_FREE)]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)]
public virtual void PdtIndirectReferenceLateInitializing2() {
MemoryStream baos = new MemoryStream();
PdfDocument document = new PdfDocument(new PdfWriter(baos));
document.AddNewPage();
PdfDictionary catalog = document.GetCatalog().GetPdfObject();
PdfIndirectReference indRef1 = document.CreateNextIndirectReference();
PdfIndirectReference indRef2 = document.CreateNextIndirectReference();
catalog.Put(new PdfName("Smth1"), indRef1);
catalog.Put(new PdfName("Smth2"), indRef2);
PdfArray array = new PdfArray();
array.Add(new PdfString("array string"));
array.MakeIndirect(document, indRef2);
document.Close();
MemoryStream bais = new MemoryStream(baos.ToArray());
document = new PdfDocument(new PdfReader(bais));
PdfDictionary catalogDict = document.GetCatalog().GetPdfObject();
PdfObject object1 = catalogDict.Get(new PdfName("Smth1"));
PdfObject object2 = catalogDict.Get(new PdfName("Smth2"));
NUnit.Framework.Assert.IsTrue(object1 is PdfNull);
NUnit.Framework.Assert.IsTrue(object2 is PdfArray);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.FLUSHED_OBJECT_CONTAINS_REFERENCE_WHICH_NOT_REFER_TO_ANY_OBJECT
)]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.INDIRECT_REFERENCE_USED_IN_FLUSHED_OBJECT_MADE_FREE)]
public virtual void PdtIndirectReferenceLateInitializing3() {
PdfDocument document = new PdfDocument(new PdfWriter(new MemoryStream()));
document.AddNewPage();
PdfDictionary catalog = document.GetCatalog().GetPdfObject();
PdfIndirectReference indRef1 = document.CreateNextIndirectReference();
PdfIndirectReference indRef2 = document.CreateNextIndirectReference();
PdfArray array = new PdfArray();
catalog.Put(new PdfName("array1"), array);
PdfString @string = new PdfString("array string");
array.Add(@string);
array.Add(indRef1);
array.Add(indRef2);
PdfDictionary dict = new PdfDictionary();
dict.MakeIndirect(document, indRef1);
PdfArray arrayClone = (PdfArray)array.Clone();
PdfObject object0 = arrayClone.Get(0, false);
PdfObject object1 = arrayClone.Get(1, false);
PdfObject object2 = arrayClone.Get(2, false);
NUnit.Framework.Assert.IsTrue(object0 is PdfString);
NUnit.Framework.Assert.IsTrue(object1 is PdfDictionary);
NUnit.Framework.Assert.IsTrue(object2 is PdfNull);
PdfString string1 = (PdfString)object0;
NUnit.Framework.Assert.IsTrue(@string != string1);
NUnit.Framework.Assert.IsTrue(@string.GetValue().Equals(string1.GetValue()));
PdfDictionary dict1 = (PdfDictionary)object1;
NUnit.Framework.Assert.IsTrue(dict1.GetIndirectReference().GetObjNumber() == dict.GetIndirectReference().GetObjNumber
());
NUnit.Framework.Assert.IsTrue(dict1.GetIndirectReference().GetGenNumber() == dict.GetIndirectReference().GetGenNumber
());
NUnit.Framework.Assert.IsTrue(dict1 == dict);
document.Close();
}
private static PdfDictionary GetTestPdfDictionary() {
Dictionary<PdfName, PdfObject> tmpMap = new Dictionary<PdfName, PdfObject>();
tmpMap.Put(new PdfName("b"), new PdfName("c"));
return new PdfDictionary(tmpMap);
}
}
}

View File

@@ -0,0 +1,75 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.IO.Source;
using TSpdf.Kernel.Exceptions;
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("UnitTest")]
public class PdfObjectUnitTest : ExtendedTSpdfTest {
private static readonly String SOURCE_FOLDER = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/pdf/PdfObjectUnitTest/";
[NUnit.Framework.Test]
public virtual void NoWriterForMakingIndirectTest() {
PdfDocument pdfDocument = new PdfDocument(new PdfReader(SOURCE_FOLDER + "noWriterForMakingIndirect.pdf"));
PdfDictionary pdfDictionary = new PdfDictionary();
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfDictionary.MakeIndirect(
pdfDocument));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.THERE_IS_NO_ASSOCIATE_PDF_WRITER_FOR_MAKING_INDIRECTS
, exception.Message);
}
[NUnit.Framework.Test]
public virtual void CopyDocInReadingModeTest() {
PdfDocument pdfDocument = new PdfDocument(new PdfReader(SOURCE_FOLDER + "copyDocInReadingMode.pdf"));
PdfDictionary pdfDictionary = new PdfDictionary();
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfDictionary.ProcessCopying
(pdfDocument, true));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.CANNOT_COPY_TO_DOCUMENT_OPENED_IN_READING_MODE
, exception.Message);
}
[NUnit.Framework.Test]
public virtual void CopyIndirectObjectTest() {
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
PdfObject pdfObject = pdfDocument.GetPdfObject(1);
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfObject.CopyTo(pdfDocument
, true));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.CANNOT_COPY_INDIRECT_OBJECT_FROM_THE_DOCUMENT_THAT_IS_BEING_WRITTEN
, exception.Message);
}
[NUnit.Framework.Test]
public virtual void CopyFlushedObjectTest() {
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
PdfObject pdfObject = pdfDocument.GetPdfObject(1);
pdfObject.Flush();
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfObject.CopyContent(pdfObject
, pdfDocument));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.CANNOT_COPY_FLUSHED_OBJECT, exception.Message
);
}
}
}

View File

@@ -0,0 +1,41 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.Kernel.Exceptions;
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("UnitTest")]
public class PdfObjectWrapperUnitTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void DirectObjectsCouldNotBeWrappedTest01() {
PdfDictionary pdfDictionary = new PdfDictionary();
NUnit.Framework.Assert.IsNull(pdfDictionary.GetIndirectReference());
// PdfCatalog is one of PdfObjectWrapper implementations. The issue could be reproduced on any of them, not only on this one
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => new PdfCatalog(pdfDictionary
));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.OBJECT_MUST_BE_INDIRECT_TO_WORK_WITH_THIS_WRAPPER
, exception.Message);
}
}
}

View File

@@ -0,0 +1,730 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.Collections.Generic;
using System.IO;
using TSpdf.Commons.Utils;
using TSpdf.IO.Font;
using TSpdf.Kernel.Colors;
using TSpdf.Kernel.Exceptions;
using TSpdf.Kernel.Logs;
using TSpdf.Kernel.Pdf.Navigation;
using TSpdf.Kernel.Utils;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("IntegrationTest")]
public class PdfOutlineTest : ExtendedTSpdfTest {
public static readonly String SOURCE_FOLDER = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/pdf/PdfOutlineTest/";
public static readonly String DESTINATION_FOLDER = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/pdf/PdfOutlineTest/";
[NUnit.Framework.OneTimeSetUp]
public static void Before() {
CreateOrClearDestinationFolder(DESTINATION_FOLDER);
}
[NUnit.Framework.Test]
public virtual void CreateSimpleDocWithOutlines() {
String filename = "simpleDocWithOutlines.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(DESTINATION_FOLDER + filename));
pdfDoc.GetCatalog().SetPageMode(PdfName.UseOutlines);
PdfPage firstPage = pdfDoc.AddNewPage();
PdfPage secondPage = pdfDoc.AddNewPage();
PdfOutline rootOutline = pdfDoc.GetOutlines(false);
PdfOutline firstOutline = rootOutline.AddOutline("First Page");
PdfOutline secondOutline = rootOutline.AddOutline("Second Page");
firstOutline.AddDestination(PdfExplicitDestination.CreateFit(firstPage));
secondOutline.AddDestination(PdfExplicitDestination.CreateFit(secondPage));
pdfDoc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(DESTINATION_FOLDER + filename, SOURCE_FOLDER
+ "cmp_" + filename, DESTINATION_FOLDER, "diff_"));
}
[NUnit.Framework.Test]
public virtual void OutlinesTest() {
PdfDocument pdfDoc = new PdfDocument(new PdfReader(SOURCE_FOLDER + "iphone_user_guide.pdf"));
PdfOutline outlines = pdfDoc.GetOutlines(false);
IList<PdfOutline> children = outlines.GetAllChildren()[0].GetAllChildren();
NUnit.Framework.Assert.AreEqual(outlines.GetTitle(), "Outlines");
NUnit.Framework.Assert.AreEqual(children.Count, 13);
NUnit.Framework.Assert.IsTrue(children[0].GetDestination() is PdfStringDestination);
}
[NUnit.Framework.Test]
public virtual void OutlinesWithPagesTest() {
PdfDocument pdfDoc = new PdfDocument(new PdfReader(SOURCE_FOLDER + "iphone_user_guide.pdf"));
PdfPage page = pdfDoc.GetPage(52);
IList<PdfOutline> pageOutlines = page.GetOutlines(true);
try {
NUnit.Framework.Assert.AreEqual(3, pageOutlines.Count);
NUnit.Framework.Assert.IsTrue(pageOutlines[0].GetTitle().Equals("Safari"));
NUnit.Framework.Assert.AreEqual(pageOutlines[0].GetAllChildren().Count, 4);
}
finally {
pdfDoc.Close();
}
}
[NUnit.Framework.Test]
public virtual void AddOutlinesToDocumentTest() {
PdfReader reader = new PdfReader(SOURCE_FOLDER + "iphone_user_guide.pdf");
String filename = "addOutlinesToDocumentTest.pdf";
PdfWriter writer = new PdfWriter(DESTINATION_FOLDER + filename);
PdfDocument pdfDoc = new PdfDocument(reader, writer);
pdfDoc.SetTagged();
PdfOutline outlines = pdfDoc.GetOutlines(false);
PdfOutline firstPage = outlines.AddOutline("firstPage");
PdfOutline firstPageChild = firstPage.AddOutline("firstPageChild");
PdfOutline secondPage = outlines.AddOutline("secondPage");
PdfOutline secondPageChild = secondPage.AddOutline("secondPageChild");
firstPage.AddDestination(PdfExplicitDestination.CreateFit(pdfDoc.GetPage(1)));
firstPageChild.AddDestination(PdfExplicitDestination.CreateFit(pdfDoc.GetPage(1)));
secondPage.AddDestination(PdfExplicitDestination.CreateFit(pdfDoc.GetPage(2)));
secondPageChild.AddDestination(PdfExplicitDestination.CreateFit(pdfDoc.GetPage(2)));
outlines.GetAllChildren()[0].GetAllChildren()[1].AddOutline("testOutline", 1).AddDestination(PdfExplicitDestination
.CreateFit(pdfDoc.GetPage(102)));
pdfDoc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(DESTINATION_FOLDER + filename, SOURCE_FOLDER
+ "cmp_" + filename, DESTINATION_FOLDER, "diff_"));
}
[NUnit.Framework.Test]
public virtual void ReadOutlinesFromDocumentTest() {
String filename = SOURCE_FOLDER + "addOutlinesResult.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfReader(filename));
PdfOutline outlines = pdfDoc.GetOutlines(false);
try {
NUnit.Framework.Assert.AreEqual(3, outlines.GetAllChildren().Count);
NUnit.Framework.Assert.AreEqual("firstPageChild", outlines.GetAllChildren()[1].GetAllChildren()[0].GetTitle
());
}
finally {
pdfDoc.Close();
}
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.FLUSHED_OBJECT_CONTAINS_FREE_REFERENCE, Count = 36)]
public virtual void RemovePageWithOutlinesTest() {
// TODO DEVSIX-1643: destinations are not removed along with page
String filename = "removePageWithOutlinesTest.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfReader(SOURCE_FOLDER + "iphone_user_guide.pdf"), new PdfWriter
(DESTINATION_FOLDER + filename));
// TODO DEVSIX-1643 (this causes log message errors. It's because of destinations pointing to removed page (freed reference, replaced by PdfNull))
pdfDoc.RemovePage(102);
pdfDoc.Close();
CompareTool compareTool = new CompareTool();
String diffContent = compareTool.CompareByContent(DESTINATION_FOLDER + filename, SOURCE_FOLDER + "cmp_" +
filename, DESTINATION_FOLDER, "diff_");
String diffTags = compareTool.CompareTagStructures(DESTINATION_FOLDER + filename, SOURCE_FOLDER + "cmp_" +
filename);
if (diffContent != null || diffTags != null) {
diffContent = diffContent != null ? diffContent : "";
diffTags = diffTags != null ? diffTags : "";
NUnit.Framework.Assert.Fail(diffContent + diffTags);
}
}
[NUnit.Framework.Test]
public virtual void ReadRemovedPageWithOutlinesTest() {
// TODO DEVSIX-1643: src document is taken from the previous removePageWithOutlinesTest test, however it contains numerous destination objects which contain PdfNull instead of page reference
String filename = SOURCE_FOLDER + "removePagesWithOutlinesResult.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfReader(filename));
PdfPage page = pdfDoc.GetPage(102);
IList<PdfOutline> pageOutlines = page.GetOutlines(false);
try {
NUnit.Framework.Assert.AreEqual(4, pageOutlines.Count);
}
finally {
pdfDoc.Close();
}
}
[NUnit.Framework.Test]
public virtual void UpdateOutlineTitle() {
PdfReader reader = new PdfReader(SOURCE_FOLDER + "iphone_user_guide.pdf");
String filename = "updateOutlineTitle.pdf";
PdfWriter writer = new PdfWriter(DESTINATION_FOLDER + filename);
PdfDocument pdfDoc = new PdfDocument(reader, writer);
PdfOutline outlines = pdfDoc.GetOutlines(false);
outlines.GetAllChildren()[0].GetAllChildren()[1].SetTitle("New Title");
pdfDoc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(DESTINATION_FOLDER + filename, SOURCE_FOLDER
+ "cmp_" + filename, DESTINATION_FOLDER, "diff_"));
}
[NUnit.Framework.Test]
public virtual void GetOutlinesInvalidParentLink() {
PdfReader reader = new PdfReader(SOURCE_FOLDER + "outlinesInvalidParentLink.pdf");
String filename = "updateOutlineTitleInvalidParentLink.pdf";
PdfWriter writer = new PdfWriter(DESTINATION_FOLDER + filename);
PdfDocument pdfDoc = new PdfDocument(reader, writer);
PdfOutline outlines = pdfDoc.GetOutlines(true);
PdfOutline firstOutline = outlines.GetAllChildren()[0];
PdfOutline secondOutline = outlines.GetAllChildren()[1];
try {
NUnit.Framework.Assert.AreEqual(2, outlines.GetAllChildren().Count);
NUnit.Framework.Assert.AreEqual("First Page", firstOutline.GetTitle());
NUnit.Framework.Assert.AreEqual(outlines, firstOutline.GetParent());
NUnit.Framework.Assert.AreEqual("Second Page", secondOutline.GetTitle());
NUnit.Framework.Assert.AreEqual(outlines, secondOutline.GetParent());
}
finally {
pdfDoc.Close();
}
}
[NUnit.Framework.Test]
public virtual void ReadOutlineTitle() {
String filename = SOURCE_FOLDER + "updateOutlineTitleResult.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfReader(filename));
PdfOutline outlines = pdfDoc.GetOutlines(false);
PdfOutline outline = outlines.GetAllChildren()[0].GetAllChildren()[1];
try {
NUnit.Framework.Assert.AreEqual("New Title", outline.GetTitle());
}
finally {
pdfDoc.Close();
}
}
[NUnit.Framework.Test]
public virtual void AddOutlineInNotOutlineMode() {
String filename = "addOutlineInNotOutlineMode.pdf";
PdfReader reader = new PdfReader(SOURCE_FOLDER + "iphone_user_guide.pdf");
PdfWriter writer = new PdfWriter(DESTINATION_FOLDER + filename);
PdfDocument pdfDoc = new PdfDocument(reader, writer);
PdfOutline outlines = new PdfOutline(pdfDoc);
PdfOutline firstPage = outlines.AddOutline("firstPage");
PdfOutline firstPageChild = firstPage.AddOutline("firstPageChild");
PdfOutline secondPage = outlines.AddOutline("secondPage");
PdfOutline secondPageChild = secondPage.AddOutline("secondPageChild");
firstPage.AddDestination(PdfExplicitDestination.CreateFit(pdfDoc.GetPage(1)));
firstPageChild.AddDestination(PdfExplicitDestination.CreateFit(pdfDoc.GetPage(1)));
secondPage.AddDestination(PdfExplicitDestination.CreateFit(pdfDoc.GetPage(2)));
secondPageChild.AddDestination(PdfExplicitDestination.CreateFit(pdfDoc.GetPage(2)));
pdfDoc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(DESTINATION_FOLDER + filename, SOURCE_FOLDER
+ "cmp_" + filename, DESTINATION_FOLDER, "diff_"));
}
[NUnit.Framework.Test]
public virtual void ReadOutlineAddedInNotOutlineMode() {
String filename = SOURCE_FOLDER + "addOutlinesWithoutOutlineModeResult.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfReader(filename));
IList<PdfOutline> pageOutlines = pdfDoc.GetPage(102).GetOutlines(true);
try {
NUnit.Framework.Assert.AreEqual(5, pageOutlines.Count);
}
finally {
pdfDoc.Close();
}
}
[NUnit.Framework.Test]
public virtual void CreateDocWithOutlines() {
String filename = SOURCE_FOLDER + "documentWithOutlines.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfReader(filename));
PdfOutline outlines = pdfDoc.GetOutlines(false);
try {
NUnit.Framework.Assert.AreEqual(2, outlines.GetAllChildren().Count);
NUnit.Framework.Assert.AreEqual("First Page", outlines.GetAllChildren()[0].GetTitle());
}
finally {
pdfDoc.Close();
}
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.SOURCE_DOCUMENT_HAS_ACROFORM_DICTIONARY)]
public virtual void CopyPagesWithOutlines() {
PdfReader reader = new PdfReader(SOURCE_FOLDER + "iphone_user_guide.pdf");
PdfWriter writer = new PdfWriter(DESTINATION_FOLDER + "copyPagesWithOutlines01.pdf");
PdfDocument pdfDoc = new PdfDocument(reader);
PdfDocument pdfDoc1 = new PdfDocument(writer);
IList<int> pages = new List<int>();
pages.Add(1);
pages.Add(2);
pages.Add(3);
pages.Add(5);
pages.Add(52);
pages.Add(102);
pdfDoc1.InitializeOutlines();
pdfDoc.CopyPagesTo(pages, pdfDoc1);
pdfDoc.Close();
NUnit.Framework.Assert.AreEqual(6, pdfDoc1.GetNumberOfPages());
NUnit.Framework.Assert.AreEqual(4, pdfDoc1.GetOutlines(false).GetAllChildren()[0].GetAllChildren().Count);
pdfDoc1.Close();
}
[NUnit.Framework.Test]
public virtual void AddOutlinesWithNamedDestinations01() {
String filename = DESTINATION_FOLDER + "outlinesWithNamedDestinations01.pdf";
PdfReader reader = new PdfReader(SOURCE_FOLDER + "iphone_user_guide.pdf");
PdfWriter writer = new PdfWriter(filename);
PdfDocument pdfDoc = new PdfDocument(reader, writer);
PdfArray array1 = new PdfArray();
array1.Add(pdfDoc.GetPage(2).GetPdfObject());
array1.Add(PdfName.XYZ);
array1.Add(new PdfNumber(36));
array1.Add(new PdfNumber(806));
array1.Add(new PdfNumber(0));
PdfArray array2 = new PdfArray();
array2.Add(pdfDoc.GetPage(3).GetPdfObject());
array2.Add(PdfName.XYZ);
array2.Add(new PdfNumber(36));
array2.Add(new PdfNumber(806));
array2.Add(new PdfNumber(1.25));
PdfArray array3 = new PdfArray();
array3.Add(pdfDoc.GetPage(4).GetPdfObject());
array3.Add(PdfName.XYZ);
array3.Add(new PdfNumber(36));
array3.Add(new PdfNumber(806));
array3.Add(new PdfNumber(1));
pdfDoc.AddNamedDestination("test1", array2);
pdfDoc.AddNamedDestination("test2", array3);
pdfDoc.AddNamedDestination("test3", array1);
PdfOutline root = pdfDoc.GetOutlines(false);
PdfOutline firstOutline = root.AddOutline("Test1");
firstOutline.AddDestination(PdfDestination.MakeDestination(new PdfString("test1")));
PdfOutline secondOutline = root.AddOutline("Test2");
secondOutline.AddDestination(PdfDestination.MakeDestination(new PdfString("test2")));
PdfOutline thirdOutline = root.AddOutline("Test3");
thirdOutline.AddDestination(PdfDestination.MakeDestination(new PdfString("test3")));
pdfDoc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, SOURCE_FOLDER + "cmp_outlinesWithNamedDestinations01.pdf"
, DESTINATION_FOLDER, "diff_"));
}
[NUnit.Framework.Test]
public virtual void AddOutlinesWithNamedDestinations02() {
String filename = DESTINATION_FOLDER + "outlinesWithNamedDestinations02.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(filename));
PdfArray array1 = new PdfArray();
array1.Add(pdfDoc.AddNewPage().GetPdfObject());
array1.Add(PdfName.XYZ);
array1.Add(new PdfNumber(36));
array1.Add(new PdfNumber(806));
array1.Add(new PdfNumber(0));
PdfArray array2 = new PdfArray();
array2.Add(pdfDoc.AddNewPage().GetPdfObject());
array2.Add(PdfName.XYZ);
array2.Add(new PdfNumber(36));
array2.Add(new PdfNumber(806));
array2.Add(new PdfNumber(1.25));
PdfArray array3 = new PdfArray();
array3.Add(pdfDoc.AddNewPage().GetPdfObject());
array3.Add(PdfName.XYZ);
array3.Add(new PdfNumber(36));
array3.Add(new PdfNumber(806));
array3.Add(new PdfNumber(1));
pdfDoc.AddNamedDestination("page1", array2);
pdfDoc.AddNamedDestination("page2", array3);
pdfDoc.AddNamedDestination("page3", array1);
PdfOutline root = pdfDoc.GetOutlines(false);
PdfOutline firstOutline = root.AddOutline("Test1");
firstOutline.AddDestination(PdfDestination.MakeDestination(new PdfString("page1")));
PdfOutline secondOutline = root.AddOutline("Test2");
secondOutline.AddDestination(PdfDestination.MakeDestination(new PdfString("page2")));
PdfOutline thirdOutline = root.AddOutline("Test3");
thirdOutline.AddDestination(PdfDestination.MakeDestination(new PdfString("page3")));
pdfDoc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, SOURCE_FOLDER + "cmp_outlinesWithNamedDestinations02.pdf"
, DESTINATION_FOLDER, "diff_"));
}
[NUnit.Framework.Test]
public virtual void OutlineStackOverflowTest01() {
PdfReader reader = new PdfReader(SOURCE_FOLDER + "outlineStackOverflowTest01.pdf");
PdfDocument pdfDoc = new PdfDocument(reader);
try {
pdfDoc.GetOutlines(true);
}
catch (OutOfMemoryException) {
NUnit.Framework.Assert.Fail("StackOverflow thrown when reading document with a large number of outlines.");
}
}
[NUnit.Framework.Test]
public virtual void OutlineTypeNull() {
String filename = "outlineTypeNull";
String outputFile = DESTINATION_FOLDER + filename + ".pdf";
PdfReader reader = new PdfReader(SOURCE_FOLDER + filename + ".pdf");
PdfWriter writer = new PdfWriter(new FileStream(outputFile, FileMode.Create));
PdfDocument pdfDoc = new PdfDocument(reader, writer);
pdfDoc.RemovePage(3);
pdfDoc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outputFile, SOURCE_FOLDER + "cmp_" + filename
+ ".pdf", DESTINATION_FOLDER, "diff_"));
}
[NUnit.Framework.Test]
public virtual void RemoveAllOutlinesTest() {
String filename = "iphone_user_guide_removeAllOutlinesTest.pdf";
String input = SOURCE_FOLDER + "iphone_user_guide.pdf";
String output = DESTINATION_FOLDER + "cmp_" + filename;
String cmp = SOURCE_FOLDER + "cmp_" + filename;
PdfReader reader = new PdfReader(input);
PdfWriter writer = new PdfWriter(output);
PdfDocument pdfDocument = new PdfDocument(reader, writer);
pdfDocument.GetOutlines(true).RemoveOutline();
pdfDocument.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(output, cmp, DESTINATION_FOLDER, "diff_")
);
}
[NUnit.Framework.Test]
public virtual void RemoveOneOutlineTest() {
String filename = "removeOneOutline.pdf";
String input = SOURCE_FOLDER + "outlineTree.pdf";
String output = DESTINATION_FOLDER + "cmp_" + filename;
String cmp = SOURCE_FOLDER + "cmp_" + filename;
PdfReader reader = new PdfReader(input);
PdfWriter writer = new PdfWriter(output);
PdfDocument pdfDocument = new PdfDocument(reader, writer);
PdfOutline root = pdfDocument.GetOutlines(true);
PdfOutline toRemove = root.GetAllChildren()[2];
toRemove.RemoveOutline();
pdfDocument.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(output, cmp, DESTINATION_FOLDER, "diff_")
);
}
[NUnit.Framework.Test]
public virtual void TestReinitializingOutlines() {
String input = SOURCE_FOLDER + "outlineTree.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(input));
PdfOutline root = pdfDocument.GetOutlines(false);
NUnit.Framework.Assert.AreEqual(4, root.GetAllChildren().Count);
pdfDocument.GetCatalog().GetPdfObject().Remove(PdfName.Outlines);
root = pdfDocument.GetOutlines(true);
NUnit.Framework.Assert.IsNull(root);
pdfDocument.Close();
}
[NUnit.Framework.Test]
public virtual void RemovePageInDocWithSimpleOutlineTreeStructTest() {
String input = SOURCE_FOLDER + "simpleOutlineTreeStructure.pdf";
String output = DESTINATION_FOLDER + "simpleOutlineTreeStructure.pdf";
String cmp = SOURCE_FOLDER + "cmp_simpleOutlineTreeStructure.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(input), new PdfWriter(output));
pdfDocument.RemovePage(2);
NUnit.Framework.Assert.AreEqual(2, pdfDocument.GetNumberOfPages());
pdfDocument.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(output, cmp, DESTINATION_FOLDER, "diff_")
);
}
[NUnit.Framework.Test]
public virtual void RemovePageInDocWithComplexOutlineTreeStructTest() {
String input = SOURCE_FOLDER + "complexOutlineTreeStructure.pdf";
String output = DESTINATION_FOLDER + "complexOutlineTreeStructure.pdf";
String cmp = SOURCE_FOLDER + "cmp_complexOutlineTreeStructure.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(input), new PdfWriter(output));
pdfDocument.RemovePage(2);
NUnit.Framework.Assert.AreEqual(2, pdfDocument.GetNumberOfPages());
pdfDocument.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(output, cmp, DESTINATION_FOLDER, "diff_")
);
}
[NUnit.Framework.Test]
public virtual void ConstructOutlinesNoParentTest() {
using (MemoryStream baos = new MemoryStream()) {
using (PdfDocument pdfDocument = new PdfDocument(new PdfWriter(baos))) {
pdfDocument.AddNewPage();
PdfDictionary first = new PdfDictionary();
first.MakeIndirect(pdfDocument);
PdfDictionary outlineDictionary = new PdfDictionary();
outlineDictionary.Put(PdfName.First, first);
outlineDictionary.Put(PdfName.Title, new PdfString("title", PdfEncodings.UNICODE_BIG));
first.Put(PdfName.Title, new PdfString("title", PdfEncodings.UNICODE_BIG));
NUnit.Framework.Assert.DoesNotThrow(() => pdfDocument.GetCatalog().ConstructOutlines(outlineDictionary, new
PdfOutlineTest.EmptyNameTree()));
}
}
}
[NUnit.Framework.Test]
public virtual void ConstructOutlinesNoTitleTest() {
using (MemoryStream baos = new MemoryStream()) {
using (PdfDocument pdfDocument = new PdfDocument(new PdfWriter(baos))) {
pdfDocument.AddNewPage();
PdfDictionary first = new PdfDictionary();
first.MakeIndirect(pdfDocument);
PdfDictionary outlineDictionary = new PdfDictionary();
outlineDictionary.MakeIndirect(pdfDocument);
outlineDictionary.Put(PdfName.First, first);
first.Put(PdfName.Parent, outlineDictionary);
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfDocument.GetCatalog().ConstructOutlines
(outlineDictionary, new PdfOutlineTest.EmptyNameTree()));
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(KernelExceptionMessageConstant.CORRUPTED_OUTLINE_NO_TITLE_ENTRY
, first.indirectReference), exception.Message);
}
}
}
[NUnit.Framework.Test]
public virtual void CheckParentOfOutlinesTest() {
using (MemoryStream baos = new MemoryStream()) {
using (PdfDocument pdfDocument = new PdfDocument(new PdfWriter(baos))) {
pdfDocument.GetCatalog().SetPageMode(PdfName.UseOutlines);
PdfPage firstPage = pdfDocument.AddNewPage();
PdfOutline rootOutline = pdfDocument.GetOutlines(false);
PdfOutline firstOutline = rootOutline.AddOutline("First outline");
PdfOutline firstSubOutline = firstOutline.AddOutline("First suboutline");
PdfOutline secondSubOutline = firstOutline.AddOutline("Second suboutline");
PdfOutline secondOutline = rootOutline.AddOutline("SecondOutline");
firstOutline.AddDestination(PdfExplicitDestination.CreateFit(firstPage));
PdfOutline resultedRoot = pdfDocument.GetOutlines(true);
NUnit.Framework.Assert.AreEqual(2, resultedRoot.GetAllChildren().Count);
NUnit.Framework.Assert.AreEqual(resultedRoot, resultedRoot.GetAllChildren()[0].GetParent());
NUnit.Framework.Assert.AreEqual(resultedRoot, resultedRoot.GetAllChildren()[1].GetParent());
PdfOutline resultedFirstOutline = resultedRoot.GetAllChildren()[0];
NUnit.Framework.Assert.AreEqual(2, resultedFirstOutline.GetAllChildren().Count);
NUnit.Framework.Assert.AreEqual(resultedFirstOutline, resultedFirstOutline.GetAllChildren()[0].GetParent()
);
NUnit.Framework.Assert.AreEqual(resultedFirstOutline, resultedFirstOutline.GetAllChildren()[1].GetParent()
);
}
}
}
[NUnit.Framework.Test]
public virtual void CheckNestedOutlinesParentTest() {
using (MemoryStream baos = new MemoryStream()) {
using (PdfDocument pdfDocument = new PdfDocument(new PdfWriter(baos))) {
pdfDocument.GetCatalog().SetPageMode(PdfName.UseOutlines);
PdfPage firstPage = pdfDocument.AddNewPage();
PdfOutline rootOutline = pdfDocument.GetOutlines(false);
PdfOutline firstOutline = rootOutline.AddOutline("First outline");
PdfOutline secondOutline = firstOutline.AddOutline("Second outline");
PdfOutline thirdOutline = secondOutline.AddOutline("Third outline");
firstOutline.AddDestination(PdfExplicitDestination.CreateFit(firstPage));
PdfOutline resultedRoot = pdfDocument.GetOutlines(true);
NUnit.Framework.Assert.AreEqual(1, resultedRoot.GetAllChildren().Count);
NUnit.Framework.Assert.AreEqual(resultedRoot, resultedRoot.GetAllChildren()[0].GetParent());
PdfOutline resultedFirstOutline = resultedRoot.GetAllChildren()[0];
NUnit.Framework.Assert.AreEqual(1, resultedFirstOutline.GetAllChildren().Count);
NUnit.Framework.Assert.AreEqual(resultedFirstOutline, resultedFirstOutline.GetAllChildren()[0].GetParent()
);
PdfOutline resultedSecondOutline = resultedFirstOutline.GetAllChildren()[0];
NUnit.Framework.Assert.AreEqual(1, resultedSecondOutline.GetAllChildren().Count);
NUnit.Framework.Assert.AreEqual(resultedSecondOutline, resultedSecondOutline.GetAllChildren()[0].GetParent
());
}
}
}
[NUnit.Framework.Test]
public virtual void SetOutlinePropertiesTest() {
using (MemoryStream baos = new MemoryStream()) {
using (PdfDocument pdfDocument = new PdfDocument(new PdfWriter(baos))) {
PdfPage firstPage = pdfDocument.AddNewPage();
PdfOutline rootOutline = pdfDocument.GetOutlines(true);
PdfOutline outline = rootOutline.AddOutline("Outline");
NUnit.Framework.Assert.IsTrue(outline.IsOpen());
NUnit.Framework.Assert.IsNull(outline.GetStyle());
NUnit.Framework.Assert.IsNull(outline.GetColor());
outline.GetContent().Put(PdfName.C, new PdfArray(ColorConstants.BLACK.GetColorValue()));
outline.GetContent().Put(PdfName.F, new PdfNumber(2));
outline.GetContent().Put(PdfName.Count, new PdfNumber(4));
NUnit.Framework.Assert.IsTrue(outline.IsOpen());
NUnit.Framework.Assert.AreEqual(2, outline.GetStyle());
NUnit.Framework.Assert.AreEqual(ColorConstants.BLACK, outline.GetColor());
outline.GetContent().Put(PdfName.Count, new PdfNumber(0));
NUnit.Framework.Assert.IsTrue(outline.IsOpen());
outline.GetContent().Put(PdfName.Count, new PdfNumber(-5));
NUnit.Framework.Assert.IsFalse(outline.IsOpen());
}
}
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.CORRUPTED_OUTLINE_DICTIONARY_HAS_INFINITE_LOOP)]
public virtual void CheckPossibleInfiniteLoopWithSameNextAndPrevLinkTest() {
using (MemoryStream baos = new MemoryStream()) {
using (PdfDocument pdfDocument = new PdfDocument(new PdfWriter(baos))) {
pdfDocument.AddNewPage();
PdfDictionary first = new PdfDictionary();
first.MakeIndirect(pdfDocument);
PdfDictionary second = new PdfDictionary();
second.MakeIndirect(pdfDocument);
PdfDictionary outlineDictionary = new PdfDictionary();
outlineDictionary.MakeIndirect(pdfDocument);
outlineDictionary.Put(PdfName.First, first);
outlineDictionary.Put(PdfName.Last, second);
first.Put(PdfName.Parent, outlineDictionary);
second.Put(PdfName.Parent, outlineDictionary);
first.Put(PdfName.Next, second);
first.Put(PdfName.Prev, second);
second.Put(PdfName.Next, first);
second.Put(PdfName.Prev, first);
outlineDictionary.Put(PdfName.Title, new PdfString("title", PdfEncodings.UNICODE_BIG));
first.Put(PdfName.Title, new PdfString("title", PdfEncodings.UNICODE_BIG));
second.Put(PdfName.Title, new PdfString("title", PdfEncodings.UNICODE_BIG));
NUnit.Framework.Assert.DoesNotThrow(() => pdfDocument.GetCatalog().ConstructOutlines(outlineDictionary, new
PdfOutlineTest.EmptyNameTree()));
PdfOutline resultedOutline = pdfDocument.GetOutlines(false);
NUnit.Framework.Assert.AreEqual(2, resultedOutline.GetAllChildren().Count);
NUnit.Framework.Assert.AreEqual(resultedOutline.GetAllChildren()[1].GetParent(), resultedOutline.GetAllChildren
()[0].GetParent());
}
}
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.CORRUPTED_OUTLINE_DICTIONARY_HAS_INFINITE_LOOP)]
public virtual void CheckPossibleInfiniteLoopWithSameFirstAndLastLinkTest() {
using (MemoryStream baos = new MemoryStream()) {
using (PdfDocument pdfDocument = new PdfDocument(new PdfWriter(baos))) {
pdfDocument.AddNewPage();
PdfDictionary first = new PdfDictionary();
first.MakeIndirect(pdfDocument);
PdfDictionary outlineDictionary = new PdfDictionary();
outlineDictionary.MakeIndirect(pdfDocument);
outlineDictionary.Put(PdfName.First, first);
first.Put(PdfName.Parent, outlineDictionary);
first.Put(PdfName.First, outlineDictionary);
first.Put(PdfName.Last, outlineDictionary);
outlineDictionary.Put(PdfName.Title, new PdfString("title", PdfEncodings.UNICODE_BIG));
first.Put(PdfName.Title, new PdfString("title", PdfEncodings.UNICODE_BIG));
NUnit.Framework.Assert.DoesNotThrow(() => pdfDocument.GetCatalog().ConstructOutlines(outlineDictionary, new
PdfOutlineTest.EmptyNameTree()));
PdfOutline resultedOutline = pdfDocument.GetOutlines(false);
NUnit.Framework.Assert.AreEqual(1, resultedOutline.GetAllChildren().Count);
NUnit.Framework.Assert.AreEqual(resultedOutline, resultedOutline.GetAllChildren()[0].GetParent());
}
}
}
[NUnit.Framework.Test]
public virtual void OutlineNoParentLinkInConservativeModeTest() {
using (PdfDocument pdfDocument = new PdfDocument(new PdfReader(SOURCE_FOLDER + "outlinesNoParentLink.pdf")
)) {
pdfDocument.GetReader().SetStrictnessLevel(PdfReader.StrictnessLevel.CONSERVATIVE);
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfDocument.GetOutlines(true
));
//Hardcode indirectReference, cause there is no option to get this outline due to #getOutlines method
// will be thrown an exception.
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(KernelExceptionMessageConstant.CORRUPTED_OUTLINE_NO_PARENT_ENTRY
, "9 0 R"), exception.Message);
}
}
[NUnit.Framework.Test]
public virtual void OutlineHasInfiniteLoopInConservativeModeTest() {
using (PdfDocument pdfDocument = new PdfDocument(new PdfReader(SOURCE_FOLDER + "outlinesHaveInfiniteLoop.pdf"
))) {
pdfDocument.GetReader().SetStrictnessLevel(PdfReader.StrictnessLevel.CONSERVATIVE);
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfDocument.GetOutlines(true
));
//Hardcode indirectReference, cause there is no option to get this outline due to #getOutlines method
// will be thrown an exception.
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(KernelExceptionMessageConstant.CORRUPTED_OUTLINE_DICTIONARY_HAS_INFINITE_LOOP
, "<</Dest [4 0 R /Fit ] /Next 10 0 R /Parent <<>> /Prev 10 0 R /Title First Page >>"), exception.Message
);
}
}
[NUnit.Framework.Test]
public virtual void CreateOutlinesWithDifferentVariantsOfChildrenTest() {
using (MemoryStream baos = new MemoryStream()) {
using (PdfDocument pdfDocument = new PdfDocument(new PdfWriter(baos))) {
pdfDocument.GetCatalog().SetPageMode(PdfName.UseOutlines);
PdfPage firstPage = pdfDocument.AddNewPage();
PdfOutline a = pdfDocument.GetOutlines(false);
PdfOutline b = a.AddOutline("B");
PdfOutline e = b.AddOutline("E");
PdfOutline f = e.AddOutline("F");
PdfOutline d = b.AddOutline("D");
PdfOutline c = a.AddOutline("C");
PdfOutline g = f.AddOutline("G");
PdfOutline h = f.AddOutline("H");
a.AddDestination(PdfExplicitDestination.CreateFit(firstPage));
PdfOutline resultedA = pdfDocument.GetOutlines(true);
// Asserting children of root outline.
NUnit.Framework.Assert.AreEqual(2, resultedA.GetAllChildren().Count);
NUnit.Framework.Assert.AreEqual(resultedA, resultedA.GetAllChildren()[0].GetParent());
NUnit.Framework.Assert.AreEqual(resultedA, resultedA.GetAllChildren()[1].GetParent());
NUnit.Framework.Assert.IsTrue(resultedA.GetAllChildren()[1].GetAllChildren().IsEmpty());
NUnit.Framework.Assert.AreEqual(2, resultedA.GetAllChildren()[0].GetAllChildren().Count);
//Asserting children of B outline after reconstructing.
PdfOutline resultedB = resultedA.GetAllChildren()[0];
NUnit.Framework.Assert.AreEqual(resultedB, resultedB.GetAllChildren()[0].GetParent());
NUnit.Framework.Assert.AreEqual(resultedB, resultedB.GetAllChildren()[1].GetParent());
NUnit.Framework.Assert.IsTrue(resultedB.GetAllChildren()[1].GetAllChildren().IsEmpty());
NUnit.Framework.Assert.AreEqual(1, resultedB.GetAllChildren()[0].GetAllChildren().Count);
//Asserting children of E outline after reconstructing.
PdfOutline resultedE = resultedB.GetAllChildren()[0];
NUnit.Framework.Assert.AreEqual(resultedE, resultedE.GetAllChildren()[0].GetParent());
NUnit.Framework.Assert.AreEqual(2, resultedE.GetAllChildren()[0].GetAllChildren().Count);
//Asserting children of F outline after reconstructing.
PdfOutline resultedF = resultedE.GetAllChildren()[0];
NUnit.Framework.Assert.AreEqual(resultedF, resultedF.GetAllChildren()[0].GetParent());
NUnit.Framework.Assert.AreEqual(resultedF, resultedF.GetAllChildren()[1].GetParent());
NUnit.Framework.Assert.IsTrue(resultedF.GetAllChildren()[0].GetAllChildren().IsEmpty());
NUnit.Framework.Assert.IsTrue(resultedF.GetAllChildren()[1].GetAllChildren().IsEmpty());
}
}
}
private sealed class EmptyNameTree : IPdfNameTreeAccess {
public PdfObject GetEntry(PdfString key) {
return null;
}
public PdfObject GetEntry(String key) {
return null;
}
public ICollection<PdfString> GetKeys() {
return JavaCollectionsUtil.EmptySet<PdfString>();
}
}
}
}

View File

@@ -0,0 +1,74 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.IO.Source;
using TSpdf.Kernel.Exceptions;
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("UnitTest")]
public class PdfPageUnitTest : ExtendedTSpdfTest {
private static readonly String SOURCE_FOLDER = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/pdf/PdfPageUnitTest/";
[NUnit.Framework.Test]
public virtual void CannotGetMcidIfDocIsNotTagged() {
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
PdfPage pdfPage = pdfDoc.AddNewPage();
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfPage.GetNextMcid());
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.MUST_BE_A_TAGGED_DOCUMENT, exception.Message
);
}
[NUnit.Framework.Test]
public virtual void CannotSetPageLabelIfFirstPageLessThanOneTest() {
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
PdfPage pdfPage = pdfDoc.AddNewPage();
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfPage.SetPageLabel(PageLabelNumberingStyle
.DECIMAL_ARABIC_NUMERALS, "test_prefix", 0));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.IN_A_PAGE_LABEL_THE_PAGE_NUMBERS_MUST_BE_GREATER_OR_EQUAL_TO_1
, exception.Message);
}
[NUnit.Framework.Test]
public virtual void CannotFlushTagsIfNoTagStructureIsPresentTest() {
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
PdfPage pdfPage = pdfDoc.AddNewPage();
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfPage.TryFlushPageTags());
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.TAG_STRUCTURE_FLUSHING_FAILED_IT_MIGHT_BE_CORRUPTED
, exception.Message);
}
[NUnit.Framework.Test]
public virtual void MediaBoxAttributeIsNotPresentTest() {
PdfDocument pdfDoc = new PdfDocument(new PdfReader(SOURCE_FOLDER + "mediaBoxAttributeIsNotPresentTest.pdf"
));
PdfObject mediaBox = pdfDoc.GetPage(1).GetPdfObject().Get(PdfName.MediaBox);
NUnit.Framework.Assert.IsNull(mediaBox);
PdfPage page = pdfDoc.GetPage(1);
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => page.GetMediaBox());
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.CANNOT_RETRIEVE_MEDIA_BOX_ATTRIBUTE, exception
.Message);
}
}
}

View File

@@ -0,0 +1,739 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.Collections.Generic;
using System.IO;
using TSpdf.Commons.Utils;
using TSpdf.IO.Image;
using TSpdf.IO.Source;
using TSpdf.Kernel.Colors;
using TSpdf.Kernel.Exceptions;
using TSpdf.Kernel.Geom;
using TSpdf.Kernel.Pdf.Annot;
using TSpdf.Kernel.Pdf.Canvas;
using TSpdf.Kernel.Pdf.Extgstate;
using TSpdf.Kernel.Pdf.Xobject;
using TSpdf.Kernel.Utils;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("IntegrationTest")]
public class PdfPagesTest : ExtendedTSpdfTest {
public static readonly String DESTINATION_FOLDER = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/pdf/PdfPagesTest/";
public static readonly String SOURCE_FOLDER = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/pdf/PdfPagesTest/";
private static readonly PdfName PageNum = new PdfName("PageNum");
[NUnit.Framework.OneTimeSetUp]
public static void Setup() {
CreateDestinationFolder(DESTINATION_FOLDER);
}
[NUnit.Framework.Test]
public virtual void SimplePagesTest() {
String filename = "simplePagesTest.pdf";
int pageCount = 111;
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(DESTINATION_FOLDER + filename));
for (int i = 0; i < pageCount; i++) {
PdfPage page = pdfDoc.AddNewPage();
page.GetPdfObject().Put(PageNum, new PdfNumber(i + 1));
page.Flush();
}
pdfDoc.Close();
VerifyPagesOrder(DESTINATION_FOLDER + filename, pageCount);
}
[NUnit.Framework.Test]
public virtual void ReversePagesTest() {
String filename = "reversePagesTest.pdf";
int pageCount = 111;
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(DESTINATION_FOLDER + filename));
for (int i = pageCount; i > 0; i--) {
PdfPage page = new PdfPage(pdfDoc, pdfDoc.GetDefaultPageSize());
pdfDoc.AddPage(1, page);
page.GetPdfObject().Put(PageNum, new PdfNumber(i));
page.Flush();
}
pdfDoc.Close();
VerifyPagesOrder(DESTINATION_FOLDER + filename, pageCount);
}
[NUnit.Framework.Test]
public virtual void ReversePagesTest2() {
String filename = "1000PagesDocument_reversed.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfReader(SOURCE_FOLDER + "1000PagesDocument.pdf"), new PdfWriter
(DESTINATION_FOLDER + filename));
int n = pdfDoc.GetNumberOfPages();
for (int i = n - 1; i > 0; --i) {
pdfDoc.MovePage(i, n + 1);
}
pdfDoc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(DESTINATION_FOLDER + filename, SOURCE_FOLDER
+ "cmp_" + filename, DESTINATION_FOLDER, "diff"));
}
[NUnit.Framework.Test]
public virtual void RandomObjectPagesTest() {
String filename = "randomObjectPagesTest.pdf";
int pageCount = 10000;
int[] indexes = new int[pageCount];
for (int i = 0; i < indexes.Length; i++) {
indexes[i] = i + 1;
}
Random rnd = new Random();
for (int i = indexes.Length - 1; i > 0; i--) {
int index = rnd.Next(i + 1);
int a = indexes[index];
indexes[index] = indexes[i];
indexes[i] = a;
}
PdfDocument document = new PdfDocument(new PdfWriter(DESTINATION_FOLDER + filename));
PdfPage[] pages = new PdfPage[pageCount];
for (int i = 0; i < indexes.Length; i++) {
PdfPage page = document.AddNewPage();
page.GetPdfObject().Put(PageNum, new PdfNumber(indexes[i]));
//page.flush();
pages[indexes[i] - 1] = page;
}
int testPageXref = document.GetPage(1000).GetPdfObject().GetIndirectReference().GetObjNumber();
document.MovePage(1000, 1000);
NUnit.Framework.Assert.AreEqual(testPageXref, document.GetPage(1000).GetPdfObject().GetIndirectReference()
.GetObjNumber());
for (int i = 0; i < pages.Length; i++) {
NUnit.Framework.Assert.IsTrue(document.MovePage(pages[i], i + 1), "Move page");
}
document.Close();
VerifyPagesOrder(DESTINATION_FOLDER + filename, pageCount);
}
[NUnit.Framework.Test]
public virtual void RandomNumberPagesTest() {
String filename = "randomNumberPagesTest.pdf";
int pageCount = 1000;
int[] indexes = new int[pageCount];
for (int i = 0; i < indexes.Length; i++) {
indexes[i] = i + 1;
}
Random rnd = new Random();
for (int i = indexes.Length - 1; i > 0; i--) {
int index = rnd.Next(i + 1);
int a = indexes[index];
indexes[index] = indexes[i];
indexes[i] = a;
}
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(DESTINATION_FOLDER + filename));
for (int i = 0; i < indexes.Length; i++) {
PdfPage page = pdfDoc.AddNewPage();
page.GetPdfObject().Put(PageNum, new PdfNumber(indexes[i]));
}
for (int i = 1; i < pageCount; i++) {
for (int j = i + 1; j <= pageCount; j++) {
int j_page = pdfDoc.GetPage(j).GetPdfObject().GetAsNumber(PageNum).IntValue();
int i_page = pdfDoc.GetPage(i).GetPdfObject().GetAsNumber(PageNum).IntValue();
if (j_page < i_page) {
pdfDoc.MovePage(i, j);
pdfDoc.MovePage(j, i);
}
}
NUnit.Framework.Assert.IsTrue(VerifyIntegrity(pdfDoc.GetCatalog().GetPageTree()) == -1);
}
pdfDoc.Close();
VerifyPagesOrder(DESTINATION_FOLDER + filename, pageCount);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.REMOVING_PAGE_HAS_ALREADY_BEEN_FLUSHED)]
public virtual void InsertFlushedPageTest() {
PdfWriter writer = new PdfWriter(new MemoryStream());
PdfDocument pdfDoc = new PdfDocument(writer);
PdfPage page = pdfDoc.AddNewPage();
page.Flush();
pdfDoc.RemovePage(page);
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfDoc.AddPage(1, page));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.FLUSHED_PAGE_CANNOT_BE_ADDED_OR_INSERTED, e
.Message);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.REMOVING_PAGE_HAS_ALREADY_BEEN_FLUSHED)]
public virtual void AddFlushedPageTest() {
PdfWriter writer = new PdfWriter(new MemoryStream());
PdfDocument pdfDoc = new PdfDocument(writer);
PdfPage page = pdfDoc.AddNewPage();
page.Flush();
pdfDoc.RemovePage(page);
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfDoc.AddPage(page));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.FLUSHED_PAGE_CANNOT_BE_ADDED_OR_INSERTED, e
.Message);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.REMOVING_PAGE_HAS_ALREADY_BEEN_FLUSHED, Count = 2)]
public virtual void RemoveFlushedPage() {
String filename = "removeFlushedPage.pdf";
int pageCount = 10;
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(DESTINATION_FOLDER + filename));
PdfPage removedPage = pdfDoc.AddNewPage();
int removedPageObjectNumber = removedPage.GetPdfObject().GetIndirectReference().GetObjNumber();
removedPage.Flush();
pdfDoc.RemovePage(removedPage);
for (int i = 0; i < pageCount; i++) {
PdfPage page = pdfDoc.AddNewPage();
page.GetPdfObject().Put(PageNum, new PdfNumber(i + 1));
page.Flush();
}
NUnit.Framework.Assert.IsTrue(pdfDoc.RemovePage(pdfDoc.GetPage(pageCount)), "Remove last page");
NUnit.Framework.Assert.IsFalse(pdfDoc.GetXref().Get(removedPageObjectNumber).CheckState(PdfObject.FREE), "Free reference"
);
pdfDoc.Close();
VerifyPagesOrder(DESTINATION_FOLDER + filename, pageCount - 1);
}
[NUnit.Framework.Test]
public virtual void RemoveFlushedPageFromTaggedDocument() {
using (PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new MemoryStream()))) {
pdfDocument.SetTagged();
pdfDocument.AddNewPage();
pdfDocument.GetPage(1).Flush();
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfDocument.RemovePage(1));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.FLUSHED_PAGE_CANNOT_BE_REMOVED, e.Message);
}
}
[NUnit.Framework.Test]
public virtual void RemoveFlushedPageFromDocumentWithAcroForm() {
using (PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new MemoryStream()))) {
pdfDocument.GetCatalog().Put(PdfName.AcroForm, new PdfDictionary());
pdfDocument.AddNewPage();
pdfDocument.GetPage(1).Flush();
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfDocument.RemovePage(1));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.FLUSHED_PAGE_CANNOT_BE_REMOVED, e.Message);
}
}
[NUnit.Framework.Test]
public virtual void TestInheritedResources() {
PdfDocument pdfDocument = new PdfDocument(new PdfReader(SOURCE_FOLDER + "simpleInheritedResources.pdf"));
PdfPage page = pdfDocument.GetPage(1);
PdfDictionary dict = page.GetResources().GetResource(PdfName.ExtGState);
NUnit.Framework.Assert.AreEqual(2, dict.Size());
PdfExtGState gState = new PdfExtGState((PdfDictionary)dict.Get(new PdfName("Gs1")));
NUnit.Framework.Assert.AreEqual(10, gState.GetLineWidth());
}
[NUnit.Framework.Test]
public virtual void ReadFormXObjectsWithCircularReferencesInResources() {
// given input file contains circular reference in resources of form xobjects
// (form xobjects are nested inside each other)
String input = SOURCE_FOLDER + "circularReferencesInResources.pdf";
PdfReader reader1 = new PdfReader(input);
PdfDocument inputPdfDoc1 = new PdfDocument(reader1);
PdfPage page = inputPdfDoc1.GetPage(1);
PdfResources resources = page.GetResources();
IList<PdfFormXObject> formXObjects = new List<PdfFormXObject>();
// We just try to work with resources in arbitrary way and make sure that circular reference
// doesn't block it. However it is expected that PdfResources doesn't try to "look in deep"
// and recursively resolves resources, so this test should never meet any issues.
foreach (PdfName xObjName in resources.GetResourceNames(PdfName.XObject)) {
PdfFormXObject form = resources.GetForm(xObjName);
if (form != null) {
formXObjects.Add(form);
}
}
// ensure resources XObject entry is read correctly
NUnit.Framework.Assert.AreEqual(2, formXObjects.Count);
}
[NUnit.Framework.Test]
public virtual void TestInheritedResourcesUpdate() {
PdfDocument pdfDoc = new PdfDocument(new PdfReader(SOURCE_FOLDER + "simpleInheritedResources.pdf"), new PdfWriter
(DESTINATION_FOLDER + "updateInheritedResources.pdf").SetCompressionLevel(CompressionConstants.NO_COMPRESSION
));
PdfName newGsName = pdfDoc.GetPage(1).GetResources().AddExtGState(new PdfExtGState().SetLineWidth(30));
int gsCount = pdfDoc.GetPage(1).GetResources().GetResource(PdfName.ExtGState).Size();
pdfDoc.Close();
String compareResult = new CompareTool().CompareByContent(DESTINATION_FOLDER + "updateInheritedResources.pdf"
, SOURCE_FOLDER + "cmp_" + "updateInheritedResources.pdf", DESTINATION_FOLDER, "diff");
NUnit.Framework.Assert.AreEqual(3, gsCount);
NUnit.Framework.Assert.AreEqual("Gs3", newGsName.GetValue());
NUnit.Framework.Assert.IsNull(compareResult);
}
[NUnit.Framework.Test]
public virtual void ReorderInheritedResourcesTest() {
//TODO: DEVSIX-1643 Inherited resources aren't copied on page reordering
PdfDocument pdfDoc = new PdfDocument(new PdfReader(SOURCE_FOLDER + "inheritedFontResources.pdf"), new PdfWriter
(DESTINATION_FOLDER + "reorderInheritedFontResources.pdf"));
pdfDoc.MovePage(1, pdfDoc.GetNumberOfPages() + 1);
pdfDoc.RemovePage(1);
pdfDoc.Close();
String compareResult = new CompareTool().CompareByContent(DESTINATION_FOLDER + "reorderInheritedFontResources.pdf"
, SOURCE_FOLDER + "cmp_reorderInheritedFontResources.pdf", DESTINATION_FOLDER, "diff_reorderInheritedFontResources_"
);
NUnit.Framework.Assert.IsNull(compareResult);
}
[NUnit.Framework.Test]
public virtual void GetPageByDictionary() {
String filename = SOURCE_FOLDER + "1000PagesDocument.pdf";
PdfReader reader = new PdfReader(filename);
PdfDocument pdfDoc = new PdfDocument(reader);
PdfObject[] pageDictionaries = new PdfObject[] { pdfDoc.GetPdfObject(4), pdfDoc.GetPdfObject(255), pdfDoc.
GetPdfObject(512), pdfDoc.GetPdfObject(1023), pdfDoc.GetPdfObject(2049), pdfDoc.GetPdfObject(3100) };
foreach (PdfObject pageObject in pageDictionaries) {
PdfDictionary pageDictionary = (PdfDictionary)pageObject;
NUnit.Framework.Assert.AreEqual(PdfName.Page, pageDictionary.Get(PdfName.Type));
PdfPage page = pdfDoc.GetPage(pageDictionary);
NUnit.Framework.Assert.AreEqual(pageDictionary, page.GetPdfObject());
}
pdfDoc.Close();
}
[NUnit.Framework.Test]
public virtual void RemovePageWithFormFieldsTest() {
String testName = "docWithFieldsRemovePage.pdf";
String outPdf = DESTINATION_FOLDER + testName;
String sourceFile = SOURCE_FOLDER + "docWithFields.pdf";
using (PdfDocument pdfDoc = new PdfDocument(new PdfReader(sourceFile), new PdfWriter(outPdf))) {
pdfDoc.RemovePage(1);
}
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, SOURCE_FOLDER + "cmp_" + testName
, DESTINATION_FOLDER));
}
[NUnit.Framework.Test]
public virtual void GetPageSizeWithInheritedMediaBox() {
double eps = 0.0000001;
String filename = SOURCE_FOLDER + "inheritedMediaBox.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfReader(filename));
NUnit.Framework.Assert.AreEqual(0, pdfDoc.GetPage(1).GetPageSize().GetLeft(), eps);
NUnit.Framework.Assert.AreEqual(0, pdfDoc.GetPage(1).GetPageSize().GetBottom(), eps);
NUnit.Framework.Assert.AreEqual(595, pdfDoc.GetPage(1).GetPageSize().GetRight(), eps);
NUnit.Framework.Assert.AreEqual(842, pdfDoc.GetPage(1).GetPageSize().GetTop(), eps);
pdfDoc.Close();
}
[NUnit.Framework.Test]
public virtual void PageThumbnailTest() {
String filename = "pageThumbnail.pdf";
String imageSrc = "icon.jpg";
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(DESTINATION_FOLDER + filename).SetCompressionLevel(CompressionConstants
.NO_COMPRESSION));
PdfPage page = pdfDoc.AddNewPage().SetThumbnailImage(new PdfImageXObject(ImageDataFactory.Create(SOURCE_FOLDER
+ imageSrc)));
new PdfCanvas(page).SetFillColor(ColorConstants.RED).Rectangle(100, 100, 400, 400).Fill();
pdfDoc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(DESTINATION_FOLDER + filename, SOURCE_FOLDER
+ "cmp_" + filename, DESTINATION_FOLDER, "diff"));
}
[NUnit.Framework.Test]
public virtual void RotationPagesRotationTest() {
String filename = "singlePageDocumentWithRotation.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfReader(SOURCE_FOLDER + filename));
PdfPage page = pdfDoc.GetPage(1);
NUnit.Framework.Assert.AreEqual(90, page.GetRotation(), "Inherited value is invalid");
}
[NUnit.Framework.Test]
public virtual void PageTreeCleanupParentRefTest() {
String src = SOURCE_FOLDER + "CatalogWithPageAndPagesEntries.pdf";
String dest = DESTINATION_FOLDER + "CatalogWithPageAndPagesEntries_opened.pdf";
PdfReader reader = new PdfReader(src);
PdfWriter writer = new PdfWriter(dest);
PdfDocument pdfDoc = new PdfDocument(reader, writer);
pdfDoc.Close();
NUnit.Framework.Assert.IsTrue(TestPageTreeParentsValid(src) && TestPageTreeParentsValid(dest));
}
[NUnit.Framework.Test]
public virtual void PdfNumberInPageContentArrayTest() {
String src = SOURCE_FOLDER + "pdfNumberInPageContentArray.pdf";
String dest = DESTINATION_FOLDER + "pdfNumberInPageContentArray_saved.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
pdfDoc.Close();
// test is mainly to ensure document is successfully opened-and-closed without exceptions
pdfDoc = new PdfDocument(new PdfReader(dest));
PdfObject pageDictWithInvalidContents = pdfDoc.GetPdfObject(10);
PdfArray invalidContentsArray = ((PdfDictionary)pageDictWithInvalidContents).GetAsArray(PdfName.Contents);
NUnit.Framework.Assert.AreEqual(5, invalidContentsArray.Size());
NUnit.Framework.Assert.IsFalse(invalidContentsArray.Get(0).IsStream());
NUnit.Framework.Assert.IsFalse(invalidContentsArray.Get(1).IsStream());
NUnit.Framework.Assert.IsFalse(invalidContentsArray.Get(2).IsStream());
NUnit.Framework.Assert.IsFalse(invalidContentsArray.Get(3).IsStream());
NUnit.Framework.Assert.IsTrue(invalidContentsArray.Get(4).IsStream());
}
private bool TestPageTreeParentsValid(String src) {
bool valid = true;
PdfReader reader = new PdfReader(src);
PdfDocument pdfDocument = new PdfDocument(reader);
PdfDictionary page_root = pdfDocument.GetCatalog().GetPdfObject().GetAsDictionary(PdfName.Pages);
for (int x = 1; x < pdfDocument.GetNumberOfPdfObjects(); x++) {
PdfObject obj = pdfDocument.GetPdfObject(x);
if (obj != null && obj.IsDictionary() && ((PdfDictionary)obj).GetAsName(PdfName.Type) != null && ((PdfDictionary
)obj).GetAsName(PdfName.Type).Equals(PdfName.Pages)) {
if (obj != page_root) {
PdfDictionary parent = ((PdfDictionary)obj).GetAsDictionary(PdfName.Parent);
if (parent == null) {
System.Console.Out.WriteLine(obj);
valid = false;
}
}
}
}
return valid;
}
[NUnit.Framework.Test]
public virtual void TestExcessiveXrefEntriesForCopyXObject() {
PdfDocument inputPdf = new PdfDocument(new PdfReader(SOURCE_FOLDER + "input500.pdf"));
PdfDocument outputPdf = new PdfDocument(new PdfWriter(DESTINATION_FOLDER + "output500.pdf"));
float scaleX = 595f / 612f;
float scaleY = 842f / 792f;
for (int i = 1; i <= inputPdf.GetNumberOfPages(); ++i) {
PdfPage sourcePage = inputPdf.GetPage(i);
PdfFormXObject pageCopy = sourcePage.CopyAsFormXObject(outputPdf);
PdfPage page = outputPdf.AddNewPage(PageSize.A4);
PdfCanvas outputCanvas = new PdfCanvas(page);
outputCanvas.AddXObjectWithTransformationMatrix(pageCopy, scaleX, 0, 0, scaleY, 0, 0);
page.Flush();
}
outputPdf.Close();
inputPdf.Close();
NUnit.Framework.Assert.IsNotNull(outputPdf.GetXref());
NUnit.Framework.Assert.AreEqual(500, outputPdf.GetXref().Size() - inputPdf.GetXref().Size());
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.WRONG_MEDIABOX_SIZE_TOO_MANY_ARGUMENTS, Count = 1)]
public virtual void PageGetMediaBoxTooManyArgumentsTest() {
PdfReader reader = new PdfReader(SOURCE_FOLDER + "helloWorldMediaboxTooManyArguments.pdf");
Rectangle expected = new Rectangle(0, 0, 375, 300);
PdfDocument pdfDoc = new PdfDocument(reader);
PdfPage pageOne = pdfDoc.GetPage(1);
Rectangle actual = pageOne.GetPageSize();
NUnit.Framework.Assert.IsTrue(expected.EqualsWithEpsilon(actual));
}
[NUnit.Framework.Test]
public virtual void CloseDocumentWithRecursivePagesNodeReferencesThrowsExTest() {
using (PdfReader reader = new PdfReader(SOURCE_FOLDER + "recursivePagesNodeReference.pdf")) {
using (PdfWriter writer = new PdfWriter(new MemoryStream())) {
PdfDocument pdfDocument = new PdfDocument(reader, writer);
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfDocument.Close());
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(KernelExceptionMessageConstant.INVALID_PAGE_STRUCTURE
, 2), e.Message);
}
}
}
[NUnit.Framework.Test]
public virtual void GetPageWithRecursivePagesNodeReferenceInAppendModeThrowExTest() {
using (PdfReader reader = new PdfReader(SOURCE_FOLDER + "recursivePagesNodeReference.pdf")) {
using (PdfWriter writer = new PdfWriter(new MemoryStream())) {
using (PdfDocument pdfDocument = new PdfDocument(reader, writer, new StampingProperties().UseAppendMode())
) {
NUnit.Framework.Assert.AreEqual(2, pdfDocument.GetNumberOfPages());
NUnit.Framework.Assert.IsNotNull(pdfDocument.GetPage(1));
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfDocument.GetPage(2));
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(KernelExceptionMessageConstant.INVALID_PAGE_STRUCTURE
, 2), e.Message);
}
}
}
}
[NUnit.Framework.Test]
public virtual void CloseDocumentWithRecursivePagesNodeInAppendModeDoesNotThrowsTest() {
using (PdfReader reader = new PdfReader(SOURCE_FOLDER + "recursivePagesNodeReference.pdf")) {
using (PdfWriter writer = new PdfWriter(new MemoryStream())) {
using (PdfDocument pdfDocument = new PdfDocument(reader, writer, new StampingProperties().UseAppendMode())
) {
NUnit.Framework.Assert.DoesNotThrow(() => pdfDocument.Close());
}
}
}
}
[NUnit.Framework.Test]
public virtual void PageGetMediaBoxNotEnoughArgumentsTest() {
PdfReader reader = new PdfReader(SOURCE_FOLDER + "helloWorldMediaboxNotEnoughArguments.pdf");
PdfDocument pdfDoc = new PdfDocument(reader);
PdfPage pageOne = pdfDoc.GetPage(1);
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pageOne.GetPageSize());
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(KernelExceptionMessageConstant.WRONG_MEDIA_BOX_SIZE_TOO_FEW_ARGUMENTS
, 3), e.Message);
}
[NUnit.Framework.Test]
public virtual void InsertIntermediateParentTest() {
String filename = "insertIntermediateParentTest.pdf";
PdfReader reader = new PdfReader(SOURCE_FOLDER + filename);
PdfWriter writer = new PdfWriter(new MemoryStream());
PdfDocument pdfDoc = new PdfDocument(reader, writer, new StampingProperties().UseAppendMode());
PdfPage page = pdfDoc.GetFirstPage();
PdfPages pdfPages = new PdfPages(page.parentPages.GetFrom(), pdfDoc, page.parentPages);
page.parentPages.GetKids().Set(0, pdfPages.GetPdfObject());
page.parentPages.DecrementCount();
pdfPages.AddPage(page.GetPdfObject());
pdfDoc.Close();
NUnit.Framework.Assert.IsTrue(page.GetPdfObject().IsModified());
}
[NUnit.Framework.Test]
public virtual void VerifyPagesAreNotReadOnOpenTest() {
String srcFile = SOURCE_FOLDER + "taggedOnePage.pdf";
PdfPagesTest.CustomPdfReader reader = new PdfPagesTest.CustomPdfReader(this, srcFile);
PdfDocument document = new PdfDocument(reader);
document.Close();
NUnit.Framework.Assert.IsFalse(reader.pagesAreRead);
}
[NUnit.Framework.Test]
public virtual void CopyAnnotationWithoutSubtypeTest() {
using (MemoryStream baos = CreateSourceDocumentWithEmptyAnnotation(new MemoryStream())) {
using (PdfDocument documentToMerge = new PdfDocument(new PdfReader(new RandomAccessSourceFactory().CreateSource
(baos.ToArray()), new ReaderProperties()))) {
using (MemoryStream resultantBaos = new MemoryStream()) {
using (PdfDocument resultantDocument = new PdfDocument(new PdfWriter(resultantBaos))) {
// We do expect that the following line will not throw any NPE
PdfPage copiedPage = documentToMerge.GetPage(1).CopyTo(resultantDocument);
NUnit.Framework.Assert.AreEqual(1, copiedPage.GetAnnotations().Count);
NUnit.Framework.Assert.IsNull(copiedPage.GetAnnotations()[0].GetSubtype());
resultantDocument.AddPage(copiedPage);
}
}
}
}
}
[NUnit.Framework.Test]
public virtual void ReadPagesInBlocksTest() {
String srcFile = SOURCE_FOLDER + "docWithBalancedPageTree.pdf";
int maxAmountOfPagesReadAtATime = 0;
PdfPagesTest.CustomPdfReader reader = new PdfPagesTest.CustomPdfReader(this, srcFile);
PdfDocument document = new PdfDocument(reader);
for (int page = 1; page <= document.GetNumberOfPages(); page++) {
document.GetPage(page);
if (reader.numOfPagesRead > maxAmountOfPagesReadAtATime) {
maxAmountOfPagesReadAtATime = reader.numOfPagesRead;
}
reader.numOfPagesRead = 0;
}
NUnit.Framework.Assert.AreEqual(111, document.GetNumberOfPages());
NUnit.Framework.Assert.AreEqual(10, maxAmountOfPagesReadAtATime);
document.Close();
}
[NUnit.Framework.Test]
public virtual void ReadSinglePageTest() {
String srcFile = SOURCE_FOLDER + "allPagesAreLeaves.pdf";
PdfPagesTest.CustomPdfReader reader = new PdfPagesTest.CustomPdfReader(this, srcFile);
reader.SetMemorySavingMode(true);
PdfDocument document = new PdfDocument(reader);
int amountOfPages = document.GetNumberOfPages();
PdfPages pdfPages = document.catalog.GetPageTree().GetRoot();
PdfArray pageIndRefArray = ((PdfDictionary)pdfPages.GetPdfObject()).GetAsArray(PdfName.Kids);
document.GetPage(amountOfPages);
NUnit.Framework.Assert.AreEqual(1, GetAmountOfReadPages(pageIndRefArray));
document.GetPage(amountOfPages / 2);
NUnit.Framework.Assert.AreEqual(2, GetAmountOfReadPages(pageIndRefArray));
document.GetPage(1);
NUnit.Framework.Assert.AreEqual(3, GetAmountOfReadPages(pageIndRefArray));
document.Close();
}
[NUnit.Framework.Test]
public virtual void ImplicitPagesTreeRebuildingTest() {
String inFileName = SOURCE_FOLDER + "implicitPagesTreeRebuilding.pdf";
String outFileName = DESTINATION_FOLDER + "implicitPagesTreeRebuilding.pdf";
String cmpFileName = SOURCE_FOLDER + "cmp_implicitPagesTreeRebuilding.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(inFileName), new PdfWriter(outFileName));
pdfDocument.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, DESTINATION_FOLDER
));
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.PAGE_TREE_IS_BROKEN_FAILED_TO_RETRIEVE_PAGE)]
public virtual void BrokenPageTreeWithExcessiveLastPageTest() {
String inFileName = SOURCE_FOLDER + "brokenPageTreeNullLast.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(inFileName));
IList<int> pages = JavaUtil.ArraysAsList(4);
ICollection<int> nullPages = new HashSet<int>(pages);
FindAndAssertNullPages(pdfDocument, nullPages);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.PAGE_TREE_IS_BROKEN_FAILED_TO_RETRIEVE_PAGE)]
public virtual void BrokenPageTreeWithExcessiveMiddlePageTest() {
String inFileName = SOURCE_FOLDER + "brokenPageTreeNullMiddle.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(inFileName));
IList<int> pages = JavaUtil.ArraysAsList(3);
ICollection<int> nullPages = new HashSet<int>(pages);
FindAndAssertNullPages(pdfDocument, nullPages);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.PAGE_TREE_IS_BROKEN_FAILED_TO_RETRIEVE_PAGE, Count = 7)]
public virtual void BrokenPageTreeWithExcessiveMultipleNegativePagesTest() {
String inFileName = SOURCE_FOLDER + "brokenPageTreeNullMultipleSequence.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(inFileName));
IList<int> pages = JavaUtil.ArraysAsList(2, 3, 4, 6, 7, 8, 9);
ICollection<int> nullPages = new HashSet<int>(pages);
FindAndAssertNullPages(pdfDocument, nullPages);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.PAGE_TREE_IS_BROKEN_FAILED_TO_RETRIEVE_PAGE, Count = 2)]
public virtual void BrokenPageTreeWithExcessiveRangeNegativePagesTest() {
String inFileName = SOURCE_FOLDER + "brokenPageTreeNullRangeNegative.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(inFileName));
IList<int> pages = JavaUtil.ArraysAsList(2, 4);
ICollection<int> nullPages = new HashSet<int>(pages);
FindAndAssertNullPages(pdfDocument, nullPages);
}
[NUnit.Framework.Test]
public virtual void TestPageTreeGenerationWhenFirstPdfPagesHasOnePageOnly() {
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new MemoryStream()));
int totalPageCount = PdfPagesTree.DEFAULT_LEAF_SIZE + 4;
for (int i = 0; i < totalPageCount; i++) {
pdfDocument.AddNewPage();
}
NUnit.Framework.Assert.AreEqual(2, pdfDocument.GetCatalog().GetPageTree().GetParents().Count);
NUnit.Framework.Assert.AreEqual(PdfPagesTree.DEFAULT_LEAF_SIZE, pdfDocument.GetCatalog().GetPageTree().GetParents
()[0].GetCount());
// Leave only one page in the first pages tree
for (int i = PdfPagesTree.DEFAULT_LEAF_SIZE - 1; i >= 1; i--) {
pdfDocument.RemovePage(i);
}
NUnit.Framework.Assert.AreEqual(2, pdfDocument.GetCatalog().GetPageTree().GetParents().Count);
NUnit.Framework.Assert.AreEqual(1, pdfDocument.GetCatalog().GetPageTree().GetParents()[0].GetCount());
// TODO DEVSIX-5575 remove expected exception and add proper assertions
NUnit.Framework.Assert.Catch(typeof(NullReferenceException), () => pdfDocument.Close());
}
private static void FindAndAssertNullPages(PdfDocument pdfDocument, ICollection<int> nullPages) {
foreach (int? nullPage in nullPages) {
int pageNum = (int)nullPage;
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfDocument.GetPage(pageNum
));
NUnit.Framework.Assert.AreEqual(exception.Message, MessageFormatUtil.Format(TSpdf.IO.Logs.IoLogMessageConstant
.PAGE_TREE_IS_BROKEN_FAILED_TO_RETRIEVE_PAGE, pageNum));
}
}
private static int GetAmountOfReadPages(PdfArray pageIndRefArray) {
int amountOfLoadedPages = 0;
for (int i = 0; i < pageIndRefArray.Size(); i++) {
if (((PdfIndirectReference)pageIndRefArray.Get(i, false)).refersTo != null) {
amountOfLoadedPages++;
}
}
return amountOfLoadedPages;
}
private static void VerifyPagesOrder(String filename, int numOfPages) {
PdfReader reader = new PdfReader(filename);
PdfDocument pdfDocument = new PdfDocument(reader);
NUnit.Framework.Assert.AreEqual(false, reader.HasRebuiltXref(), "Rebuilt");
for (int i = 1; i <= pdfDocument.GetNumberOfPages(); i++) {
PdfDictionary page = pdfDocument.GetPage(i).GetPdfObject();
NUnit.Framework.Assert.IsNotNull(page);
PdfNumber number = page.GetAsNumber(PageNum);
NUnit.Framework.Assert.AreEqual(i, number.IntValue(), "Page number");
}
NUnit.Framework.Assert.AreEqual(numOfPages, pdfDocument.GetNumberOfPages(), "Number of pages");
pdfDocument.Close();
}
private static int VerifyIntegrity(PdfPagesTree pagesTree) {
IList<PdfPages> parents = pagesTree.GetParents();
int from = 0;
for (int i = 0; i < parents.Count; i++) {
if (parents[i].GetFrom() != from) {
return i;
}
from = parents[i].GetFrom() + parents[i].GetCount();
}
return -1;
}
private static MemoryStream CreateSourceDocumentWithEmptyAnnotation(MemoryStream baos) {
using (PdfDocument sourceDocument = new PdfDocument(new PdfWriter(baos))) {
PdfPage page = sourceDocument.AddNewPage();
PdfAnnotation annotation = PdfAnnotation.MakeAnnotation(new PdfDictionary());
page.AddAnnotation(annotation);
return baos;
}
}
private class CustomPdfReader : PdfReader {
public bool pagesAreRead = false;
public int numOfPagesRead = 0;
public CustomPdfReader(PdfPagesTest _enclosing, String filename)
: base(filename) {
this._enclosing = _enclosing;
}
protected internal override PdfObject ReadObject(PdfIndirectReference reference) {
PdfObject toReturn = base.ReadObject(reference);
if (toReturn is PdfDictionary && PdfName.Page.Equals(((PdfDictionary)toReturn).Get(PdfName.Type))) {
this.numOfPagesRead++;
this.pagesAreRead = true;
}
return toReturn;
}
private readonly PdfPagesTest _enclosing;
}
}
}

View File

@@ -0,0 +1,35 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using TSpdf.IO.Source;
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("UnitTest")]
public class PdfPagesTreeTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void GenerateTreeDocHasNoPagesTest() {
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
NUnit.Framework.Assert.DoesNotThrow(() => pdfDoc.Close());
}
}
}

View File

@@ -0,0 +1,367 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.Text;
using TSpdf.IO.Source;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("IntegrationTest")]
public class PdfPrimitivesTest : ExtendedTSpdfTest {
internal static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/pdf/PdfPrimitivesTest/";
internal static readonly PdfName TestArray = new PdfName("TestArray");
internal const int DefaultArraySize = 64;
internal const int PageCount = 1000;
public class RandomString {
private static readonly char[] symbols;
private readonly Random random = new Random();
private readonly char[] buf;
static RandomString() {
StringBuilder tmp = new StringBuilder();
for (char ch = 'A'; ch <= 'Z'; ++ch) {
tmp.Append(ch);
}
for (char ch = 'a'; ch <= 'z'; ++ch) {
tmp.Append(ch);
}
for (char ch = '0'; ch <= '9'; ++ch) {
tmp.Append(ch);
}
symbols = tmp.ToString().ToCharArray();
}
public RandomString(int length) {
if (length < 1) {
throw new ArgumentException("length < 1: " + length);
}
buf = new char[length];
}
public virtual String NextString() {
for (int idx = 0; idx < buf.Length; ++idx) {
buf[idx] = symbols[random.Next(symbols.Length)];
}
return new String(buf);
}
}
[NUnit.Framework.SetUp]
public virtual void Setup() {
CreateDestinationFolder(destinationFolder);
}
[NUnit.Framework.Test]
public virtual void PrimitivesFloatNumberTest() {
String filename = "primitivesFloatNumberTest.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(destinationFolder + filename));
for (int i = 0; i < PageCount; i++) {
PdfPage page = pdfDoc.AddNewPage();
PdfArray array = GeneratePdfArrayWithFloatNumbers(null, false);
page.GetPdfObject().Put(TestArray, array);
array.Flush();
page.Flush();
}
pdfDoc.Close();
}
[NUnit.Framework.Test]
public virtual void PrimitivesIntNumberTest() {
String filename = "primitivesIntNumberTest.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(destinationFolder + filename));
for (int i = 0; i < PageCount; i++) {
PdfPage page = pdfDoc.AddNewPage();
PdfArray array = GeneratePdfArrayWithIntNumbers(null, false);
page.GetPdfObject().Put(TestArray, array);
array.Flush();
page.Flush();
}
pdfDoc.Close();
}
[NUnit.Framework.Test]
public virtual void PrimitivesNameTest() {
String filename = "primitivesNameTest.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(destinationFolder + filename));
for (int i = 0; i < PageCount; i++) {
PdfPage page = pdfDoc.AddNewPage();
PdfArray array = GeneratePdfArrayWithNames(null, false);
page.GetPdfObject().Put(TestArray, array);
array.Flush();
page.Flush();
}
pdfDoc.Close();
}
[NUnit.Framework.Test]
public virtual void PrimitivesStringTest() {
String filename = "primitivesStringTest.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(destinationFolder + filename));
for (int i = 0; i < PageCount; i++) {
PdfPage page = pdfDoc.AddNewPage();
PdfArray array = GeneratePdfArrayWithStrings(null, false);
page.GetPdfObject().Put(TestArray, array);
array.Flush();
page.Flush();
}
pdfDoc.Close();
}
[NUnit.Framework.Test]
public virtual void PrimitivesBooleanTest() {
String filename = "primitivesBooleanTest.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(destinationFolder + filename));
for (int i = 0; i < PageCount; i++) {
PdfPage page = pdfDoc.AddNewPage();
page.GetPdfObject().Put(TestArray, GeneratePdfArrayWithBooleans(null, false));
page.Flush();
}
pdfDoc.Close();
}
[NUnit.Framework.Test]
public virtual void PrimitivesFloatNumberIndirectTest() {
String filename = "primitivesFloatNumberIndirectTest.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(destinationFolder + filename));
for (int i = 0; i < PageCount; i++) {
PdfPage page = pdfDoc.AddNewPage();
page.GetPdfObject().Put(TestArray, GeneratePdfArrayWithFloatNumbers(pdfDoc, true));
page.Flush();
}
pdfDoc.Close();
}
[NUnit.Framework.Test]
public virtual void PrimitivesIntNumberIndirectTest() {
String filename = "primitivesIntNumberIndirectTest.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(destinationFolder + filename));
for (int i = 0; i < PageCount; i++) {
PdfPage page = pdfDoc.AddNewPage();
page.GetPdfObject().Put(TestArray, GeneratePdfArrayWithIntNumbers(pdfDoc, true));
page.Flush();
}
pdfDoc.Close();
}
[NUnit.Framework.Test]
public virtual void PrimitivesStringIndirectTest() {
String filename = "primitivesStringIndirectTest.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(destinationFolder + filename));
for (int i = 0; i < PageCount; i++) {
PdfPage page = pdfDoc.AddNewPage();
page.GetPdfObject().Put(TestArray, GeneratePdfArrayWithStrings(pdfDoc, true));
page.Flush();
}
pdfDoc.Close();
}
[NUnit.Framework.Test]
public virtual void PrimitivesNameIndirectTest() {
String filename = "primitivesNameIndirectTest.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(destinationFolder + filename));
for (int i = 0; i < PageCount; i++) {
PdfPage page = pdfDoc.AddNewPage();
page.GetPdfObject().Put(TestArray, GeneratePdfArrayWithNames(pdfDoc, true));
page.Flush();
}
pdfDoc.Close();
}
[NUnit.Framework.Test]
public virtual void PrimitivesBooleanIndirectTest() {
String filename = "primitivesBooleanIndirectTest.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(destinationFolder + filename));
for (int i = 0; i < PageCount; i++) {
PdfPage page = pdfDoc.AddNewPage();
page.GetPdfObject().Put(TestArray, GeneratePdfArrayWithBooleans(pdfDoc, true));
page.Flush();
}
pdfDoc.Close();
}
[NUnit.Framework.Test]
public virtual void PdfNamesTest() {
PdfPrimitivesTest.RandomString rnd = new PdfPrimitivesTest.RandomString(16);
for (int i = 0; i < 10000000; i++) {
new PdfName(rnd.NextString());
}
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.DIRECTONLY_OBJECT_CANNOT_BE_INDIRECT)]
public virtual void MakeIndirectDirectOnlyPdfBoolean() {
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
PdfBoolean t = PdfBoolean.ValueOf(true);
t.MakeIndirect(pdfDoc);
}
[NUnit.Framework.Test]
public virtual void EqualStrings() {
PdfString a = (PdfString)new PdfString("abcd").MakeIndirect(new PdfDocument(new PdfWriter(new ByteArrayOutputStream
())));
PdfString b = new PdfString("abcd".GetBytes(System.Text.Encoding.ASCII));
NUnit.Framework.Assert.IsTrue(a.Equals(b));
PdfString c = new PdfString("abcd", "UTF-8");
NUnit.Framework.Assert.IsFalse(c.Equals(a));
}
[NUnit.Framework.Test]
public virtual void EqualNumbers() {
using (PdfDocument document = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()))) {
// add a page to avoid exception throwing on close
document.AddNewPage();
PdfNumber num1 = (PdfNumber)new PdfNumber(1).MakeIndirect(document);
PdfNumber num2 = new PdfNumber(2);
NUnit.Framework.Assert.IsFalse(num1.Equals(num2));
int hashCode = num1.GetHashCode();
num1.Increment();
NUnit.Framework.Assert.IsTrue(num1.Equals(num2));
NUnit.Framework.Assert.AreNotEqual(hashCode, num1.GetHashCode());
}
PdfNumber a = new PdfNumber(1);
PdfNumber aContent = new PdfNumber(a.GetInternalContent());
PdfNumber b = new PdfNumber(2);
PdfNumber bContent = new PdfNumber(b.GetInternalContent());
NUnit.Framework.Assert.IsTrue(a.Equals(aContent));
NUnit.Framework.Assert.AreEqual(a.GetHashCode(), aContent.GetHashCode());
NUnit.Framework.Assert.IsTrue(b.Equals(bContent));
NUnit.Framework.Assert.AreEqual(b.GetHashCode(), bContent.GetHashCode());
NUnit.Framework.Assert.IsFalse(aContent.Equals(bContent));
NUnit.Framework.Assert.AreNotEqual(aContent.GetHashCode(), bContent.GetHashCode());
aContent.Increment();
NUnit.Framework.Assert.IsFalse(a.Equals(aContent));
NUnit.Framework.Assert.AreNotEqual(a.GetHashCode(), aContent.GetHashCode());
NUnit.Framework.Assert.IsTrue(aContent.Equals(bContent));
NUnit.Framework.Assert.AreEqual(aContent.GetHashCode(), bContent.GetHashCode());
}
[NUnit.Framework.Test]
public virtual void EqualNames() {
PdfName a = (PdfName)new PdfName("abcd").MakeIndirect(new PdfDocument(new PdfWriter(new ByteArrayOutputStream
())));
PdfName b = new PdfName("abcd");
NUnit.Framework.Assert.IsTrue(a.Equals(b));
}
[NUnit.Framework.Test]
public virtual void EqualBoolean() {
PdfBoolean f = (PdfBoolean)new PdfBoolean(false).MakeIndirect(new PdfDocument(new PdfWriter(new ByteArrayOutputStream
())));
PdfBoolean t = new PdfBoolean(true);
NUnit.Framework.Assert.IsFalse(f.Equals(t));
NUnit.Framework.Assert.IsTrue(f.Equals(PdfBoolean.FALSE));
NUnit.Framework.Assert.IsTrue(t.Equals(PdfBoolean.TRUE));
}
[NUnit.Framework.Test]
public virtual void EqualNulls() {
PdfNull a = (PdfNull)new PdfNull().MakeIndirect(new PdfDocument(new PdfWriter(new ByteArrayOutputStream())
));
NUnit.Framework.Assert.IsTrue(a.Equals(PdfNull.PDF_NULL));
}
[NUnit.Framework.Test]
public virtual void EqualLiterals() {
PdfLiteral a = new PdfLiteral("abcd");
PdfLiteral b = new PdfLiteral("abcd".GetBytes(System.Text.Encoding.ASCII));
NUnit.Framework.Assert.IsTrue(a.Equals(b));
}
private PdfArray GeneratePdfArrayWithFloatNumbers(PdfDocument doc, bool indirects) {
PdfArray array = (PdfArray)new PdfArray().MakeIndirect(doc);
Random rnd = new Random();
for (int i = 0; i < DefaultArraySize; i++) {
PdfNumber num = new PdfNumber(rnd.NextFloat());
if (indirects) {
num.MakeIndirect(doc);
}
array.Add(num);
}
return array;
}
private PdfArray GeneratePdfArrayWithIntNumbers(PdfDocument doc, bool indirects) {
PdfArray array = (PdfArray)new PdfArray().MakeIndirect(doc);
Random rnd = new Random();
for (int i = 0; i < DefaultArraySize; i++) {
array.Add(new PdfNumber(rnd.Next()).MakeIndirect(indirects ? doc : null));
}
return array;
}
private PdfArray GeneratePdfArrayWithStrings(PdfDocument doc, bool indirects) {
PdfArray array = (PdfArray)new PdfArray().MakeIndirect(doc);
PdfPrimitivesTest.RandomString rnd = new PdfPrimitivesTest.RandomString(16);
for (int i = 0; i < DefaultArraySize; i++) {
array.Add(new PdfString(rnd.NextString()).MakeIndirect(indirects ? doc : null));
}
return array;
}
private PdfArray GeneratePdfArrayWithNames(PdfDocument doc, bool indirects) {
PdfArray array = (PdfArray)new PdfArray().MakeIndirect(doc);
PdfPrimitivesTest.RandomString rnd = new PdfPrimitivesTest.RandomString(6);
for (int i = 0; i < DefaultArraySize; i++) {
array.Add(new PdfName(rnd.NextString()).MakeIndirect(indirects ? doc : null));
}
return array;
}
private PdfArray GeneratePdfArrayWithBooleans(PdfDocument doc, bool indirects) {
PdfArray array = (PdfArray)new PdfArray().MakeIndirect(doc);
Random rnd = new Random();
for (int i = 0; i < DefaultArraySize; i++) {
array.Add(new PdfBoolean(rnd.NextBoolean()).MakeIndirect(indirects ? doc : null));
}
return array;
}
}
}

View File

@@ -0,0 +1,261 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.IO;
using TSpdf.Kernel.Exceptions;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("IntegrationTest")]
public class PdfReaderDecodeTest : ExtendedTSpdfTest {
public static readonly String SOURCE_FOLDER = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/pdf/PdfReaderDecodeTest/";
[NUnit.Framework.Test]
public virtual void NoMemoryHandlerTest() {
using (PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new MemoryStream()))) {
using (FileStream @is = new FileStream(SOURCE_FOLDER + "stream", FileMode.Open, FileAccess.Read)) {
byte[] b = new byte[51];
@is.Read(b);
PdfArray array = new PdfArray();
PdfStream stream = new PdfStream(b);
stream.Put(PdfName.Filter, array);
stream.MakeIndirect(pdfDocument);
NUnit.Framework.Assert.AreEqual(51, PdfReader.DecodeBytes(b, stream).Length);
array.Add(PdfName.Fl);
NUnit.Framework.Assert.AreEqual(40, PdfReader.DecodeBytes(b, stream).Length);
array.Add(PdfName.Fl);
NUnit.Framework.Assert.AreEqual(992, PdfReader.DecodeBytes(b, stream).Length);
array.Add(PdfName.Fl);
NUnit.Framework.Assert.AreEqual(1000000, PdfReader.DecodeBytes(b, stream).Length);
// needed to close the document
pdfDocument.AddNewPage();
}
}
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.INVALID_INDIRECT_REFERENCE)]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)]
public virtual void DefaultMemoryHandlerTest() {
using (PdfDocument pdfDocument = new PdfDocument(new PdfReader(SOURCE_FOLDER + "timing.pdf"), new PdfWriter
(new MemoryStream()))) {
PdfStream stream = pdfDocument.GetFirstPage().GetContentStream(0);
byte[] b = stream.GetBytes(false);
PdfArray array = new PdfArray();
stream.Put(PdfName.Filter, array);
NUnit.Framework.Assert.AreEqual(51, PdfReader.DecodeBytes(b, stream).Length);
array.Add(PdfName.Fl);
NUnit.Framework.Assert.AreEqual(40, PdfReader.DecodeBytes(b, stream).Length);
array.Add(PdfName.Fl);
NUnit.Framework.Assert.AreEqual(992, PdfReader.DecodeBytes(b, stream).Length);
array.Add(PdfName.Fl);
NUnit.Framework.Assert.AreEqual(1000000, PdfReader.DecodeBytes(b, stream).Length);
}
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.INVALID_INDIRECT_REFERENCE)]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)]
public virtual void CustomMemoryHandlerSingleTest() {
MemoryLimitsAwareHandler handler = new MemoryLimitsAwareHandler();
handler.SetMaxSizeOfSingleDecompressedPdfStream(1000);
using (PdfDocument pdfDocument = new PdfDocument(new PdfReader(SOURCE_FOLDER + "timing.pdf", new ReaderProperties
().SetMemoryLimitsAwareHandler(handler)), new PdfWriter(new MemoryStream()))) {
PdfStream stream = pdfDocument.GetFirstPage().GetContentStream(0);
byte[] b = stream.GetBytes(false);
PdfArray array = new PdfArray();
stream.Put(PdfName.Filter, array);
NUnit.Framework.Assert.AreEqual(51, PdfReader.DecodeBytes(b, stream).Length);
array.Add(PdfName.Fl);
NUnit.Framework.Assert.AreEqual(40, PdfReader.DecodeBytes(b, stream).Length);
array.Add(PdfName.Fl);
NUnit.Framework.Assert.AreEqual(992, PdfReader.DecodeBytes(b, stream).Length);
array.Add(PdfName.Fl);
Exception e = NUnit.Framework.Assert.Catch(typeof(MemoryLimitsAwareException), () => PdfReader.DecodeBytes
(b, stream));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.DURING_DECOMPRESSION_SINGLE_STREAM_OCCUPIED_MORE_MEMORY_THAN_ALLOWED
, e.Message);
}
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.INVALID_INDIRECT_REFERENCE)]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)]
public virtual void OneFilterCustomMemoryHandlerSingleTest() {
MemoryLimitsAwareHandler handler = new MemoryLimitsAwareHandler();
handler.SetMaxSizeOfSingleDecompressedPdfStream(20);
using (PdfDocument pdfDocument = new PdfDocument(new PdfReader(SOURCE_FOLDER + "timing.pdf", new ReaderProperties
().SetMemoryLimitsAwareHandler(handler)), new PdfWriter(new MemoryStream()))) {
PdfStream stream = pdfDocument.GetFirstPage().GetContentStream(0);
byte[] b = stream.GetBytes(false);
PdfArray array = new PdfArray();
stream.Put(PdfName.Filter, array);
// Limit is reached, but the stream has no filters. Therefore, we don't consider it to be suspicious.
NUnit.Framework.Assert.AreEqual(51, PdfReader.DecodeBytes(b, stream).Length);
// Limit is reached, but the stream has only one filter. Therefore, we don't consider it to be suspicious.
array.Add(PdfName.Fl);
NUnit.Framework.Assert.AreEqual(40, PdfReader.DecodeBytes(b, stream).Length);
}
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.INVALID_INDIRECT_REFERENCE)]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)]
public virtual void OverriddenMemoryHandlerAllStreamsAreSuspiciousTest() {
MemoryLimitsAwareHandler handler = new _MemoryLimitsAwareHandler_194();
handler.SetMaxSizeOfSingleDecompressedPdfStream(20);
using (PdfDocument pdfDocument = new PdfDocument(new PdfReader(SOURCE_FOLDER + "timing.pdf", new ReaderProperties
().SetMemoryLimitsAwareHandler(handler)), new PdfWriter(new MemoryStream()))) {
PdfStream stream = pdfDocument.GetFirstPage().GetContentStream(0);
byte[] b = stream.GetBytes(false);
PdfArray array = new PdfArray();
stream.Put(PdfName.Filter, array);
array.Add(PdfName.Fl);
// Limit is reached, and the stream with one filter is considered to be suspicious.
Exception e = NUnit.Framework.Assert.Catch(typeof(MemoryLimitsAwareException), () => PdfReader.DecodeBytes
(b, stream));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.DURING_DECOMPRESSION_SINGLE_STREAM_OCCUPIED_MORE_MEMORY_THAN_ALLOWED
, e.Message);
}
}
private sealed class _MemoryLimitsAwareHandler_194 : MemoryLimitsAwareHandler {
public _MemoryLimitsAwareHandler_194() {
}
public override bool IsMemoryLimitsAwarenessRequiredOnDecompression(PdfArray filters) {
return true;
}
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.INVALID_INDIRECT_REFERENCE)]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)]
public virtual void OverriddenMemoryHandlerNoStreamsAreSuspiciousTest() {
MemoryLimitsAwareHandler handler = new _MemoryLimitsAwareHandler_229();
handler.SetMaxSizeOfSingleDecompressedPdfStream(20);
using (PdfDocument pdfDocument = new PdfDocument(new PdfReader(SOURCE_FOLDER + "timing.pdf", new ReaderProperties
().SetMemoryLimitsAwareHandler(handler)), new PdfWriter(new MemoryStream()))) {
PdfStream stream = pdfDocument.GetFirstPage().GetContentStream(0);
byte[] b = stream.GetBytes(false);
PdfArray array = new PdfArray();
stream.Put(PdfName.Filter, array);
array.Add(PdfName.Fl);
array.Add(PdfName.Fl);
// Limit is reached but the stream with several copies of the filter is not considered to be suspicious.
PdfReader.DecodeBytes(b, stream);
}
}
private sealed class _MemoryLimitsAwareHandler_229 : MemoryLimitsAwareHandler {
public _MemoryLimitsAwareHandler_229() {
}
public override bool IsMemoryLimitsAwarenessRequiredOnDecompression(PdfArray filters) {
return false;
}
}
[NUnit.Framework.Test]
public virtual void DifferentFiltersEmptyTest() {
byte[] b = new byte[1000];
PdfArray array = new PdfArray();
array.Add(PdfName.Fl);
array.Add(PdfName.AHx);
array.Add(PdfName.A85);
array.Add(PdfName.RunLengthDecode);
PdfStream stream = new PdfStream(b);
stream.Put(PdfName.Filter, array);
NUnit.Framework.Assert.AreEqual(0, PdfReader.DecodeBytes(b, stream).Length);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.INVALID_INDIRECT_REFERENCE)]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)]
public virtual void CustomMemoryHandlerSumTest() {
MemoryLimitsAwareHandler handler = new MemoryLimitsAwareHandler();
handler.SetMaxSizeOfDecompressedPdfStreamsSum(100000);
using (PdfDocument pdfDocument = new PdfDocument(new PdfReader(SOURCE_FOLDER + "timing.pdf", new ReaderProperties
().SetMemoryLimitsAwareHandler(handler)), new PdfWriter(new MemoryStream()))) {
PdfStream stream = pdfDocument.GetFirstPage().GetContentStream(0);
byte[] b = stream.GetBytes(false);
Exception e = NUnit.Framework.Assert.Catch(typeof(MemoryLimitsAwareException), () => PdfReader.DecodeBytes
(b, stream));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.DURING_DECOMPRESSION_MULTIPLE_STREAMS_IN_SUM_OCCUPIED_MORE_MEMORY_THAN_ALLOWED
, e.Message);
}
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.INVALID_INDIRECT_REFERENCE)]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)]
public virtual void PageSumTest() {
MemoryLimitsAwareHandler handler = new MemoryLimitsAwareHandler();
handler.SetMaxSizeOfDecompressedPdfStreamsSum(1500000);
using (PdfDocument pdfDocument = new PdfDocument(new PdfReader(SOURCE_FOLDER + "timing.pdf", new ReaderProperties
().SetMemoryLimitsAwareHandler(handler)), new PdfWriter(new MemoryStream()))) {
Exception e = NUnit.Framework.Assert.Catch(typeof(MemoryLimitsAwareException), () => pdfDocument.GetFirstPage
().GetContentBytes());
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.DURING_DECOMPRESSION_MULTIPLE_STREAMS_IN_SUM_OCCUPIED_MORE_MEMORY_THAN_ALLOWED
, e.Message);
}
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.INVALID_INDIRECT_REFERENCE)]
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT)]
public virtual void PageAsSingleStreamTest() {
MemoryLimitsAwareHandler handler = new MemoryLimitsAwareHandler();
handler.SetMaxSizeOfSingleDecompressedPdfStream(1500000);
using (PdfDocument pdfDocument = new PdfDocument(new PdfReader(SOURCE_FOLDER + "timing.pdf", new ReaderProperties
().SetMemoryLimitsAwareHandler(handler)), new PdfWriter(new MemoryStream()))) {
Exception e = NUnit.Framework.Assert.Catch(typeof(MemoryLimitsAwareException), () => pdfDocument.GetFirstPage
().GetContentBytes());
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.DURING_DECOMPRESSION_SINGLE_STREAM_OCCUPIED_MORE_MEMORY_THAN_ALLOWED
, e.Message);
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,132 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.Collections.Generic;
using System.IO;
using TSpdf.IO.Source;
using TSpdf.Kernel.Pdf.Extgstate;
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("IntegrationTest")]
public class PdfResourcesTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void ResourcesTest1() {
PdfDocument document = new PdfDocument(new PdfWriter(new MemoryStream()));
PdfPage page = document.AddNewPage();
PdfExtGState egs1 = new PdfExtGState();
PdfExtGState egs2 = new PdfExtGState();
PdfResources resources = page.GetResources();
PdfName n1 = resources.AddExtGState(egs1);
NUnit.Framework.Assert.AreEqual("Gs1", n1.GetValue());
PdfName n2 = resources.AddExtGState(egs2);
NUnit.Framework.Assert.AreEqual("Gs2", n2.GetValue());
n1 = resources.AddExtGState(egs1);
NUnit.Framework.Assert.AreEqual("Gs1", n1.GetValue());
document.Close();
}
[NUnit.Framework.Test]
public virtual void ResourcesTest2() {
MemoryStream baos = new MemoryStream();
PdfDocument document = new PdfDocument(new PdfWriter(baos));
PdfPage page = document.AddNewPage();
PdfExtGState egs1 = new PdfExtGState();
PdfExtGState egs2 = new PdfExtGState();
PdfResources resources = page.GetResources();
resources.AddExtGState(egs1);
resources.AddExtGState(egs2);
document.Close();
PdfReader reader = new PdfReader(new MemoryStream(baos.ToArray()));
document = new PdfDocument(reader, new PdfWriter(new ByteArrayOutputStream()));
page = document.GetPage(1);
resources = page.GetResources();
ICollection<PdfName> names = resources.GetResourceNames();
NUnit.Framework.Assert.AreEqual(2, names.Count);
String[] expectedNames = new String[] { "Gs1", "Gs2" };
int i = 0;
foreach (PdfName name in names) {
NUnit.Framework.Assert.AreEqual(expectedNames[i++], name.GetValue());
}
PdfExtGState egs3 = new PdfExtGState();
PdfName n3 = resources.AddExtGState(egs3);
NUnit.Framework.Assert.AreEqual("Gs3", n3.GetValue());
PdfDictionary egsResources = page.GetPdfObject().GetAsDictionary(PdfName.Resources).GetAsDictionary(PdfName
.ExtGState);
PdfDictionary e1 = egsResources.GetAsDictionary(new PdfName("Gs1"));
PdfName n1 = resources.AddExtGState(e1);
NUnit.Framework.Assert.AreEqual("Gs1", n1.GetValue());
PdfDictionary e2 = egsResources.GetAsDictionary(new PdfName("Gs2"));
PdfName n2 = resources.AddExtGState(e2);
NUnit.Framework.Assert.AreEqual("Gs2", n2.GetValue());
PdfDictionary e4 = (PdfDictionary)e2.Clone();
PdfName n4 = resources.AddExtGState(e4);
NUnit.Framework.Assert.AreEqual("Gs4", n4.GetValue());
document.Close();
}
[NUnit.Framework.Test]
public virtual void GetNonExistentResourcesCategory() {
PdfResources resources = new PdfResources();
ICollection<PdfName> unknownResCategory = resources.GetResourceNames(new PdfName("UnknownResCategory"));
// Assert returned value is properly functioning
PdfName randomResName = new PdfName("NonExistentResourceName");
NUnit.Framework.Assert.IsFalse(unknownResCategory.Contains(randomResName));
NUnit.Framework.Assert.IsFalse(unknownResCategory.Remove(randomResName));
NUnit.Framework.Assert.IsTrue(unknownResCategory.IsEmpty());
}
[NUnit.Framework.Test]
public virtual void ResourcesCategoryDictionarySetModifiedTest() {
PdfDictionary pdfDict = new PdfDictionary();
pdfDict.Put(PdfName.ExtGState, new PdfDictionary());
PdfResources resources = new PdfResources(pdfDict);
PdfObject resourceCategoryDict = resources.GetPdfObject().Get(PdfName.ExtGState);
resourceCategoryDict.SetIndirectReference(new PdfIndirectReference(null, 1));
NUnit.Framework.Assert.IsFalse(resourceCategoryDict.IsModified());
resources.AddExtGState(new PdfExtGState());
// Check that when changing an existing resource category dictionary, the flag PdfObject.MODIFIED will be set for it
NUnit.Framework.Assert.IsTrue(resourceCategoryDict.IsModified());
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,78 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.Commons.Utils;
using TSpdf.Kernel.Exceptions;
using TSpdf.Kernel.Logs;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("UnitTest")]
public class PdfStreamDecodeTest : ExtendedTSpdfTest {
private static readonly byte[] BYTES = new byte[] { (byte)0x78, (byte)0xda, (byte)0x01, (byte)0x28, (byte)
0x00, (byte)0xd7, (byte)0xff, (byte)0x78, (byte)0xda, (byte)0xab, (byte)0xb8, (byte)0xf5, (byte)0xf6,
(byte)0x60, (byte)0x23, (byte)0x03, (byte)0x10, (byte)0x1c, (byte)0x56, (byte)0x58, (byte)0xf1, (byte)
0x73, (byte)0xb7, (byte)0xec, (byte)0x93, (byte)0x50, (byte)0x46, (byte)0x86, (byte)0x51, (byte)0x30,
(byte)0x0a, (byte)0x46, (byte)0xc1, (byte)0x90, (byte)0x07, (byte)0xeb, (byte)0xd9, (byte)0x96, (byte)
0x87, (byte)0x26, (byte)0x84, (byte)0x03, (byte)0x00, (byte)0x27, (byte)0xef, (byte)0x0a, (byte)0x80,
(byte)0x91, (byte)0x9d, (byte)0x12, (byte)0x0e };
private static readonly byte[] FLATE_DECODED_BYTES = new byte[] { (byte)0x78, (byte)0x9c, (byte)0x01, (byte
)0x33, (byte)0x00, (byte)0xcc, (byte)0xff, (byte)0x78, (byte)0xda, (byte)0x01, (byte)0x28, (byte)0x00,
(byte)0xd7, (byte)0xff, (byte)0x78, (byte)0xda, (byte)0xab, (byte)0xb8, (byte)0xf5, (byte)0xf6, (byte)
0x60, (byte)0x23, (byte)0x03, (byte)0x10, (byte)0x1c, (byte)0x56, (byte)0x58, (byte)0xf1, (byte)0x73,
(byte)0xb7, (byte)0xec, (byte)0x93, (byte)0x50, (byte)0x46, (byte)0x86, (byte)0x51, (byte)0x30, (byte)
0x0a, (byte)0x46, (byte)0xc1, (byte)0x90, (byte)0x07, (byte)0xeb, (byte)0xd9, (byte)0x96, (byte)0x87,
(byte)0x26, (byte)0x84, (byte)0x03, (byte)0x00, (byte)0x27, (byte)0xef, (byte)0x0a, (byte)0x80, (byte)
0x91, (byte)0x9d, (byte)0x12, (byte)0x0e, (byte)0x7b, (byte)0xda, (byte)0x16, (byte)0xad };
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.DCTDECODE_FILTER_DECODING, LogLevel = LogLevelConstants.INFO)]
public virtual void TestDCTDecodeFilter() {
PdfStream pdfStream = new PdfStream(FLATE_DECODED_BYTES);
pdfStream.Put(PdfName.Filter, new PdfArray(JavaUtil.ArraysAsList((PdfObject)PdfName.FlateDecode, (PdfObject
)PdfName.DCTDecode)));
NUnit.Framework.Assert.AreEqual(BYTES, pdfStream.GetBytes());
}
[NUnit.Framework.Test]
public virtual void TestJBIG2DecodeFilter() {
PdfStream pdfStream = new PdfStream(FLATE_DECODED_BYTES);
pdfStream.Put(PdfName.Filter, new PdfArray(JavaUtil.ArraysAsList((PdfObject)PdfName.FlateDecode, (PdfObject
)PdfName.JBIG2Decode)));
Exception e = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfStream.GetBytes(true));
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(KernelExceptionMessageConstant.THIS_FILTER_IS_NOT_SUPPORTED
, PdfName.JBIG2Decode), e.Message);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.JPXDECODE_FILTER_DECODING, LogLevel = LogLevelConstants.INFO)]
public virtual void TestJPXDecodeFilter() {
PdfStream pdfStream = new PdfStream(FLATE_DECODED_BYTES);
pdfStream.Put(PdfName.Filter, new PdfArray(JavaUtil.ArraysAsList((PdfObject)PdfName.FlateDecode, (PdfObject
)PdfName.JPXDecode)));
NUnit.Framework.Assert.AreEqual(BYTES, pdfStream.GetBytes());
}
}
}

View File

@@ -0,0 +1,375 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using TSpdf.Commons.Utils;
using TSpdf.Kernel.Exceptions;
using TSpdf.Kernel.Logs;
using TSpdf.Kernel.Pdf.Xobject;
using TSpdf.Kernel.Utils;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("BouncyCastleIntegrationTest")]
public class PdfStreamTest : ExtendedTSpdfTest {
public static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/kernel/pdf/PdfStreamTest/";
public static readonly String destinationFolder = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/kernel/pdf/PdfStreamTest/";
[NUnit.Framework.OneTimeSetUp]
public static void Before() {
CreateOrClearDestinationFolder(destinationFolder);
}
[NUnit.Framework.Test]
public virtual void StreamAppendDataOnJustCopiedWithCompression() {
String srcFile = sourceFolder + "pageWithContent.pdf";
String cmpFile = sourceFolder + "cmp_streamAppendDataOnJustCopiedWithCompression.pdf";
String destFile = destinationFolder + "streamAppendDataOnJustCopiedWithCompression.pdf";
PdfDocument srcDocument = new PdfDocument(new PdfReader(srcFile));
PdfDocument document = new PdfDocument(new PdfWriter(destFile));
srcDocument.CopyPagesTo(1, 1, document);
srcDocument.Close();
String newContentString = "BT\n" + "/F1 36 Tf\n" + "50 700 Td\n" + "(new content here!) Tj\n" + "ET";
byte[] newContent = newContentString.GetBytes(System.Text.Encoding.UTF8);
document.GetPage(1).GetLastContentStream().SetData(newContent, true);
document.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destFile, cmpFile, destinationFolder, "diff_"
));
}
[NUnit.Framework.Test]
public virtual void RunLengthEncodingTest01() {
// Android-Conversion-Ignore-Test (TODO DEVSIX-6445 fix different DeflaterOutputStream behavior)
String srcFile = sourceFolder + "runLengthEncodedImages.pdf";
PdfDocument document = new PdfDocument(new PdfReader(srcFile));
PdfImageXObject im1 = document.GetPage(1).GetResources().GetImage(new PdfName("Im1"));
PdfImageXObject im2 = document.GetPage(1).GetResources().GetImage(new PdfName("Im2"));
byte[] imgBytes1 = im1.GetImageBytes();
byte[] imgBytes2 = im2.GetImageBytes();
document.Close();
byte[] cmpImgBytes1 = ReadFile(sourceFolder + "cmp_img1.jpg");
byte[] cmpImgBytes2 = ReadFile(sourceFolder + "cmp_img2.jpg");
NUnit.Framework.Assert.AreEqual(imgBytes1, cmpImgBytes1);
NUnit.Framework.Assert.AreEqual(imgBytes2, cmpImgBytes2);
}
[NUnit.Framework.Test]
public virtual void IndirectRefInFilterAndNoTaggedPdfTest() {
String inFile = sourceFolder + "indirectRefInFilterAndNoTaggedPdf.pdf";
String outFile = destinationFolder + "destIndirectRefInFilterAndNoTaggedPdf.pdf";
PdfDocument srcDoc = new PdfDocument(new PdfReader(inFile));
PdfDocument outDoc = new PdfDocument(new PdfReader(inFile), new PdfWriter(outFile));
outDoc.Close();
PdfDocument doc = new PdfDocument(new PdfReader(outFile));
PdfStream outStreamIm1 = doc.GetFirstPage().GetResources().GetResource(PdfName.XObject).GetAsStream(new PdfName
("Im1"));
PdfStream outStreamIm2 = doc.GetFirstPage().GetResources().GetResource(PdfName.XObject).GetAsStream(new PdfName
("Im2"));
PdfStream cmpStreamIm1 = srcDoc.GetFirstPage().GetResources().GetResource(PdfName.XObject).GetAsStream(new
PdfName("Im1"));
PdfStream cmpStreamIm2 = srcDoc.GetFirstPage().GetResources().GetResource(PdfName.XObject).GetAsStream(new
PdfName("Im2"));
NUnit.Framework.Assert.IsNull(new CompareTool().CompareStreamsStructure(outStreamIm1, cmpStreamIm1));
NUnit.Framework.Assert.IsNull(new CompareTool().CompareStreamsStructure(outStreamIm2, cmpStreamIm2));
srcDoc.Close();
outDoc.Close();
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void CryptFilterFlushedBeforeReadStreamTest() {
String file = sourceFolder + "cryptFilterTest.pdf";
String destFile = destinationFolder + "cryptFilterReadStreamTest.pdf";
PdfReader reader = new PdfReader(file, new ReaderProperties().SetPassword("World".GetBytes(TSpdf.Commons.Utils.EncodingUtil.ISO_8859_1
)));
int encryptionType = EncryptionConstants.ENCRYPTION_AES_256 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA;
int permissions = EncryptionConstants.ALLOW_SCREENREADERS;
WriterProperties writerProperties = new WriterProperties().SetStandardEncryption("World".GetBytes(TSpdf.Commons.Utils.EncodingUtil.ISO_8859_1
), "Hello".GetBytes(TSpdf.Commons.Utils.EncodingUtil.ISO_8859_1), permissions, encryptionType);
PdfWriter writer = new PdfWriter(destFile, writerProperties.AddXmpMetadata());
PdfDocument doc = new PdfDocument(reader, writer);
((PdfStream)doc.GetPdfObject(5)).GetBytes();
//Simulating that this flush happened automatically before normal stream flushing in close method
((PdfStream)doc.GetPdfObject(5)).Get(PdfName.Filter).Flush();
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => doc.Close());
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(KernelExceptionMessageConstant.FLUSHED_STREAM_FILTER_EXCEPTION
, "5", "0"), exception.Message);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void CryptFilterFlushedBeforeStreamTest() {
String file = sourceFolder + "cryptFilterTest.pdf";
String destFile = destinationFolder + "cryptFilterStreamNotReadTest.pdf";
PdfReader reader = new PdfReader(file, new ReaderProperties().SetPassword("World".GetBytes(TSpdf.Commons.Utils.EncodingUtil.ISO_8859_1
)));
int encryptionType = EncryptionConstants.ENCRYPTION_AES_256 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA;
int permissions = EncryptionConstants.ALLOW_SCREENREADERS;
WriterProperties writerProperties = new WriterProperties().SetStandardEncryption("World".GetBytes(TSpdf.Commons.Utils.EncodingUtil.ISO_8859_1
), "Hello".GetBytes(TSpdf.Commons.Utils.EncodingUtil.ISO_8859_1), permissions, encryptionType);
PdfWriter writer = new PdfWriter(destFile, writerProperties.AddXmpMetadata());
PdfDocument doc = new PdfDocument(reader, writer);
//Simulating that this flush happened automatically before normal stream flushing in close method
((PdfStream)doc.GetPdfObject(5)).Get(PdfName.Filter).Flush();
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => doc.Close());
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(KernelExceptionMessageConstant.FLUSHED_STREAM_FILTER_EXCEPTION
, "5", "0"), exception.Message);
}
[NUnit.Framework.Test]
[LogMessage(KernelLogMessageConstant.MD5_IS_NOT_FIPS_COMPLIANT, Ignore = true)]
public virtual void CryptFilterFlushedAfterStreamTest() {
String file = sourceFolder + "cryptFilterTest.pdf";
String cmpFile = sourceFolder + "cmp_cryptFilterTest.pdf";
String destFile = destinationFolder + "cryptFilterTest.pdf";
byte[] user = "Hello".GetBytes(TSpdf.Commons.Utils.EncodingUtil.ISO_8859_1);
byte[] owner = "World".GetBytes(TSpdf.Commons.Utils.EncodingUtil.ISO_8859_1);
PdfReader reader = new PdfReader(file, new ReaderProperties().SetPassword(owner));
int encryptionType = EncryptionConstants.ENCRYPTION_AES_256 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA;
int permissions = EncryptionConstants.ALLOW_SCREENREADERS;
WriterProperties writerProperties = new WriterProperties().SetStandardEncryption(user, owner, permissions,
encryptionType);
PdfWriter writer = new PdfWriter(destFile, writerProperties.AddXmpMetadata());
writer.SetCompressionLevel(-1);
PdfDocument doc = new PdfDocument(reader, writer);
PdfObject cryptFilter = ((PdfStream)doc.GetPdfObject(5)).Get(PdfName.Filter);
doc.GetPdfObject(5).Flush();
//Simulating that this flush happened automatically before normal stream flushing in close method
cryptFilter.Flush();
doc.Close();
CompareTool compareTool = new CompareTool().EnableEncryptionCompare();
String compareResult = compareTool.CompareByContent(destFile, cmpFile, destinationFolder, "diff_", user, user
);
if (compareResult != null) {
NUnit.Framework.Assert.Fail(compareResult);
}
}
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.FILTER_WAS_ALREADY_FLUSHED, Count = 2, LogLevel = LogLevelConstants
.INFO)]
[NUnit.Framework.Test]
public virtual void IndirectFilterInCatalogTest() {
String file = sourceFolder + "indFilterInCatalog.pdf";
String cmpFile = sourceFolder + "cmp_indFilterInCatalog.pdf";
String destFile = destinationFolder + "indFilterInCatalog.pdf";
PdfDocument doc = new PdfDocument(new PdfReader(file), new PdfWriter(destFile));
doc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destFile, cmpFile, destinationFolder));
}
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.FILTER_WAS_ALREADY_FLUSHED, Count = 2, LogLevel = LogLevelConstants
.INFO)]
[NUnit.Framework.Test]
public virtual void UserDefinedCompressionWithIndirectFilterInCatalogTest() {
String file = sourceFolder + "indFilterInCatalog.pdf";
String cmpFile = sourceFolder + "cmp_indFilterInCatalog.pdf";
String destFile = destinationFolder + "indFilterInCatalog.pdf";
PdfDocument doc = new PdfDocument(new PdfReader(file), new PdfWriter(destFile));
PdfStream stream = (PdfStream)doc.GetPdfObject(5);
stream.SetCompressionLevel(CompressionConstants.BEST_COMPRESSION);
doc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destFile, cmpFile, destinationFolder));
}
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.FILTER_WAS_ALREADY_FLUSHED, Count = 2, LogLevel = LogLevelConstants
.INFO)]
[NUnit.Framework.Test]
public virtual void IndirectFilterFlushedBeforeStreamTest() {
String file = sourceFolder + "indFilterInCatalog.pdf";
String cmpFile = sourceFolder + "cmp_indFilterInCatalog.pdf";
String destFile = destinationFolder + "indFilterInCatalog.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfReader(file), new PdfWriter(destFile));
// Simulate the case in which filter is somehow already flushed before stream.
// Either directly by user or because of any other reason.
PdfObject filterObject = pdfDoc.GetPdfObject(6);
//Simulating that this flush happened automatically before normal stream flushing in close method
filterObject.Flush();
pdfDoc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destFile, cmpFile, destinationFolder));
}
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.FILTER_WAS_ALREADY_FLUSHED, Count = 2, LogLevel = LogLevelConstants
.INFO)]
[NUnit.Framework.Test]
public virtual void IndirectFilterMarkedToBeFlushedBeforeStreamTest() {
String file = sourceFolder + "indFilterInCatalog.pdf";
String cmpFile = sourceFolder + "cmp_indFilterInCatalog.pdf";
String destFile = destinationFolder + "indFilterInCatalog.pdf";
PdfWriter writer = new PdfWriter(destFile);
PdfDocument pdfDoc = new PdfDocument(new PdfReader(file), writer);
// Simulate the case when indirect filter object is marked to be flushed before the stream itself.
PdfObject filterObject = pdfDoc.GetPdfObject(6);
filterObject.GetIndirectReference().SetState(PdfObject.MUST_BE_FLUSHED);
// The image stream will be marked as MUST_BE_FLUSHED after page is flushed.
pdfDoc.GetFirstPage().GetPdfObject().GetIndirectReference().SetState(PdfObject.MUST_BE_FLUSHED);
// There was a NPE because FlateFilter was already flushed.
writer.FlushWaitingObjects(JavaCollectionsUtil.EmptySet<PdfIndirectReference>());
// There also was a NPE because FlateFilter was already flushed.
pdfDoc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destFile, cmpFile, destinationFolder));
}
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.FILTER_WAS_ALREADY_FLUSHED, LogLevel = LogLevelConstants.INFO
)]
[NUnit.Framework.Test]
public virtual void DecodeParamsFlushedBeforeStreamTest() {
String file = sourceFolder + "decodeParamsTest.pdf";
String cmpFile = sourceFolder + "cmp_decodeParamsTest.pdf";
String destFile = destinationFolder + "decodeParamsTest.pdf";
PdfDocument doc = new PdfDocument(new PdfReader(file), new PdfWriter(destFile));
PdfStream stream = (PdfStream)doc.GetPdfObject(7);
stream.SetCompressionLevel(CompressionConstants.BEST_COMPRESSION);
//Simulating that this flush happened automatically before normal stream flushing in close method
stream.Get(PdfName.DecodeParms).MakeIndirect(stream.GetIndirectReference().GetDocument()).Flush();
doc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destFile, cmpFile, destinationFolder));
}
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.FILTER_WAS_ALREADY_FLUSHED, LogLevel = LogLevelConstants.INFO
)]
[NUnit.Framework.Test]
public virtual void DecodeParamsPredictorFlushedBeforeStreamTest() {
String file = sourceFolder + "decodeParamsTest.pdf";
String cmpFile = sourceFolder + "cmp_decodeParamsPredictorTest.pdf";
String destFile = destinationFolder + "decodeParamsPredictorTest.pdf";
PdfDocument doc = new PdfDocument(new PdfReader(file), new PdfWriter(destFile));
PdfStream stream = (PdfStream)doc.GetPdfObject(7);
stream.SetCompressionLevel(CompressionConstants.BEST_COMPRESSION);
//Simulating that this flush happened automatically before normal stream flushing in close method
((PdfDictionary)stream.Get(PdfName.DecodeParms)).Get(PdfName.Predictor).MakeIndirect(stream.GetIndirectReference
().GetDocument()).Flush();
doc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destFile, cmpFile, destinationFolder));
}
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.FILTER_WAS_ALREADY_FLUSHED, LogLevel = LogLevelConstants.INFO
)]
[NUnit.Framework.Test]
public virtual void DecodeParamsColumnsFlushedBeforeStreamTest() {
String file = sourceFolder + "decodeParamsTest.pdf";
String cmpFile = sourceFolder + "cmp_decodeParamsColumnsTest.pdf";
String destFile = destinationFolder + "decodeParamsColumnsTest.pdf";
PdfDocument doc = new PdfDocument(new PdfReader(file), new PdfWriter(destFile));
PdfStream stream = (PdfStream)doc.GetPdfObject(7);
stream.SetCompressionLevel(CompressionConstants.BEST_COMPRESSION);
//Simulating that this flush happened automatically before normal stream flushing in close method
((PdfDictionary)stream.Get(PdfName.DecodeParms)).Get(PdfName.Columns).MakeIndirect(stream.GetIndirectReference
().GetDocument()).Flush();
doc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destFile, cmpFile, destinationFolder));
}
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.FILTER_WAS_ALREADY_FLUSHED, LogLevel = LogLevelConstants.INFO
)]
[NUnit.Framework.Test]
public virtual void DecodeParamsColorsFlushedBeforeStreamTest() {
String file = sourceFolder + "decodeParamsTest.pdf";
String cmpFile = sourceFolder + "cmp_decodeParamsColorsTest.pdf";
String destFile = destinationFolder + "decodeParamsColorsTest.pdf";
PdfDocument doc = new PdfDocument(new PdfReader(file), new PdfWriter(destFile));
PdfStream stream = (PdfStream)doc.GetPdfObject(7);
stream.SetCompressionLevel(CompressionConstants.BEST_COMPRESSION);
//Simulating that this flush happened automatically before normal stream flushing in close method
((PdfDictionary)stream.Get(PdfName.DecodeParms)).Get(PdfName.Colors).MakeIndirect(stream.GetIndirectReference
().GetDocument()).Flush();
doc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destFile, cmpFile, destinationFolder));
}
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.FILTER_WAS_ALREADY_FLUSHED, LogLevel = LogLevelConstants.INFO
)]
[NUnit.Framework.Test]
public virtual void DecodeParamsBitsPerComponentFlushedBeforeStreamTest() {
String file = sourceFolder + "decodeParamsTest.pdf";
String cmpFile = sourceFolder + "cmp_decodeParamsBitsPerComponentTest.pdf";
String destFile = destinationFolder + "decodeParamsBitsPerComponentTest.pdf";
PdfDocument doc = new PdfDocument(new PdfReader(file), new PdfWriter(destFile));
PdfStream stream = (PdfStream)doc.GetPdfObject(7);
stream.SetCompressionLevel(CompressionConstants.BEST_COMPRESSION);
//Simulating that this flush happened automatically before normal stream flushing in close method
((PdfDictionary)stream.Get(PdfName.DecodeParms)).Get(PdfName.BitsPerComponent).MakeIndirect(stream.GetIndirectReference
().GetDocument()).Flush();
doc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destFile, cmpFile, destinationFolder));
}
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.FILTER_WAS_ALREADY_FLUSHED, Count = 2, LogLevel = LogLevelConstants
.INFO)]
[NUnit.Framework.Test]
public virtual void FlateFilterFlushedWhileDecodeTest() {
String file = sourceFolder + "decodeParamsTest.pdf";
String cmpFile = sourceFolder + "cmp_flateFilterFlushedWhileDecodeTest.pdf";
String destFile = destinationFolder + "flateFilterFlushedWhileDecodeTest.pdf";
PdfDocument doc = new PdfDocument(new PdfReader(file), new PdfWriter(destFile));
PdfStream stream = (PdfStream)doc.GetPdfObject(7);
stream.SetCompressionLevel(CompressionConstants.BEST_COMPRESSION);
stream.Remove(PdfName.Filter);
stream.Put(PdfName.Filter, new PdfName(PdfName.FlateDecode.value));
//Simulating that this flush happened automatically before normal stream flushing in close method
stream.Get(PdfName.Filter).MakeIndirect(stream.GetIndirectReference().GetDocument()).Flush();
doc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destFile, cmpFile, destinationFolder));
}
[LogMessage(TSpdf.IO.Logs.IoLogMessageConstant.FILTER_WAS_ALREADY_FLUSHED, Count = 2, LogLevel = LogLevelConstants
.INFO)]
[NUnit.Framework.Test]
public virtual void ArrayFlateFilterFlushedWhileDecodeTest() {
String file = sourceFolder + "decodeParamsTest.pdf";
String cmpFile = sourceFolder + "cmp_arrayFlateFilterFlushedWhileDecodeTest.pdf";
String destFile = destinationFolder + "arrayFlateFilterFlushedWhileDecodeTest.pdf";
PdfDocument doc = new PdfDocument(new PdfReader(file), new PdfWriter(destFile));
PdfStream stream = (PdfStream)doc.GetPdfObject(7);
stream.SetCompressionLevel(CompressionConstants.BEST_COMPRESSION);
stream.Remove(PdfName.Filter);
stream.Put(PdfName.Filter, new PdfArray(new PdfName(PdfName.FlateDecode.value)));
//Simulating that this flush happened automatically before normal stream flushing in close method
stream.Get(PdfName.Filter).MakeIndirect(stream.GetIndirectReference().GetDocument()).Flush();
doc.Close();
NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destFile, cmpFile, destinationFolder));
}
}
}

View File

@@ -0,0 +1,51 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.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 <https://www.gnu.org/licenses/>.
*/
using System;
using System.IO;
using TSpdf.IO.Source;
using TSpdf.Kernel.Exceptions;
using TSpdf.Test;
namespace TSpdf.Kernel.Pdf {
[NUnit.Framework.Category("UnitTest")]
public class PdfStreamUnitTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void CannotCreatePdfStreamWithoutDocumentTest() {
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => new PdfStream(null, null, 1
));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.CANNOT_CREATE_PDFSTREAM_BY_INPUT_STREAM_WITHOUT_PDF_DOCUMENT
, exception.Message);
}
[NUnit.Framework.Test]
public virtual void SetDataToPdfStreamWithInputStreamTest() {
Stream inputStream = new MemoryStream(new byte[] { });
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
PdfStream pdfStream = new PdfStream(pdfDocument, inputStream, 1);
Exception exception = NUnit.Framework.Assert.Catch(typeof(PdfException), () => pdfStream.SetData(new byte[
] { }, true));
NUnit.Framework.Assert.AreEqual(KernelExceptionMessageConstant.CANNOT_SET_DATA_TO_PDF_STREAM_WHICH_WAS_CREATED_BY_INPUT_STREAM
, exception.Message);
}
}
}

Some files were not shown because too many files have changed in this diff Show More