Support for setting the compression level (zlib).

Works for streams created by PdfWriter, for the image types where FlateDecode is done by iText, and for font streams.


git-svn-id: svn://svn.code.sf.net/p/itextsharp/code/trunk@10 820d3149-562b-4f88-9aa4-a8e61a3485cf
master
psoares33 2008-07-27 15:43:33 +00:00
parent 61a66b3167
commit c4e9a9ce5f
26 changed files with 1229 additions and 991 deletions

View File

@ -177,6 +177,12 @@ namespace iTextSharp.text {
/// <summary> This is the original height of the image taking rotation into account. </summary> /// <summary> This is the original height of the image taking rotation into account. </summary>
protected float scaledHeight; protected float scaledHeight;
/**
* The compression level of the content streams.
* @since 2.1.3
*/
protected int compressionLevel = PdfStream.DEFAULT_COMPRESSION;
/// <summary> This is the rotation of the image. </summary> /// <summary> This is the rotation of the image. </summary>
protected float rotationRadians; protected float rotationRadians;
@ -1479,5 +1485,22 @@ namespace iTextSharp.text {
return directReference; return directReference;
} }
} }
/**
* Sets the compression level to be used if the image is written as a compressed stream.
* @param compressionLevel a value between 0 (best speed) and 9 (best compression)
* @since 2.1.3
*/
public int CompressionLevel {
set {
if (compressionLevel < PdfStream.NO_COMPRESSION || compressionLevel > PdfStream.BEST_COMPRESSION)
compressionLevel = PdfStream.DEFAULT_COMPRESSION;
else
compressionLevel = compressionLevel;
}
get {
return compressionLevel;
}
}
} }
} }

View File

@ -9,7 +9,7 @@ using System.util;
using iTextSharp.text.xml.simpleparser; using iTextSharp.text.xml.simpleparser;
/* /*
* $Id: BaseFont.cs,v 1.18 2008/06/01 13:17:07 psoares33 Exp $ * $Id: BaseFont.cs,v 1.17 2008/05/13 11:25:17 psoares33 Exp $
* *
* *
* Copyright 2000-2006 by Paulo Soares. * Copyright 2000-2006 by Paulo Soares.
@ -258,6 +258,12 @@ namespace iTextSharp.text.pdf {
/** true if the font is to be embedded in the PDF */ /** true if the font is to be embedded in the PDF */
protected bool embedded; protected bool embedded;
/**
* The compression level for the font stream.
* @since 2.1.3
*/
protected int compressionLevel = PdfStream.DEFAULT_COMPRESSION;
/** /**
* true if the font must use it's built in encoding. In that case the * true if the font must use it's built in encoding. In that case the
* <CODE>encoding</CODE> is only used to map a char to the position inside * <CODE>encoding</CODE> is only used to map a char to the position inside
@ -321,25 +327,36 @@ namespace iTextSharp.text.pdf {
internal class StreamFont : PdfStream { internal class StreamFont : PdfStream {
/** Generates the PDF stream with the Type1 and Truetype fonts returning /** Generates the PDF stream with the Type1 and Truetype fonts returning
* a PdfStream. * a PdfStream.
* @param contents the content of the stream * @param contents the content of the stream
* @param lengths an array of int that describes the several lengths of each part of the font * @param lengths an array of int that describes the several lengths of each part of the font
*/ * @param compressionLevel the compression level of the Stream
internal StreamFont(byte[] contents, int[] lengths) { * @throws DocumentException error in the stream compression
* @since 2.1.3 (replaces the constructor without param compressionLevel)
*/
internal StreamFont(byte[] contents, int[] lengths, int compressionLevel) {
bytes = contents; bytes = contents;
Put(PdfName.LENGTH, new PdfNumber(bytes.Length)); Put(PdfName.LENGTH, new PdfNumber(bytes.Length));
for (int k = 0; k < lengths.Length; ++k) { for (int k = 0; k < lengths.Length; ++k) {
Put(new PdfName("Length" + (k + 1)), new PdfNumber(lengths[k])); Put(new PdfName("Length" + (k + 1)), new PdfNumber(lengths[k]));
} }
FlateCompress(); FlateCompress(compressionLevel);
} }
internal StreamFont(byte[] contents, string subType) { /**
* Generates the PDF stream for a font.
* @param contents the content of a stream
* @param subType the subtype of the font.
* @param compressionLevel the compression level of the Stream
* @throws DocumentException error in the stream compression
* @since 2.1.3 (replaces the constructor without param compressionLevel)
*/
internal StreamFont(byte[] contents, string subType, int compressionLevel) {
bytes = contents; bytes = contents;
Put(PdfName.LENGTH, new PdfNumber(bytes.Length)); Put(PdfName.LENGTH, new PdfNumber(bytes.Length));
if (subType != null) if (subType != null)
Put(PdfName.SUBTYPE, new PdfName(subType)); Put(PdfName.SUBTYPE, new PdfName(subType));
FlateCompress(); FlateCompress(compressionLevel);
} }
} }
@ -1438,5 +1455,22 @@ namespace iTextSharp.text.pdf {
subsetRanges = new ArrayList(); subsetRanges = new ArrayList();
subsetRanges.Add(range); subsetRanges.Add(range);
} }
/**
* Sets the compression level to be used for the font streams.
* @param compressionLevel a value between 0 (best speed) and 9 (best compression)
* @since 2.1.3
*/
public int CompressionLevel {
set {
if (compressionLevel < PdfStream.NO_COMPRESSION || compressionLevel > PdfStream.BEST_COMPRESSION)
compressionLevel = PdfStream.DEFAULT_COMPRESSION;
else
compressionLevel = compressionLevel;
}
get {
return compressionLevel;
}
}
} }
} }

View File

@ -70,6 +70,7 @@ public class PRStream : PdfStream {
offset = stream.offset; offset = stream.offset;
length = stream.Length; length = stream.Length;
compressed = stream.compressed; compressed = stream.compressed;
compressionLevel = stream.compressionLevel;
streamBytes = stream.streamBytes; streamBytes = stream.streamBytes;
bytes = stream.bytes; bytes = stream.bytes;
objNum = stream.objNum; objNum = stream.objNum;
@ -89,12 +90,23 @@ public class PRStream : PdfStream {
this.offset = offset; this.offset = offset;
} }
public PRStream(PdfReader reader, byte[] conts) { public PRStream(PdfReader reader, byte[] conts) : this(reader, conts, DEFAULT_COMPRESSION) {
}
/**
* Creates a new PDF stream object that will replace a stream
* in a existing PDF file.
* @param reader the reader that holds the existing PDF
* @param conts the new content
* @param compressionLevel the compression level for the content
* @since 2.1.3 (replacing the existing constructor without param compressionLevel)
*/
public PRStream(PdfReader reader, byte[] conts, int compressionLevel) {
this.reader = reader; this.reader = reader;
this.offset = -1; this.offset = -1;
if (Document.Compress) { if (Document.Compress) {
MemoryStream stream = new MemoryStream(); MemoryStream stream = new MemoryStream();
ZDeflaterOutputStream zip = new ZDeflaterOutputStream(stream); ZDeflaterOutputStream zip = new ZDeflaterOutputStream(stream, compressionLevel);
zip.Write(conts, 0, conts.Length); zip.Write(conts, 0, conts.Length);
zip.Close(); zip.Close();
bytes = stream.ToArray(); bytes = stream.ToArray();
@ -115,14 +127,29 @@ public class PRStream : PdfStream {
* @since iText 2.1.1 * @since iText 2.1.1
*/ */
public void SetData(byte[] data, bool compress) { public void SetData(byte[] data, bool compress) {
SetData(data, compress, DEFAULT_COMPRESSION);
}
/**
* Sets the data associated with the stream, either compressed or
* uncompressed. Note that the data will never be compressed if
* Document.compress is set to false.
*
* @param data raw data, decrypted and uncompressed.
* @param compress true if you want the stream to be compresssed.
* @param compressionLevel a value between -1 and 9 (ignored if compress == false)
* @since iText 2.1.3
*/
public void SetData(byte[] data, bool compress, int compressionLevel) {
Remove(PdfName.FILTER); Remove(PdfName.FILTER);
this.offset = -1; this.offset = -1;
if (Document.Compress && compress) { if (Document.Compress && compress) {
MemoryStream stream = new MemoryStream(); MemoryStream stream = new MemoryStream();
ZDeflaterOutputStream zip = new ZDeflaterOutputStream(stream); ZDeflaterOutputStream zip = new ZDeflaterOutputStream(stream, compressionLevel);
zip.Write(data, 0, data.Length); zip.Write(data, 0, data.Length);
zip.Close(); zip.Close();
bytes = stream.ToArray(); bytes = stream.ToArray();
this.compressionLevel = compressionLevel;
Put(PdfName.FILTER, PdfName.FLATEDECODE); Put(PdfName.FILTER, PdfName.FLATEDECODE);
} }
else else
@ -195,7 +222,7 @@ public class PRStream : PdfStream {
Put(PdfName.LENGTH, objLen); Put(PdfName.LENGTH, objLen);
os.Write(STARTSTREAM, 0, STARTSTREAM.Length); os.Write(STARTSTREAM, 0, STARTSTREAM.Length);
if (length > 0) { if (length > 0) {
if (crypto != null) if (crypto != null && !crypto.IsEmbeddedFilesOnly())
b = crypto.EncryptByteArray(b); b = crypto.EncryptByteArray(b);
os.Write(b, 0, b.Length); os.Write(b, 0, b.Length);
} }

View File

@ -276,7 +276,7 @@ namespace iTextSharp.text.pdf {
else { else {
byte[] b = PdfEncodings.ConvertToBytes(code, unicode ? PdfObject.TEXT_UNICODE : PdfObject.TEXT_PDFDOCENCODING); byte[] b = PdfEncodings.ConvertToBytes(code, unicode ? PdfObject.TEXT_UNICODE : PdfObject.TEXT_PDFDOCENCODING);
PdfStream stream = new PdfStream(b); PdfStream stream = new PdfStream(b);
stream.FlateCompress(); stream.FlateCompress(writer.CompressionLevel);
js.Put(PdfName.JS, writer.AddToBody(stream).IndirectReference); js.Put(PdfName.JS, writer.AddToBody(stream).IndirectReference);
} }
return js; return js;

View File

@ -86,7 +86,7 @@ namespace iTextSharp.text.pdf {
streamBytes = new MemoryStream(); streamBytes = new MemoryStream();
if (Document.Compress) { if (Document.Compress) {
compressed = true; compressed = true;
ostr = new ZDeflaterOutputStream(streamBytes); ostr = new ZDeflaterOutputStream(streamBytes, text.PdfWriter.CompressionLevel);
} }
else else
ostr = streamBytes; ostr = streamBytes;

View File

@ -593,7 +593,7 @@ namespace iTextSharp.text.pdf {
if (over != null) if (over != null)
out_p.Append(PdfContents.SAVESTATE); out_p.Append(PdfContents.SAVESTATE);
PdfStream stream = new PdfStream(out_p.ToByteArray()); PdfStream stream = new PdfStream(out_p.ToByteArray());
stream.FlateCompress(); stream.FlateCompress(cstp.CompressionLevel);
PdfIndirectReference ref1 = cstp.AddToBody(stream).IndirectReference; PdfIndirectReference ref1 = cstp.AddToBody(stream).IndirectReference;
ar.AddFirst(ref1); ar.AddFirst(ref1);
out_p.Reset(); out_p.Reset();
@ -605,7 +605,7 @@ namespace iTextSharp.text.pdf {
out_p.Append(over.InternalBuffer); out_p.Append(over.InternalBuffer);
out_p.Append(PdfContents.RESTORESTATE); out_p.Append(PdfContents.RESTORESTATE);
stream = new PdfStream(out_p.ToByteArray()); stream = new PdfStream(out_p.ToByteArray());
stream.FlateCompress(); stream.FlateCompress(cstp.CompressionLevel);
ar.Add(cstp.AddToBody(stream).IndirectReference); ar.Add(cstp.AddToBody(stream).IndirectReference);
} }
pageN.Put(PdfName.RESOURCES, pageResources.Resources); pageN.Put(PdfName.RESOURCES, pageResources.Resources);

File diff suppressed because it is too large Load Diff

View File

@ -69,18 +69,15 @@ namespace iTextSharp.text.pdf {
/** This is the 1 - matrix. */ /** This is the 1 - matrix. */
public static PdfLiteral MATRIX = new PdfLiteral("[1 0 0 1 0 0]"); public static PdfLiteral MATRIX = new PdfLiteral("[1 0 0 1 0 0]");
// membervariables
// constructor
/** /**
* Constructs a <CODE>PdfFormXObject</CODE>-object. * Constructs a <CODE>PdfFormXObject</CODE>-object.
* *
* @param template the template * @param template the template
* @param compressionLevel the compression level for the stream
* @since 2.1.3 (Replacing the existing constructor with param compressionLevel)
*/ */
internal PdfFormXObject(PdfTemplate template) : base() { internal PdfFormXObject(PdfTemplate template, int compressionLevel) : base() {
Put(PdfName.TYPE, PdfName.XOBJECT); Put(PdfName.TYPE, PdfName.XOBJECT);
Put(PdfName.SUBTYPE, PdfName.FORM); Put(PdfName.SUBTYPE, PdfName.FORM);
Put(PdfName.RESOURCES, template.Resources); Put(PdfName.RESOURCES, template.Resources);
@ -97,7 +94,7 @@ namespace iTextSharp.text.pdf {
Put(PdfName.MATRIX, matrix); Put(PdfName.MATRIX, matrix);
bytes = template.ToPdf(null); bytes = template.ToPdf(null);
Put(PdfName.LENGTH, new PdfNumber(bytes.Length)); Put(PdfName.LENGTH, new PdfNumber(bytes.Length));
FlateCompress(); FlateCompress(compressionLevel);
} }
} }

View File

@ -79,7 +79,7 @@ namespace iTextSharp.text.pdf {
int bitsPerSample, int order, float[] encode, float[] decode, byte[] stream) { int bitsPerSample, int order, float[] encode, float[] decode, byte[] stream) {
PdfFunction func = new PdfFunction(writer); PdfFunction func = new PdfFunction(writer);
func.dictionary = new PdfStream(stream); func.dictionary = new PdfStream(stream);
((PdfStream)func.dictionary).FlateCompress(); ((PdfStream)func.dictionary).FlateCompress(writer.CompressionLevel);
func.dictionary.Put(PdfName.FUNCTIONTYPE, new PdfNumber(0)); func.dictionary.Put(PdfName.FUNCTIONTYPE, new PdfNumber(0));
func.dictionary.Put(PdfName.DOMAIN, new PdfArray(domain)); func.dictionary.Put(PdfName.DOMAIN, new PdfArray(domain));
func.dictionary.Put(PdfName.RANGE, new PdfArray(range)); func.dictionary.Put(PdfName.RANGE, new PdfArray(range));
@ -131,7 +131,7 @@ namespace iTextSharp.text.pdf {
b[k] = (byte)postscript[k]; b[k] = (byte)postscript[k];
PdfFunction func = new PdfFunction(writer); PdfFunction func = new PdfFunction(writer);
func.dictionary = new PdfStream(b); func.dictionary = new PdfStream(b);
((PdfStream)func.dictionary).FlateCompress(); ((PdfStream)func.dictionary).FlateCompress(writer.CompressionLevel);
func.dictionary.Put(PdfName.FUNCTIONTYPE, new PdfNumber(4)); func.dictionary.Put(PdfName.FUNCTIONTYPE, new PdfNumber(4));
func.dictionary.Put(PdfName.DOMAIN, new PdfArray(domain)); func.dictionary.Put(PdfName.DOMAIN, new PdfArray(domain));
func.dictionary.Put(PdfName.RANGE, new PdfArray(range)); func.dictionary.Put(PdfName.RANGE, new PdfArray(range));

View File

@ -10,7 +10,23 @@ namespace iTextSharp.text.pdf {
public class PdfICCBased : PdfStream { public class PdfICCBased : PdfStream {
public PdfICCBased(ICC_Profile profile) { /**
* Creates an ICC stream.
* @param profile an ICC profile
*/
public PdfICCBased(ICC_Profile profile) : this(profile, DEFAULT_COMPRESSION) {
;
}
/**
* Creates an ICC stream.
*
* @param compressionLevel the compressionLevel
*
* @param profile an ICC profile
* @since 2.1.3 (replacing the constructor without param compressionLevel)
*/
public PdfICCBased(ICC_Profile profile, int compressionLevel) {
int numberOfComponents = profile.NumComponents; int numberOfComponents = profile.NumComponents;
switch (numberOfComponents) { switch (numberOfComponents) {
case 1: case 1:
@ -27,7 +43,7 @@ namespace iTextSharp.text.pdf {
} }
Put(PdfName.N, new PdfNumber(numberOfComponents)); Put(PdfName.N, new PdfNumber(numberOfComponents));
bytes = profile.Data; bytes = profile.Data;
FlateCompress(); FlateCompress(compressionLevel);
} }
} }
} }

View File

@ -161,7 +161,7 @@ namespace iTextSharp.text.pdf {
if (image.Deflated) if (image.Deflated)
Put(PdfName.FILTER, PdfName.FLATEDECODE); Put(PdfName.FILTER, PdfName.FLATEDECODE);
else { else {
FlateCompress(); FlateCompress(image.CompressionLevel);
} }
} }
return; return;
@ -273,6 +273,7 @@ namespace iTextSharp.text.pdf {
protected void ImportAll(PdfImage dup) { protected void ImportAll(PdfImage dup) {
name = dup.name; name = dup.name;
compressed = dup.compressed; compressed = dup.compressed;
compressionLevel = dup.compressionLevel;
streamBytes = dup.streamBytes; streamBytes = dup.streamBytes;
bytes = dup.bytes; bytes = dup.bytes;
hashMap = dup.hashMap; hashMap = dup.hashMap;

View File

@ -3,7 +3,7 @@ using System;
using iTextSharp.text; using iTextSharp.text;
/* /*
* $Id: PdfImportedPage.cs,v 1.4 2008/07/05 09:34:43 psoares33 Exp $ * $Id: PdfImportedPage.cs,v 1.3 2008/05/13 11:25:21 psoares33 Exp $
* *
* *
* Copyright 2001, 2002 Paulo Soares * Copyright 2001, 2002 Paulo Soares
@ -123,10 +123,15 @@ namespace iTextSharp.text.pdf {
} }
} }
internal override PdfStream FormXObject { /**
get { * Gets the stream representing this page.
return readerInstance.GetFormXObject(pageNumber); *
} * @param compressionLevel the compressionLevel
* @return the stream representing this page
* @since 2.1.3 (replacing the method without param compressionLevel)
*/
internal override PdfStream GetFormXObject(int compressionLevel) {
return readerInstance.GetFormXObject(pageNumber, compressionLevel);
} }
public override void SetColorFill(PdfSpotColor sp, float tint) { public override void SetColorFill(PdfSpotColor sp, float tint) {

View File

@ -357,6 +357,12 @@ namespace iTextSharp.text.pdf {
public static readonly PdfName EARLYCHANGE = new PdfName("EarlyChange"); public static readonly PdfName EARLYCHANGE = new PdfName("EarlyChange");
/** A name */ /** A name */
public static readonly PdfName EF = new PdfName("EF"); public static readonly PdfName EF = new PdfName("EF");
/** A name
* @since 2.1.3 */
public static readonly PdfName EFF = new PdfName("EFF");
/** A name
* @since 2.1.3 */
public static readonly PdfName EFOPEN = new PdfName("EFOpen");
/** A name */ /** A name */
public static readonly PdfName EMBEDDEDFILE = new PdfName("EmbeddedFile"); public static readonly PdfName EMBEDDEDFILE = new PdfName("EmbeddedFile");
/** A name */ /** A name */

View File

@ -1,101 +1,100 @@
using System; using System;
/* /*
* Copyright 2005 Paulo Soares * Copyright 2005 Paulo Soares
* *
* The contents of this file are subject to the Mozilla Public License Version 1.1 * The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License. * (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.mozilla.org/MPL/ * You may obtain a copy of the License at http://www.mozilla.org/MPL/
* *
* Software distributed under the License is distributed on an "AS IS" basis, * Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the License. * for the specific language governing rights and limitations under the License.
* *
* The Original Code is 'iText, a free JAVA-PDF library'. * The Original Code is 'iText, a free JAVA-PDF library'.
* *
* The Initial Developer of the Original Code is Bruno Lowagie. Portions created by * The Initial Developer of the Original Code is Bruno Lowagie. Portions created by
* the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie. * the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved. * All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer * Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved. * are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved.
* *
* Contributor(s): all the names of the contributors are added in the source code * Contributor(s): all the names of the contributors are added in the source code
* where applicable. * where applicable.
* *
* Alternatively, the contents of this file may be used under the terms of the * Alternatively, the contents of this file may be used under the terms of the
* LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the * LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the
* provisions of LGPL are applicable instead of those above. If you wish to * provisions of LGPL are applicable instead of those above. If you wish to
* allow use of your version of this file only under the terms of the LGPL * allow use of your version of this file only under the terms of the LGPL
* License and not to allow others to use your version of this file under * License and not to allow others to use your version of this file under
* the MPL, indicate your decision by deleting the provisions above and * the MPL, indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by the LGPL. * replace them with the notice and other provisions required by the LGPL.
* If you do not delete the provisions above, a recipient may use your version * If you do not delete the provisions above, a recipient may use your version
* of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE. * of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE.
* *
* This library is free software; you can redistribute it and/or modify it * This library is free software; you can redistribute it and/or modify it
* under the terms of the MPL as stated above or under the terms of the GNU * under the terms of the MPL as stated above or under the terms of the GNU
* Library General Public License as published by the Free Software Foundation; * Library General Public License as published by the Free Software Foundation;
* either version 2 of the License, or any later version. * either version 2 of the License, or any later version.
* *
* This library is distributed in the hope that it will be useful, but WITHOUT * This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Library general Public License for more * FOR A PARTICULAR PURPOSE. See the GNU Library general Public License for more
* details. * details.
* *
* If you didn't download this code from the following link, you should check if * If you didn't download this code from the following link, you should check if
* you aren't using an obsolete version: * you aren't using an obsolete version:
* http://www.lowagie.com/iText/ * http://www.lowagie.com/iText/
*/ */
namespace iTextSharp.text.pdf { namespace iTextSharp.text.pdf {
/** /**
* Implements the PostScript XObject. * Implements the PostScript XObject.
*/ */
public class PdfPSXObject : PdfTemplate { public class PdfPSXObject : PdfTemplate {
/** Creates a new instance of PdfPSXObject */ /** Creates a new instance of PdfPSXObject */
protected PdfPSXObject() { protected PdfPSXObject() {
} }
/** /**
* Constructs a PSXObject * Constructs a PSXObject
* @param wr * @param wr
*/ */
public PdfPSXObject(PdfWriter wr) : base(wr) { public PdfPSXObject(PdfWriter wr) : base(wr) {
} }
/** /**
* Gets the stream representing this object. * Gets the stream representing this object.
* *
* @return the stream representing this object * @param compressionLevel the compressionLevel
* @return the stream representing this template
* @since 2.1.3 (replacing the method without param compressionLevel)
* @throws IOException * @throws IOException
*/ */
internal override PdfStream GetFormXObject(int compressionLevel) {
internal override PdfStream FormXObject { PdfStream s = new PdfStream(content.ToByteArray());
get { s.Put(PdfName.TYPE, PdfName.XOBJECT);
PdfStream s = new PdfStream(content.ToByteArray()); s.Put(PdfName.SUBTYPE, PdfName.PS);
s.Put(PdfName.TYPE, PdfName.XOBJECT); s.FlateCompress(compressionLevel);
s.Put(PdfName.SUBTYPE, PdfName.PS); return s;
s.FlateCompress(); }
return s;
} /**
} * Gets a duplicate of this <CODE>PdfPSXObject</CODE>. All
* the members are copied by reference but the buffer stays different.
/** * @return a copy of this <CODE>PdfPSXObject</CODE>
* Gets a duplicate of this <CODE>PdfPSXObject</CODE>. All */
* the members are copied by reference but the buffer stays different.
* @return a copy of this <CODE>PdfPSXObject</CODE> public override PdfContentByte Duplicate {
*/ get {
PdfPSXObject tpl = new PdfPSXObject();
public override PdfContentByte Duplicate { tpl.writer = writer;
get { tpl.pdf = pdf;
PdfPSXObject tpl = new PdfPSXObject(); tpl.thisReference = thisReference;
tpl.writer = writer; tpl.pageResources = pageResources;
tpl.pdf = pdf; tpl.separator = separator;
tpl.thisReference = thisReference; return tpl;
tpl.pageResources = pageResources; }
tpl.separator = separator; }
return tpl; }
} }
}
}
}

View File

@ -54,7 +54,20 @@ namespace iTextSharp.text.pdf {
public class PdfPattern : PdfStream { public class PdfPattern : PdfStream {
internal PdfPattern(PdfPatternPainter painter) : base() { /**
* Creates a PdfPattern object.
* @param painter a pattern painter instance
*/
internal PdfPattern(PdfPatternPainter painter) : this(painter, DEFAULT_COMPRESSION) {
}
/**
* Creates a PdfPattern object.
* @param painter a pattern painter instance
* @param compressionLevel the compressionLevel for the stream
* @since 2.1.3
*/
internal PdfPattern(PdfPatternPainter painter, int compressionLevel) : base() {
PdfNumber one = new PdfNumber(1); PdfNumber one = new PdfNumber(1);
PdfArray matrix = painter.Matrix; PdfArray matrix = painter.Matrix;
if ( matrix != null ) { if ( matrix != null ) {
@ -73,7 +86,7 @@ namespace iTextSharp.text.pdf {
Put(PdfName.YSTEP, new PdfNumber(painter.YStep)); Put(PdfName.YSTEP, new PdfNumber(painter.YStep));
bytes = painter.ToPdf(null); bytes = painter.ToPdf(null);
Put(PdfName.LENGTH, new PdfNumber(bytes.Length)); Put(PdfName.LENGTH, new PdfNumber(bytes.Length));
FlateCompress(); FlateCompress(compressionLevel);
} }
} }
} }

View File

@ -110,16 +110,23 @@ namespace iTextSharp.text.pdf {
public void SetPatternMatrix(float a, float b, float c, float d, float e, float f) { public void SetPatternMatrix(float a, float b, float c, float d, float e, float f) {
SetMatrix(a, b, c, d, e, f); SetMatrix(a, b, c, d, e, f);
} }
/** /**
* Gets the stream representing this pattern * Gets the stream representing this pattern
* * @return the stream representing this pattern
* @return the stream representing this pattern */
*/ internal PdfPattern GetPattern() {
return new PdfPattern(this);
internal PdfPattern Pattern { }
get {
return new PdfPattern(this); /**
} * Gets the stream representing this pattern
* @param compressionLevel the compression level of the stream
* @return the stream representing this pattern
* @since 2.1.3
*/
internal PdfPattern GetPattern(int compressionLevel) {
return new PdfPattern(this, compressionLevel);
} }
/** /**

View File

@ -1957,6 +1957,15 @@ namespace iTextSharp.text.pdf {
* @throws IOException on error * @throws IOException on error
*/ */
public void SetPageContent(int pageNum, byte[] content) { public void SetPageContent(int pageNum, byte[] content) {
SetPageContent(pageNum, content, PdfStream.DEFAULT_COMPRESSION);
}
/** Sets the contents of the page.
* @param content the new page content
* @param pageNum the page number. 1 is the first
* @since 2.1.3 (the method already existed without param compressionLevel)
*/
public void SetPageContent(int pageNum, byte[] content, int compressionLevel) {
PdfDictionary page = GetPageN(pageNum); PdfDictionary page = GetPageN(pageNum);
if (page == null) if (page == null)
return; return;
@ -1968,7 +1977,7 @@ namespace iTextSharp.text.pdf {
freeXref = xrefObj.Count - 1; freeXref = xrefObj.Count - 1;
} }
page.Put(PdfName.CONTENTS, new PRIndirectReference(this, freeXref)); page.Put(PdfName.CONTENTS, new PRIndirectReference(this, freeXref));
xrefObj[freeXref] = new PRStream(this, content); xrefObj[freeXref] = new PRStream(this, content, compressionLevel);
} }
/** Get the content from a stream applying the required filters. /** Get the content from a stream applying the required filters.

View File

@ -82,8 +82,8 @@ namespace iTextSharp.text.pdf {
} }
internal PdfImportedPage GetImportedPage(int pageNumber) { internal PdfImportedPage GetImportedPage(int pageNumber) {
if (!reader.IsOpenedWithFullPermissions) if (!reader.IsOpenedWithFullPermissions)
throw new ArgumentException("PdfReader not opened with owner password"); throw new ArgumentException("PdfReader not opened with owner password");
if (pageNumber < 1 || pageNumber > reader.NumberOfPages) if (pageNumber < 1 || pageNumber > reader.NumberOfPages)
throw new ArgumentException("Invalid page number: " + pageNumber); throw new ArgumentException("Invalid page number: " + pageNumber);
PdfImportedPage pageT = (PdfImportedPage)importedPages[pageNumber]; PdfImportedPage pageT = (PdfImportedPage)importedPages[pageNumber];
@ -113,8 +113,14 @@ namespace iTextSharp.text.pdf {
return obj; return obj;
} }
/**
internal PdfStream GetFormXObject(int pageNumber) { * Gets the content stream of a page as a PdfStream object.
* @param pageNumber the page of which you want the stream
* @param compressionLevel the compression level you want to apply to the stream
* @return a PdfStream object
* @since 2.1.3 (the method already existed without param compressionLevel)
*/
internal PdfStream GetFormXObject(int pageNumber, int compressionLevel) {
PdfDictionary page = reader.GetPageNRelease(pageNumber); PdfDictionary page = reader.GetPageNRelease(pageNumber);
PdfObject contents = PdfReader.GetPdfObjectRelease(page.Get(PdfName.CONTENTS)); PdfObject contents = PdfReader.GetPdfObjectRelease(page.Get(PdfName.CONTENTS));
PdfDictionary dic = new PdfDictionary(); PdfDictionary dic = new PdfDictionary();
@ -167,7 +173,7 @@ namespace iTextSharp.text.pdf {
try { try {
file.ReOpen(); file.ReOpen();
foreach (PdfImportedPage ip in importedPages.Values) { foreach (PdfImportedPage ip in importedPages.Values) {
writer.AddToBody(ip.FormXObject, ip.IndirectReference); writer.AddToBody(ip.GetFormXObject(writer.CompressionLevel), ip.IndirectReference);
} }
WriteAllVisited(); WriteAllVisited();
} }

View File

@ -376,7 +376,7 @@ namespace iTextSharp.text.pdf {
if (ps.over != null) if (ps.over != null)
out_p.Append(PdfContents.SAVESTATE); out_p.Append(PdfContents.SAVESTATE);
PdfStream stream = new PdfStream(out_p.ToByteArray()); PdfStream stream = new PdfStream(out_p.ToByteArray());
stream.FlateCompress(); stream.FlateCompress(compressionLevel);
ar.AddFirst(AddToBody(stream).IndirectReference); ar.AddFirst(AddToBody(stream).IndirectReference);
out_p.Reset(); out_p.Reset();
if (ps.over != null) { if (ps.over != null) {
@ -389,7 +389,7 @@ namespace iTextSharp.text.pdf {
out_p.Append(buf.Buffer, ps.replacePoint, buf.Size - ps.replacePoint); out_p.Append(buf.Buffer, ps.replacePoint, buf.Size - ps.replacePoint);
out_p.Append(PdfContents.RESTORESTATE); out_p.Append(PdfContents.RESTORESTATE);
stream = new PdfStream(out_p.ToByteArray()); stream = new PdfStream(out_p.ToByteArray());
stream.FlateCompress(); stream.FlateCompress(compressionLevel);
ar.Add(AddToBody(stream).IndirectReference); ar.Add(AddToBody(stream).IndirectReference);
} }
AlterResources(ps); AlterResources(ps);

View File

@ -80,8 +80,35 @@ namespace iTextSharp.text.pdf {
// membervariables // membervariables
/**
* A possible compression level.
* @since 2.1.3
*/
public const int DEFAULT_COMPRESSION = -1;
/**
* A possible compression level.
* @since 2.1.3
*/
public const int NO_COMPRESSION = 0;
/**
* A possible compression level.
* @since 2.1.3
*/
public const int BEST_SPEED = 1;
/**
* A possible compression level.
* @since 2.1.3
*/
public const int BEST_COMPRESSION = 9;
/** is the stream compressed? */ /** is the stream compressed? */
protected bool compressed = false; protected bool compressed = false;
/**
* The level of compression.
* @since 2.1.3
*/
protected int compressionLevel = NO_COMPRESSION;
protected MemoryStream streamBytes = null; protected MemoryStream streamBytes = null;
@ -168,18 +195,25 @@ namespace iTextSharp.text.pdf {
// methods // methods
/** /**
* Compresses the stream. * Compresses the stream.
* */
* @throws PdfException if a filter is allready defined
*/
public void FlateCompress() { public void FlateCompress() {
FlateCompress(DEFAULT_COMPRESSION);
}
/**
* Compresses the stream.
* @param compressionLevel the compression level (0 = best speed, 9 = best compression, -1 is default)
* @since 2.1.3
*/
public void FlateCompress(int compressionLevel) {
if (!Document.Compress) if (!Document.Compress)
return; return;
// check if the flateCompress-method has allready been // check if the flateCompress-method has allready been
if (compressed) { if (compressed) {
return; return;
} }
this.compressionLevel = compressionLevel;
if (inputStream != null) { if (inputStream != null) {
compressed = true; compressed = true;
return; return;
@ -201,7 +235,7 @@ namespace iTextSharp.text.pdf {
} }
// compress // compress
MemoryStream stream = new MemoryStream(); MemoryStream stream = new MemoryStream();
ZDeflaterOutputStream zip = new ZDeflaterOutputStream(stream); ZDeflaterOutputStream zip = new ZDeflaterOutputStream(stream, compressionLevel);
if (streamBytes != null) if (streamBytes != null)
streamBytes.WriteTo(zip); streamBytes.WriteTo(zip);
else else
@ -261,10 +295,10 @@ namespace iTextSharp.text.pdf {
OutputStreamCounter osc = new OutputStreamCounter(os); OutputStreamCounter osc = new OutputStreamCounter(os);
OutputStreamEncryption ose = null; OutputStreamEncryption ose = null;
Stream fout = osc; Stream fout = osc;
if (crypto != null) if (crypto != null && !crypto.IsEmbeddedFilesOnly())
fout = ose = crypto.GetEncryptionStream(fout); fout = ose = crypto.GetEncryptionStream(fout);
if (compressed) if (compressed)
fout = def = new ZDeflaterOutputStream(fout); fout = def = new ZDeflaterOutputStream(fout, compressionLevel);
byte[] buf = new byte[4192]; byte[] buf = new byte[4192];
while (true) { while (true) {
@ -281,13 +315,7 @@ namespace iTextSharp.text.pdf {
inputStreamLength = osc.Counter; inputStreamLength = osc.Counter;
} }
else { else {
if (crypto == null) { if (crypto != null && !crypto.IsEmbeddedFilesOnly()) {
if (streamBytes != null)
streamBytes.WriteTo(os);
else
os.Write(bytes, 0, bytes.Length);
}
else {
byte[] b; byte[] b;
if (streamBytes != null) { if (streamBytes != null) {
b = crypto.EncryptByteArray(streamBytes.ToArray()); b = crypto.EncryptByteArray(streamBytes.ToArray());
@ -297,6 +325,12 @@ namespace iTextSharp.text.pdf {
} }
os.Write(b, 0, b.Length); os.Write(b, 0, b.Length);
} }
else {
if (streamBytes != null)
streamBytes.WriteTo(os);
else
os.Write(bytes, 0, bytes.Length);
}
} }
os.Write(ENDSTREAM, 0, ENDSTREAM.Length); os.Write(ENDSTREAM, 0, ENDSTREAM.Length);
} }

View File

@ -224,13 +224,12 @@ namespace iTextSharp.text.pdf {
/** /**
* Gets the stream representing this template. * Gets the stream representing this template.
* *
* @param compressionLevel the compressionLevel
* @return the stream representing this template * @return the stream representing this template
* @since 2.1.3 (replacing the method without param compressionLevel)
*/ */
internal virtual PdfStream GetFormXObject(int compressionLevel) {
internal virtual PdfStream FormXObject { return new PdfFormXObject(this, compressionLevel);
get {
return new PdfFormXObject(this);
}
} }
/** /**

View File

@ -277,7 +277,7 @@ namespace iTextSharp.text.pdf {
int first = index.Size; int first = index.Size;
index.Append(streamObjects); index.Append(streamObjects);
PdfStream stream = new PdfStream(index.ToByteArray()); PdfStream stream = new PdfStream(index.ToByteArray());
stream.FlateCompress(); stream.FlateCompress(writer.CompressionLevel);
stream.Put(PdfName.TYPE, PdfName.OBJSTM); stream.Put(PdfName.TYPE, PdfName.OBJSTM);
stream.Put(PdfName.N, new PdfNumber(numObj)); stream.Put(PdfName.N, new PdfNumber(numObj));
stream.Put(PdfName.FIRST, new PdfNumber(first)); stream.Put(PdfName.FIRST, new PdfNumber(first));
@ -452,7 +452,7 @@ namespace iTextSharp.text.pdf {
} }
PdfStream xr = new PdfStream(buf.ToByteArray()); PdfStream xr = new PdfStream(buf.ToByteArray());
buf = null; buf = null;
xr.FlateCompress(); xr.FlateCompress(writer.CompressionLevel);
xr.Put(PdfName.SIZE, new PdfNumber(Size)); xr.Put(PdfName.SIZE, new PdfNumber(Size));
xr.Put(PdfName.ROOT, root); xr.Put(PdfName.ROOT, root);
if (info != null) { if (info != null) {
@ -1182,7 +1182,7 @@ namespace iTextSharp.text.pdf {
if (template != null && template.IndirectReference is PRIndirectReference) if (template != null && template.IndirectReference is PRIndirectReference)
continue; continue;
if (template != null && template.Type == PdfTemplate.TYPE_TEMPLATE) { if (template != null && template.Type == PdfTemplate.TYPE_TEMPLATE) {
AddToBody(template.FormXObject, template.IndirectReference); AddToBody(template.GetFormXObject(compressionLevel), template.IndirectReference);
} }
} }
// add all the dependencies in the imported pages // add all the dependencies in the imported pages
@ -1197,7 +1197,7 @@ namespace iTextSharp.text.pdf {
} }
// add the pattern // add the pattern
foreach (PdfPatternPainter pat in documentPatterns.Keys) { foreach (PdfPatternPainter pat in documentPatterns.Keys) {
AddToBody(pat.Pattern, pat.IndirectReference); AddToBody(pat.GetPattern(compressionLevel), pat.IndirectReference);
} }
// add the shading patterns // add the shading patterns
foreach (PdfShadingPattern shadingPattern in documentShadingPatterns.Keys) { foreach (PdfShadingPattern shadingPattern in documentShadingPatterns.Keys) {
@ -1746,7 +1746,7 @@ namespace iTextSharp.text.pdf {
outa.Put(PdfName.INFO, new PdfString(info, PdfObject.TEXT_UNICODE)); outa.Put(PdfName.INFO, new PdfString(info, PdfObject.TEXT_UNICODE));
if (destOutputProfile != null) { if (destOutputProfile != null) {
PdfStream stream = new PdfStream(destOutputProfile); PdfStream stream = new PdfStream(destOutputProfile);
stream.FlateCompress(); stream.FlateCompress(compressionLevel);
outa.Put(PdfName.DESTOUTPUTPROFILE, AddToBody(stream).IndirectReference); outa.Put(PdfName.DESTOUTPUTPROFILE, AddToBody(stream).IndirectReference);
} }
outa.Put(PdfName.S, PdfName.GTS_PDFX); outa.Put(PdfName.S, PdfName.GTS_PDFX);
@ -1809,6 +1809,11 @@ namespace iTextSharp.text.pdf {
internal const int ENCRYPTION_MASK = 7; internal const int ENCRYPTION_MASK = 7;
/** Add this to the mode to keep the metadata in clear text */ /** Add this to the mode to keep the metadata in clear text */
public const int DO_NOT_ENCRYPT_METADATA = 8; public const int DO_NOT_ENCRYPT_METADATA = 8;
/**
* Add this to the mode to keep encrypt only the embedded files.
* @since 2.1.3
*/
public const int EMBEDDED_FILES_ONLY = 24;
// permissions // permissions
@ -2018,6 +2023,29 @@ namespace iTextSharp.text.pdf {
SetAtLeastPdfVersion(VERSION_1_5); SetAtLeastPdfVersion(VERSION_1_5);
} }
/**
* The compression level of the content streams.
* @since 2.1.3
*/
protected internal int compressionLevel = PdfStream.DEFAULT_COMPRESSION;
/**
* Sets the compression level to be used for streams written by this writer.
* @param compressionLevel a value between 0 (best speed) and 9 (best compression)
* @since 2.1.3
*/
public int CompressionLevel {
set {
if (compressionLevel < PdfStream.NO_COMPRESSION || compressionLevel > PdfStream.BEST_COMPRESSION)
compressionLevel = PdfStream.DEFAULT_COMPRESSION;
else
compressionLevel = value;
}
get {
return compressionLevel;
}
}
// [F3] adding fonts // [F3] adding fonts
/** The fonts of this document */ /** The fonts of this document */
@ -2111,7 +2139,7 @@ namespace iTextSharp.text.pdf {
if (template.IndirectReference is PRIndirectReference) if (template.IndirectReference is PRIndirectReference)
return; return;
if (template.Type == PdfTemplate.TYPE_TEMPLATE) { if (template.Type == PdfTemplate.TYPE_TEMPLATE) {
AddToBody(template.FormXObject, template.IndirectReference); AddToBody(template.GetFormXObject(compressionLevel), template.IndirectReference);
objs[1] = null; objs[1] = null;
} }
} }
@ -2841,7 +2869,7 @@ namespace iTextSharp.text.pdf {
} }
PdfImage i = new PdfImage(image, "img" + images.Count, maskRef); PdfImage i = new PdfImage(image, "img" + images.Count, maskRef);
if (image.HasICCProfile()) { if (image.HasICCProfile()) {
PdfICCBased icc = new PdfICCBased(image.TagICC); PdfICCBased icc = new PdfICCBased(image.TagICC, image.CompressionLevel);
PdfIndirectReference iccRef = Add(icc); PdfIndirectReference iccRef = Add(icc);
PdfArray iccArray = new PdfArray(); PdfArray iccArray = new PdfArray();
iccArray.Add(PdfName.ICCBASED); iccArray.Add(PdfName.ICCBASED);

View File

@ -6,7 +6,7 @@ using System.Collections;
using iTextSharp.text; using iTextSharp.text;
/* /*
* $Id: TrueTypeFont.cs,v 1.13 2008/06/01 13:17:07 psoares33 Exp $ * $Id: TrueTypeFont.cs,v 1.12 2008/05/13 11:25:23 psoares33 Exp $
* *
* *
* Copyright 2001, 2002 Paulo Soares * Copyright 2001, 2002 Paulo Soares
@ -1258,7 +1258,7 @@ namespace iTextSharp.text.pdf {
string subsetPrefix = ""; string subsetPrefix = "";
if (embedded) { if (embedded) {
if (cff) { if (cff) {
pobj = new StreamFont(ReadCffFont(), "Type1C"); pobj = new StreamFont(ReadCffFont(), "Type1C", compressionLevel);
obj = writer.AddToBody(pobj); obj = writer.AddToBody(pobj);
ind_font = obj.IndirectReference; ind_font = obj.IndirectReference;
} }
@ -1294,7 +1294,7 @@ namespace iTextSharp.text.pdf {
b = GetFullFont(); b = GetFullFont();
} }
int[] lengths = new int[]{b.Length}; int[] lengths = new int[]{b.Length};
pobj = new StreamFont(b, lengths); pobj = new StreamFont(b, lengths, compressionLevel);
obj = writer.AddToBody(pobj); obj = writer.AddToBody(pobj);
ind_font = obj.IndirectReference; ind_font = obj.IndirectReference;
} }
@ -1341,12 +1341,12 @@ namespace iTextSharp.text.pdf {
*/ */
public override PdfStream GetFullFontStream() { public override PdfStream GetFullFontStream() {
if (cff) { if (cff) {
return new StreamFont(ReadCffFont(), "Type1C"); return new StreamFont(ReadCffFont(), "Type1C", compressionLevel);
} }
else { else {
byte[] b = GetFullFont(); byte[] b = GetFullFont();
int[] lengths = new int[]{b.Length}; int[] lengths = new int[]{b.Length};
return new StreamFont(b, lengths); return new StreamFont(b, lengths, compressionLevel);
} }
} }

View File

@ -4,7 +4,7 @@ using System.Text;
using System.Collections; using System.Collections;
/* /*
* $Id: TrueTypeFontUnicode.cs,v 1.13 2008/06/01 13:17:07 psoares33 Exp $ * $Id: TrueTypeFontUnicode.cs,v 1.12 2008/05/13 11:25:23 psoares33 Exp $
* *
* *
* Copyright 2001, 2002 Paulo Soares * Copyright 2001, 2002 Paulo Soares
@ -207,7 +207,7 @@ namespace iTextSharp.text.pdf {
"end end\n"); "end end\n");
string s = buf.ToString(); string s = buf.ToString();
PdfStream stream = new PdfStream(PdfEncodings.ConvertToBytes(s, null)); PdfStream stream = new PdfStream(PdfEncodings.ConvertToBytes(s, null));
stream.FlateCompress(); stream.FlateCompress(compressionLevel);
return stream; return stream;
} }
@ -351,7 +351,7 @@ namespace iTextSharp.text.pdf {
bt[v / 8] |= rotbits[v % 8]; bt[v / 8] |= rotbits[v % 8];
} }
stream = new PdfStream(bt); stream = new PdfStream(bt);
stream.FlateCompress(); stream.FlateCompress(compressionLevel);
} }
cidset = writer.AddToBody(stream).IndirectReference; cidset = writer.AddToBody(stream).IndirectReference;
} }
@ -363,7 +363,7 @@ namespace iTextSharp.text.pdf {
b = cffs.Process((cffs.GetNames())[0] ); b = cffs.Process((cffs.GetNames())[0] );
} }
pobj = new StreamFont(b, "CIDFontType0C"); pobj = new StreamFont(b, "CIDFontType0C", compressionLevel);
obj = writer.AddToBody(pobj); obj = writer.AddToBody(pobj);
ind_font = obj.IndirectReference; ind_font = obj.IndirectReference;
} else { } else {
@ -376,7 +376,7 @@ namespace iTextSharp.text.pdf {
b = GetFullFont(); b = GetFullFont();
} }
int[] lengths = new int[]{b.Length}; int[] lengths = new int[]{b.Length};
pobj = new StreamFont(b, lengths); pobj = new StreamFont(b, lengths, compressionLevel);
obj = writer.AddToBody(pobj); obj = writer.AddToBody(pobj);
ind_font = obj.IndirectReference; ind_font = obj.IndirectReference;
} }
@ -409,7 +409,7 @@ namespace iTextSharp.text.pdf {
*/ */
public override PdfStream GetFullFontStream() { public override PdfStream GetFullFontStream() {
if (cff) { if (cff) {
return new StreamFont(ReadCffFont(), "CIDFontType0C"); return new StreamFont(ReadCffFont(), "CIDFontType0C", compressionLevel);
} }
return base.GetFullFontStream(); return base.GetFullFontStream();
} }

View File

@ -4,7 +4,7 @@ using System.Collections;
using System.util; using System.util;
/* /*
* $Id: Type1Font.cs,v 1.14 2008/06/01 13:17:07 psoares33 Exp $ * $Id: Type1Font.cs,v 1.13 2008/05/13 11:25:23 psoares33 Exp $
* *
* *
* Copyright 2001, 2002 Paulo Soares * Copyright 2001, 2002 Paulo Soares
@ -503,7 +503,7 @@ namespace iTextSharp.text.pdf {
size -= got; size -= got;
} }
} }
return new StreamFont(st, lengths); return new StreamFont(st, lengths, compressionLevel);
} }
finally { finally {
if (rf != null) { if (rf != null) {

View File

@ -1,178 +1,178 @@
using System; using System;
using System.Collections; using System.Collections;
/* /*
* Copyright 2005 by Paulo Soares. * Copyright 2005 by Paulo Soares.
* *
* The contents of this file are subject to the Mozilla Public License Version 1.1 * The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License. * (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.mozilla.org/MPL/ * You may obtain a copy of the License at http://www.mozilla.org/MPL/
* *
* Software distributed under the License is distributed on an "AS IS" basis, * Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the License. * for the specific language governing rights and limitations under the License.
* *
* The Original Code is 'iText, a free JAVA-PDF library'. * The Original Code is 'iText, a free JAVA-PDF library'.
* *
* The Initial Developer of the Original Code is Bruno Lowagie. Portions created by * The Initial Developer of the Original Code is Bruno Lowagie. Portions created by
* the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie. * the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved. * All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer * Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved. * are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved.
* *
* Contributor(s): all the names of the contributors are added in the source code * Contributor(s): all the names of the contributors are added in the source code
* where applicable. * where applicable.
* *
* Alternatively, the contents of this file may be used under the terms of the * Alternatively, the contents of this file may be used under the terms of the
* LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the * LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the
* provisions of LGPL are applicable instead of those above. If you wish to * provisions of LGPL are applicable instead of those above. If you wish to
* allow use of your version of this file only under the terms of the LGPL * allow use of your version of this file only under the terms of the LGPL
* License and not to allow others to use your version of this file under * License and not to allow others to use your version of this file under
* the MPL, indicate your decision by deleting the provisions above and * the MPL, indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by the LGPL. * replace them with the notice and other provisions required by the LGPL.
* If you do not delete the provisions above, a recipient may use your version * If you do not delete the provisions above, a recipient may use your version
* of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE. * of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE.
* *
* This library is free software; you can redistribute it and/or modify it * This library is free software; you can redistribute it and/or modify it
* under the terms of the MPL as stated above or under the terms of the GNU * under the terms of the MPL as stated above or under the terms of the GNU
* Library General Public License as published by the Free Software Foundation; * Library General Public License as published by the Free Software Foundation;
* either version 2 of the License, or any later version. * either version 2 of the License, or any later version.
* *
* This library is distributed in the hope that it will be useful, but WITHOUT * This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Library general Public License for more * FOR A PARTICULAR PURPOSE. See the GNU Library general Public License for more
* details. * details.
* *
* If you didn't download this code from the following link, you should check if * If you didn't download this code from the following link, you should check if
* you aren't using an obsolete version: * you aren't using an obsolete version:
* http://www.lowagie.com/iText/ * http://www.lowagie.com/iText/
*/ */
namespace iTextSharp.text.pdf { namespace iTextSharp.text.pdf {
/** /**
* A class to support Type3 fonts. * A class to support Type3 fonts.
*/ */
public class Type3Font : BaseFont { public class Type3Font : BaseFont {
private bool[] usedSlot; private bool[] usedSlot;
private IntHashtable widths3 = new IntHashtable(); private IntHashtable widths3 = new IntHashtable();
private Hashtable char2glyph = new Hashtable(); private Hashtable char2glyph = new Hashtable();
private PdfWriter writer; private PdfWriter writer;
private float llx = float.NaN, lly, urx, ury; private float llx = float.NaN, lly, urx, ury;
private PageResources pageResources = new PageResources(); private PageResources pageResources = new PageResources();
private bool colorized; private bool colorized;
/** /**
* Creates a Type3 font. * Creates a Type3 font.
* @param writer the writer * @param writer the writer
* @param chars an array of chars corresponding to the glyphs used (not used, prisent for compability only) * @param chars an array of chars corresponding to the glyphs used (not used, prisent for compability only)
* @param colorized if <CODE>true</CODE> the font may specify color, if <CODE>false</CODE> no color commands are allowed * @param colorized if <CODE>true</CODE> the font may specify color, if <CODE>false</CODE> no color commands are allowed
* and only images as masks can be used * and only images as masks can be used
*/ */
public Type3Font(PdfWriter writer, char[] chars, bool colorized) : this(writer, colorized) { public Type3Font(PdfWriter writer, char[] chars, bool colorized) : this(writer, colorized) {
} }
/** /**
* Creates a Type3 font. This implementation assumes that the /FontMatrix is * Creates a Type3 font. This implementation assumes that the /FontMatrix is
* [0.001 0 0 0.001 0 0] or a 1000-unit glyph coordinate system. * [0.001 0 0 0.001 0 0] or a 1000-unit glyph coordinate system.
* <p> * <p>
* An example: * An example:
* <p> * <p>
* <pre> * <pre>
* Document document = new Document(PageSize.A4); * Document document = new Document(PageSize.A4);
* PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("type3.pdf")); * PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("type3.pdf"));
* document.open(); * document.open();
* Type3Font t3 = new Type3Font(writer, false); * Type3Font t3 = new Type3Font(writer, false);
* PdfContentByte g = t3.defineGlyph('a', 1000, 0, 0, 750, 750); * PdfContentByte g = t3.defineGlyph('a', 1000, 0, 0, 750, 750);
* g.rectangle(0, 0, 750, 750); * g.rectangle(0, 0, 750, 750);
* g.fill(); * g.fill();
* g = t3.defineGlyph('b', 1000, 0, 0, 750, 750); * g = t3.defineGlyph('b', 1000, 0, 0, 750, 750);
* g.moveTo(0, 0); * g.moveTo(0, 0);
* g.lineTo(375, 750); * g.lineTo(375, 750);
* g.lineTo(750, 0); * g.lineTo(750, 0);
* g.fill(); * g.fill();
* Font f = new Font(t3, 12); * Font f = new Font(t3, 12);
* document.add(new Paragraph("ababab", f)); * document.add(new Paragraph("ababab", f));
* document.close(); * document.close();
* </pre> * </pre>
* @param writer the writer * @param writer the writer
* @param colorized if <CODE>true</CODE> the font may specify color, if <CODE>false</CODE> no color commands are allowed * @param colorized if <CODE>true</CODE> the font may specify color, if <CODE>false</CODE> no color commands are allowed
* and only images as masks can be used * and only images as masks can be used
*/ */
public Type3Font(PdfWriter writer, bool colorized) { public Type3Font(PdfWriter writer, bool colorized) {
this.writer = writer; this.writer = writer;
this.colorized = colorized; this.colorized = colorized;
fontType = FONT_TYPE_T3; fontType = FONT_TYPE_T3;
usedSlot = new bool[256]; usedSlot = new bool[256];
} }
/** /**
* Defines a glyph. If the character was already defined it will return the same content * Defines a glyph. If the character was already defined it will return the same content
* @param c the character to match this glyph. * @param c the character to match this glyph.
* @param wx the advance this character will have * @param wx the advance this character will have
* @param llx the X lower left corner of the glyph bounding box. If the <CODE>colorize</CODE> option is * @param llx the X lower left corner of the glyph bounding box. If the <CODE>colorize</CODE> option is
* <CODE>true</CODE> the value is ignored * <CODE>true</CODE> the value is ignored
* @param lly the Y lower left corner of the glyph bounding box. If the <CODE>colorize</CODE> option is * @param lly the Y lower left corner of the glyph bounding box. If the <CODE>colorize</CODE> option is
* <CODE>true</CODE> the value is ignored * <CODE>true</CODE> the value is ignored
* @param urx the X upper right corner of the glyph bounding box. If the <CODE>colorize</CODE> option is * @param urx the X upper right corner of the glyph bounding box. If the <CODE>colorize</CODE> option is
* <CODE>true</CODE> the value is ignored * <CODE>true</CODE> the value is ignored
* @param ury the Y upper right corner of the glyph bounding box. If the <CODE>colorize</CODE> option is * @param ury the Y upper right corner of the glyph bounding box. If the <CODE>colorize</CODE> option is
* <CODE>true</CODE> the value is ignored * <CODE>true</CODE> the value is ignored
* @return a content where the glyph can be defined * @return a content where the glyph can be defined
*/ */
public PdfContentByte DefineGlyph(char c, float wx, float llx, float lly, float urx, float ury) { public PdfContentByte DefineGlyph(char c, float wx, float llx, float lly, float urx, float ury) {
if (c == 0 || c > 255) if (c == 0 || c > 255)
throw new ArgumentException("The char " + (int)c + " doesn't belong in this Type3 font"); throw new ArgumentException("The char " + (int)c + " doesn't belong in this Type3 font");
usedSlot[c] = true; usedSlot[c] = true;
Type3Glyph glyph = (Type3Glyph)char2glyph[c]; Type3Glyph glyph = (Type3Glyph)char2glyph[c];
if (glyph != null) if (glyph != null)
return glyph; return glyph;
widths3[c] = (int)wx; widths3[c] = (int)wx;
if (!colorized) { if (!colorized) {
if (float.IsNaN(this.llx)) { if (float.IsNaN(this.llx)) {
this.llx = llx; this.llx = llx;
this.lly = lly; this.lly = lly;
this.urx = urx; this.urx = urx;
this.ury = ury; this.ury = ury;
} }
else { else {
this.llx = Math.Min(this.llx, llx); this.llx = Math.Min(this.llx, llx);
this.lly = Math.Min(this.lly, lly); this.lly = Math.Min(this.lly, lly);
this.urx = Math.Max(this.urx, urx); this.urx = Math.Max(this.urx, urx);
this.ury = Math.Max(this.ury, ury); this.ury = Math.Max(this.ury, ury);
} }
} }
glyph = new Type3Glyph(writer, pageResources, wx, llx, lly, urx, ury, colorized); glyph = new Type3Glyph(writer, pageResources, wx, llx, lly, urx, ury, colorized);
char2glyph[c] = glyph; char2glyph[c] = glyph;
return glyph; return glyph;
} }
public override String[][] FamilyFontName { public override String[][] FamilyFontName {
get { get {
return FullFontName; return FullFontName;
} }
} }
public override float GetFontDescriptor(int key, float fontSize) { public override float GetFontDescriptor(int key, float fontSize) {
return 0; return 0;
} }
public override String[][] FullFontName { public override String[][] FullFontName {
get { get {
return new string[][]{new string[]{"", "", "", ""}}; return new string[][]{new string[]{"", "", "", ""}};
} }
} }
public override string[][] AllNameEntries { public override string[][] AllNameEntries {
get { get {
return new string[][]{new string[]{"4", "", "", "", ""}}; return new string[][]{new string[]{"4", "", "", "", ""}};
} }
} }
public override int GetKerning(int char1, int char2) { public override int GetKerning(int char1, int char2) {
return 0; return 0;
} }
public override string PostscriptFontName { public override string PostscriptFontName {
get { get {
return ""; return "";
@ -180,87 +180,87 @@ namespace iTextSharp.text.pdf {
set { set {
} }
} }
protected override int[] GetRawCharBBox(int c, String name) { protected override int[] GetRawCharBBox(int c, String name) {
return null; return null;
} }
internal override int GetRawWidth(int c, String name) { internal override int GetRawWidth(int c, String name) {
return 0; return 0;
} }
public override bool HasKernPairs() { public override bool HasKernPairs() {
return false; return false;
} }
public override bool SetKerning(int char1, int char2, int kern) { public override bool SetKerning(int char1, int char2, int kern) {
return false; return false;
} }
internal override void WriteFont(PdfWriter writer, PdfIndirectReference piRef, Object[] oParams) { internal override void WriteFont(PdfWriter writer, PdfIndirectReference piRef, Object[] oParams) {
if (this.writer != writer) if (this.writer != writer)
throw new ArgumentException("Type3 font used with the wrong PdfWriter"); throw new ArgumentException("Type3 font used with the wrong PdfWriter");
// Get first & lastchar ... // Get first & lastchar ...
int firstChar = 0; int firstChar = 0;
while( firstChar < usedSlot.Length && !usedSlot[firstChar] ) firstChar++; while( firstChar < usedSlot.Length && !usedSlot[firstChar] ) firstChar++;
if ( firstChar == usedSlot.Length ) { if ( firstChar == usedSlot.Length ) {
throw new DocumentException( "No glyphs defined for Type3 font" ); throw new DocumentException( "No glyphs defined for Type3 font" );
} }
int lastChar = usedSlot.Length - 1; int lastChar = usedSlot.Length - 1;
while( lastChar >= firstChar && !usedSlot[lastChar] ) lastChar--; while( lastChar >= firstChar && !usedSlot[lastChar] ) lastChar--;
int[] widths = new int[lastChar - firstChar + 1]; int[] widths = new int[lastChar - firstChar + 1];
int[] invOrd = new int[lastChar - firstChar + 1]; int[] invOrd = new int[lastChar - firstChar + 1];
int invOrdIndx = 0, w = 0; int invOrdIndx = 0, w = 0;
for( int u = firstChar; u<=lastChar; u++, w++ ) { for( int u = firstChar; u<=lastChar; u++, w++ ) {
if ( usedSlot[u] ) { if ( usedSlot[u] ) {
invOrd[invOrdIndx++] = u; invOrd[invOrdIndx++] = u;
widths[w] = widths3[u]; widths[w] = widths3[u];
} }
} }
PdfArray diffs = new PdfArray(); PdfArray diffs = new PdfArray();
PdfDictionary charprocs = new PdfDictionary(); PdfDictionary charprocs = new PdfDictionary();
int last = -1; int last = -1;
for (int k = 0; k < invOrdIndx; ++k) { for (int k = 0; k < invOrdIndx; ++k) {
int c = invOrd[k]; int c = invOrd[k];
if (c > last) { if (c > last) {
last = c; last = c;
diffs.Add(new PdfNumber(last)); diffs.Add(new PdfNumber(last));
} }
++last; ++last;
int c2 = invOrd[k]; int c2 = invOrd[k];
String s = GlyphList.UnicodeToName(c2); String s = GlyphList.UnicodeToName(c2);
if (s == null) if (s == null)
s = "a" + c2; s = "a" + c2;
PdfName n = new PdfName(s); PdfName n = new PdfName(s);
diffs.Add(n); diffs.Add(n);
Type3Glyph glyph = (Type3Glyph)char2glyph[(char)c2]; Type3Glyph glyph = (Type3Glyph)char2glyph[(char)c2];
PdfStream stream = new PdfStream(glyph.ToPdf(null)); PdfStream stream = new PdfStream(glyph.ToPdf(null));
stream.FlateCompress(); stream.FlateCompress(compressionLevel);
PdfIndirectReference refp = writer.AddToBody(stream).IndirectReference; PdfIndirectReference refp = writer.AddToBody(stream).IndirectReference;
charprocs.Put(n, refp); charprocs.Put(n, refp);
} }
PdfDictionary font = new PdfDictionary(PdfName.FONT); PdfDictionary font = new PdfDictionary(PdfName.FONT);
font.Put(PdfName.SUBTYPE, PdfName.TYPE3); font.Put(PdfName.SUBTYPE, PdfName.TYPE3);
if (colorized) if (colorized)
font.Put(PdfName.FONTBBOX, new PdfRectangle(0, 0, 0, 0)); font.Put(PdfName.FONTBBOX, new PdfRectangle(0, 0, 0, 0));
else else
font.Put(PdfName.FONTBBOX, new PdfRectangle(llx, lly, urx, ury)); font.Put(PdfName.FONTBBOX, new PdfRectangle(llx, lly, urx, ury));
font.Put(PdfName.FONTMATRIX, new PdfArray(new float[]{0.001f, 0, 0, 0.001f, 0, 0})); font.Put(PdfName.FONTMATRIX, new PdfArray(new float[]{0.001f, 0, 0, 0.001f, 0, 0}));
font.Put(PdfName.CHARPROCS, writer.AddToBody(charprocs).IndirectReference); font.Put(PdfName.CHARPROCS, writer.AddToBody(charprocs).IndirectReference);
PdfDictionary encoding = new PdfDictionary(); PdfDictionary encoding = new PdfDictionary();
encoding.Put(PdfName.DIFFERENCES, diffs); encoding.Put(PdfName.DIFFERENCES, diffs);
font.Put(PdfName.ENCODING, writer.AddToBody(encoding).IndirectReference); font.Put(PdfName.ENCODING, writer.AddToBody(encoding).IndirectReference);
font.Put(PdfName.FIRSTCHAR, new PdfNumber(firstChar)); font.Put(PdfName.FIRSTCHAR, new PdfNumber(firstChar));
font.Put(PdfName.LASTCHAR, new PdfNumber(lastChar)); font.Put(PdfName.LASTCHAR, new PdfNumber(lastChar));
font.Put(PdfName.WIDTHS, writer.AddToBody(new PdfArray(widths)).IndirectReference); font.Put(PdfName.WIDTHS, writer.AddToBody(new PdfArray(widths)).IndirectReference);
if (pageResources.HasResources()) if (pageResources.HasResources())
font.Put(PdfName.RESOURCES, writer.AddToBody(pageResources.Resources).IndirectReference); font.Put(PdfName.RESOURCES, writer.AddToBody(pageResources.Resources).IndirectReference);
writer.AddToBody(font, piRef); writer.AddToBody(font, piRef);
} }
/** /**
* Always returns null, because you can't get the FontStream of a Type3 font. * Always returns null, because you can't get the FontStream of a Type3 font.
* @return null * @return null
@ -269,58 +269,58 @@ namespace iTextSharp.text.pdf {
public override PdfStream GetFullFontStream() { public override PdfStream GetFullFontStream() {
return null; return null;
} }
internal override byte[] ConvertToBytes(String text) { internal override byte[] ConvertToBytes(String text) {
char[] cc = text.ToCharArray(); char[] cc = text.ToCharArray();
byte[] b = new byte[cc.Length]; byte[] b = new byte[cc.Length];
int p = 0; int p = 0;
for (int k = 0; k < cc.Length; ++k) { for (int k = 0; k < cc.Length; ++k) {
char c = cc[k]; char c = cc[k];
if (CharExists(c)) if (CharExists(c))
b[p++] = (byte)c; b[p++] = (byte)c;
} }
if (b.Length == p) if (b.Length == p)
return b; return b;
byte[] b2 = new byte[p]; byte[] b2 = new byte[p];
Array.Copy(b, 0, b2, 0, p); Array.Copy(b, 0, b2, 0, p);
return b2; return b2;
} }
internal override byte[] ConvertToBytes(int char1) { internal override byte[] ConvertToBytes(int char1) {
if (CharExists(char1)) if (CharExists(char1))
return new byte[]{(byte)char1}; return new byte[]{(byte)char1};
else return new byte[0]; else return new byte[0];
} }
public override int GetWidth(int char1) { public override int GetWidth(int char1) {
if (!widths3.ContainsKey(char1)) if (!widths3.ContainsKey(char1))
throw new ArgumentException("The char " + (int)char1 + " is not defined in a Type3 font"); throw new ArgumentException("The char " + (int)char1 + " is not defined in a Type3 font");
return widths3[char1]; return widths3[char1];
} }
public override int GetWidth(String text) { public override int GetWidth(String text) {
char[] c = text.ToCharArray(); char[] c = text.ToCharArray();
int total = 0; int total = 0;
for (int k = 0; k < c.Length; ++k) for (int k = 0; k < c.Length; ++k)
total += GetWidth(c[k]); total += GetWidth(c[k]);
return total; return total;
} }
public override int[] GetCharBBox(int c) { public override int[] GetCharBBox(int c) {
return null; return null;
} }
public override bool CharExists(int c) { public override bool CharExists(int c) {
if ( c > 0 && c < 256 ) { if ( c > 0 && c < 256 ) {
return usedSlot[c]; return usedSlot[c];
} else { } else {
return false; return false;
} }
} }
public override bool SetCharAdvance(int c, int advance) { public override bool SetCharAdvance(int c, int advance) {
return false; return false;
} }
} }
} }