1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
|
#region PDFsharp - A .NET library for processing PDF
//
// Authors:
// Stefan Lange (mailto:Stefan.Lange@pdfsharp.com)
//
// Copyright (c) 2005-2008 empira Software GmbH, Cologne (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Diagnostics;
using System.Collections;
using System.Globalization;
using System.Text;
using System.IO;
using PdfSharp.Pdf;
using PdfSharp.Pdf.Advanced;
using PdfSharp.Pdf.Security;
using PdfSharp.Pdf.Internal;
using PdfSharp.Internal;
namespace PdfSharp.Pdf.IO
{
/// <summary>
/// Encapsulates the arguments of the PdfPasswordProvider delegate.
/// </summary>
public class PdfPasswordProviderArgs
{
/// <summary>
/// Sets the password to open the document with.
/// </summary>
public string Password;
/// <summary>
/// When set to true the PdfReader.Open function returns null indicating that no PdfDocument was created.
/// </summary>
public bool Abort;
}
/// <summary>
/// A delegated used by the PdfReader.Open function to retrieve a password if the document is protected.
/// </summary>
public delegate void PdfPasswordProvider(PdfPasswordProviderArgs args);
/// <summary>
/// Represents the functionality for reading PDF documents.
/// </summary>
public sealed class PdfReader
{
// Makes this class static
PdfReader() { }
/// <summary>
/// Determines whether the file specified by its path is a PDF file by inspecting the first eight
/// bytes of the data. If the file header has the form %PDF-x.y the function returns the version
/// number as integer (e.g. 14 for PDF 1.4). If the file header is invalid or inaccessible
/// for any reason, 0 is returned. The function never throws an exception.
/// </summary>
public static int TestPdfFile(string path)
{
FileStream stream = null;
try
{
int pageNumber;
string realPath = PdfSharp.Drawing.XPdfForm.ExtractPageNumber(path, out pageNumber);
if (File.Exists(realPath)) // prevent unwanted exceptions during debugging
{
stream = new FileStream(realPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
byte[] bytes = new byte[1024];
stream.Read(bytes, 0, 1024);
return GetPdfFileVersion(bytes);
}
}
catch { }
finally
{
try
{
if (stream != null)
stream.Close();
}
catch { }
}
return 0;
}
/// <summary>
/// Determines whether the specified stream is a PDF file by inspecting the first eight
/// bytes of the data. If the data begins with %PDF-x.y the function returns the version
/// number as integer (e.g. 14 for PDF 1.4). If the data is invalid or inaccessible
/// for any reason, 0 is returned. The function never throws an exception.
/// </summary>
public static int TestPdfFile(Stream stream)
{
long pos = -1;
try
{
pos = stream.Position;
byte[] bytes = new byte[1024];
stream.Read(bytes, 0, 1024);
return GetPdfFileVersion(bytes);
}
catch { }
finally
{
try
{
if (pos != -1)
stream.Position = pos;
}
catch { }
}
return 0;
}
/// <summary>
/// Determines whether the specified data is a PDF file by inspecting the first eight
/// bytes of the data. If the data begins with %PDF-x.y the function returns the version
/// number as integer (e.g. 14 for PDF 1.4). If the data is invalid or inaccessible
/// for any reason, 0 is returned. The function never throws an exception.
/// </summary>
public static int TestPdfFile(byte[] data)
{
return GetPdfFileVersion(data);
}
/// <summary>
/// Implements scanning the PDF file version.
/// </summary>
internal static int GetPdfFileVersion(byte[] bytes)
{
try
{
// Acrobat accepts headers like %!PS-Adobe-N.n PDF-M.m...
string header = Encoding.ASCII.GetString(bytes);
if (header[0] == '%' || header.IndexOf("%PDF")>=0)
{
int ich = header.IndexOf("PDF-");
if (ich > 0 && header[ich + 5] == (byte)'.')
{
char major = header[ich + 4];
char minor = header[ich + 6];
if (major >= '1' && major < '2' && minor >= '0' && minor <= '9')
return ((int)(major - '0')) * 10 + (int)(minor - '0');
}
}
}
catch {}
return 0;
}
/// <summary>
/// Opens an existing PDF document.
/// </summary>
public static PdfDocument Open(string path, PdfDocumentOpenMode openmode)
{
return Open(path, null, openmode, null);
}
/// <summary>
/// Opens an existing PDF document.
/// </summary>
public static PdfDocument Open(string path, PdfDocumentOpenMode openmode, PdfPasswordProvider provider)
{
return Open(path, null, openmode, provider);
}
/// <summary>
/// Opens an existing PDF document.
/// </summary>
public static PdfDocument Open(string path, string password, PdfDocumentOpenMode openmode)
{
return Open(path, password, openmode, null);
}
/// <summary>
/// Opens an existing PDF document.
/// </summary>
public static PdfDocument Open(string path, string password, PdfDocumentOpenMode openmode, PdfPasswordProvider provider)
{
PdfDocument document = null;
Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
try
{
document = PdfReader.Open(stream, password, openmode, provider);
document.fullPath = Path.GetFullPath(path);
}
finally
{
if (stream != null)
stream.Close();
}
return document;
}
/// <summary>
/// Opens an existing PDF document.
/// </summary>
public static PdfDocument Open(string path)
{
return Open(path, null, PdfDocumentOpenMode.Modify, null);
}
/// <summary>
/// Opens an existing PDF document.
/// </summary>
public static PdfDocument Open(string path, string password)
{
return Open(path, password, PdfDocumentOpenMode.Modify, null);
}
/// <summary>
/// Opens an existing PDF document.
/// </summary>
public static PdfDocument Open(Stream stream, PdfDocumentOpenMode openmode)
{
return Open(stream, null, openmode);
}
/// <summary>
/// Opens an existing PDF document.
/// </summary>
public static PdfDocument Open(Stream stream, PdfDocumentOpenMode openmode, PdfPasswordProvider passwordProvider)
{
return Open(stream, null, openmode);
}
/// <summary>
/// Opens an existing PDF document.
/// </summary>
public static PdfDocument Open(Stream stream, string password, PdfDocumentOpenMode openmode)
{
return Open(stream, password, openmode, null);
}
/// <summary>
/// Opens an existing PDF document.
/// </summary>
public static PdfDocument Open(Stream stream, string password, PdfDocumentOpenMode openmode, PdfPasswordProvider passwordProvider)
{
PdfDocument document = null;
try
{
Lexer lexer = new Lexer(stream);
document = new PdfDocument(lexer);
document.state |= DocumentState.Imported;
document.openMode = openmode;
document.fileSize = stream.Length;
// Get file version
byte[] header = new byte[1024];
stream.Position = 0;
stream.Read(header, 0, 1024);
document.version = GetPdfFileVersion(header);
if (document.version == 0)
throw new InvalidOperationException(PSSR.InvalidPdf);
// Read all trailers
document.irefTable.IsUnderConstruction = true;
Parser parser = new Parser(document);
document.trailer = parser.ReadTrailer();
document.irefTable.IsUnderConstruction = false;
// Is document encrypted?
PdfReference xrefEncrypt = document.trailer.Elements[PdfTrailer.Keys.Encrypt] as PdfReference;
if (xrefEncrypt != null)
{
//xrefEncrypt.Value = parser.ReadObject(null, xrefEncrypt.ObjectID, false);
PdfObject encrypt = parser.ReadObject(null, xrefEncrypt.ObjectID, false);
encrypt.Reference = xrefEncrypt;
xrefEncrypt.Value = encrypt;
PdfStandardSecurityHandler securityHandler = document.SecurityHandler;
TryAgain:
int v = securityHandler.ValidatePassword(password);
if (v == 0)
{
if (passwordProvider != null)
{
PdfPasswordProviderArgs args = new PdfPasswordProviderArgs();
passwordProvider(args);
if (args.Abort)
return null;
password = args.Password;
goto TryAgain;
}
else
{
if (password == null)
throw new PdfReaderException(PSSR.PasswordRequired);
else
throw new PdfReaderException(PSSR.InvalidPassword);
}
}
else if (v == 1 && openmode == PdfDocumentOpenMode.Modify)
{
throw new PdfReaderException(PSSR.OwnerPasswordRequired);
}
}
else
{
if (password != null)
{
// Password specified but document is not encrypted.
// ignore
}
}
PdfReference[] irefs = document.irefTable.AllReferences;
int count = irefs.Length;
// Read all indirect objects
for (int idx = 0; idx < count; idx++)
{
PdfReference iref = irefs[idx];
if (iref.Value == null)
{
try
{
Debug.Assert(document.irefTable.Contains(iref.ObjectID));
PdfObject pdfObject = parser.ReadObject(null, iref.ObjectID, false);
Debug.Assert(pdfObject.Reference == iref);
pdfObject.Reference = iref;
Debug.Assert(pdfObject.Reference.Value != null, "something got wrong");
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
else
{
Debug.Assert(document.irefTable.Contains(iref.ObjectID));
iref.GetType();
}
// Set maximum object number
document.irefTable.maxObjectNumber = Math.Max(document.irefTable.maxObjectNumber, iref.ObjectNumber);
}
// Encrypt all objects
if (xrefEncrypt != null)
{
document.SecurityHandler.EncryptDocument();
}
// Fix references of trailer values and then objects and irefs are consistent.
document.trailer.Finish();
#if DEBUG_
// Some tests...
PdfReference[] reachables = document.xrefTable.TransitiveClosure(document.trailer);
reachables.GetType();
reachables = document.xrefTable.AllXRefs;
document.xrefTable.CheckConsistence();
#endif
if (openmode == PdfDocumentOpenMode.Modify)
{
// Create new or change existing document IDs
if (document.Internals.SecondDocumentID == "")
document.trailer.CreateNewDocumentIDs();
else
document.Internals.SecondDocumentID = PdfEncoders.RawEncoding.GetString(Guid.NewGuid().ToByteArray());
// Change modification date
document.Info.ModificationDate = DateTime.Now;
// Remove all unreachable objects
int removed = document.irefTable.Compact();
if (removed != 0)
Debug.WriteLine("Number of deleted unreachable objects: " + removed.ToString());
// Force flattening of page tree
PdfPages pages = document.Pages;
//bool b = document.irefTable.Contains(new PdfObjectID(1108));
//b.GetType();
document.irefTable.CheckConsistence();
document.irefTable.Renumber();
document.irefTable.CheckConsistence();
}
}
finally
{
//if (filestream != null)
// filestream.Close();
}
return document;
}
/// <summary>
/// Opens an existing PDF document.
/// </summary>
public static PdfDocument Open(Stream stream)
{
return PdfReader.Open(stream, PdfDocumentOpenMode.Modify);
}
}
}
|