David PHAM-VAN

Improve API documentation

... ... @@ -9,24 +9,24 @@ environment:
dependencies:
flutter:
sdk: flutter
printing:
path_provider:
intl:
open_file:
path_provider:
printing:
url_launcher:
intl:
dev_dependencies:
flutter_test:
sdk: flutter
flutter_driver:
sdk: flutter
flutter_test:
sdk: flutter
test:
dependency_overrides:
printing:
path: ../printing
pdf:
path: ../pdf
printing:
path: ../printing
flutter:
uses-material-design: true
... ...
... ... @@ -8,6 +8,7 @@
- Update analysis options
- Fix the line cap and joint enums
- Fix PdfOutlineMode enum
- Improve API documentation
## 1.12.0
... ...
... ... @@ -16,4 +16,5 @@
import 'package:pdf/pdf.dart';
/// Zip compression function
DeflateCallback defaultDeflate;
... ...
... ... @@ -18,4 +18,5 @@ import 'package:archive/archive.dart';
import 'package:pdf/pdf.dart';
/// Zip compression function
DeflateCallback defaultDeflate = ZLibEncoder().encode;
... ...
... ... @@ -18,4 +18,5 @@ import 'dart:io';
import 'package:pdf/pdf.dart';
/// Zip compression function
DeflateCallback defaultDeflate = zlib.encode;
... ...
... ... @@ -30,8 +30,6 @@ class PdfAnnot extends PdfObject {
final PdfPage pdfPage;
/// Output the annotation
///
/// @param os OutputStream to send the object to
@override
void _prepare() {
super._prepare();
... ...
... ... @@ -20,6 +20,7 @@
part of pdf;
/// Arabic shape substitutions functions
class PdfArabic {
/// Arabic shape substitutions: char code => (isolated, final, initial, medial).
/// Arabic Substition A
... ... @@ -398,6 +399,7 @@ class PdfArabic {
}
}
/// Apply Arabic shape substitutions
static String convert(String input) {
return List<String>.from(_parse(input)).join('');
}
... ...
... ... @@ -16,13 +16,16 @@
part of pdf;
/// An array object
class PdfArrayObject extends PdfObject {
/// Creates an array object
PdfArrayObject(
PdfDocument pdfDocument,
this.array,
) : assert(array != null),
super(pdfDocument);
/// The array
final PdfArray array;
@override
... ...
... ... @@ -16,6 +16,7 @@
part of pdf;
/// Ascii 85 encoder
class Ascii85Encoder extends Converter<Uint8List, Uint8List> {
@override
Uint8List convert(Uint8List input) {
... ...
... ... @@ -16,6 +16,7 @@
part of pdf;
/// Border style
enum PdfBorderStyle {
/// Solid border. The border is drawn as a solid line.
solid,
... ... @@ -35,15 +36,9 @@ enum PdfBorderStyle {
underlined
}
/// Defines a border object
class PdfBorder extends PdfObject {
/// Creates a border using the predefined styles in [PdfAnnot].
/// Note: Do not use [PdfAnnot.dashed] with this method.
/// Use the other constructor.
///
/// @param width The width of the border
/// @param style The style of the border
/// @param dash The line pattern definition
/// @see [PdfAnnot]
PdfBorder(
PdfDocument pdfDocument,
this.width, {
... ... @@ -62,7 +57,6 @@ class PdfBorder extends PdfObject {
/// This array allows the definition of a dotted line for the border
final List<double> dash;
/// @param os OutputStream to send the object to
@override
void _prepare() {
super._prepare();
... ...
... ... @@ -16,12 +16,9 @@
part of pdf;
/// Pdf Catalog object
class PdfCatalog extends PdfObject {
/// This constructs a Pdf Catalog object
///
/// @param pdfPageList The [PdfPageList] object that's the root of the documents page tree
/// @param pagemode How the document should appear when opened.
/// Allowed values are usenone, useoutlines, usethumbs or fullscreen.
PdfCatalog(
PdfDocument pdfDocument,
this.pdfPageList,
... ... @@ -44,7 +41,6 @@ class PdfCatalog extends PdfObject {
/// The initial page mode
final PdfNames names;
/// @param os OutputStream to send the object to
@override
void _prepare() {
super._prepare();
... ...
... ... @@ -16,6 +16,7 @@
part of pdf;
/// Represents an RGB color
class PdfColor {
/// Create a color with red, green, blue and alpha components
/// values between 0 and 1
... ... @@ -69,6 +70,7 @@ class PdfColor {
return PdfColor(red, green, blue, alpha);
}
/// Load an RGB color from a RYB color
factory PdfColor.fromRYB(double red, double yellow, double blue,
[double alpha = 1.0]) {
assert(red >= 0 && red <= 1);
... ... @@ -128,11 +130,19 @@ class PdfColor {
return PdfColor(redValue, greenValue, blueValue, alpha);
}
/// Opacity
final double alpha;
/// Red component
final double red;
/// Green component
final double green;
/// Blue component
final double blue;
/// Get the int32 representation of this color
int toInt() =>
((((alpha * 255.0).round() & 0xff) << 24) |
(((red * 255.0).round() & 0xff) << 16) |
... ... @@ -140,6 +150,7 @@ class PdfColor {
(((blue * 255.0).round() & 0xff) << 0)) &
0xFFFFFFFF;
/// Get an Hexadecimal representation of this color
String toHex() {
final i = toInt();
final rgb = (i & 0xffffff).toRadixString(16);
... ... @@ -147,14 +158,17 @@ class PdfColor {
return '#$rgb$a';
}
/// Convert this color to CMYK
PdfColorCmyk toCmyk() {
return PdfColorCmyk.fromRgb(red, green, blue, alpha);
}
/// Convert this color to HSV
PdfColorHsv toHsv() {
return PdfColorHsv.fromRgb(red, green, blue, alpha);
}
/// Convert this color to HSL
PdfColorHsl toHsl() {
return PdfColorHsl.fromRgb(red, green, blue, alpha);
}
... ... @@ -166,6 +180,7 @@ class PdfColor {
return math.pow((component + 0.055) / 1.055, 2.4);
}
/// Get the luminance
double get luminance {
final R = _linearizeColorComponent(red);
final G = _linearizeColorComponent(green);
... ... @@ -191,24 +206,31 @@ class PdfColor {
/// Get some similar colors
List<PdfColor> get monochromatic => toHsv().monochromatic;
/// Returns a list of complementary colors
List<PdfColor> get splitcomplementary => toHsv().splitcomplementary;
/// Returns a list of tetradic colors
List<PdfColor> get tetradic => toHsv().tetradic;
/// Returns a list of triadic colors
List<PdfColor> get triadic => toHsv().triadic;
/// Returns a list of analagous colors
List<PdfColor> get analagous => toHsv().analagous;
@override
String toString() => '$runtimeType($red, $green, $blue, $alpha)';
}
/// Represents an CMYK color
class PdfColorCmyk extends PdfColor {
/// Creates a CMYK color
const PdfColorCmyk(this.cyan, this.magenta, this.yellow, this.black,
[double a = 1.0])
: super((1.0 - cyan) * (1.0 - black), (1.0 - magenta) * (1.0 - black),
(1.0 - yellow) * (1.0 - black), a);
/// Create a CMYK color from red ,green and blue components
const PdfColorCmyk.fromRgb(double r, double g, double b, [double a = 1.0])
: black = 1.0 - r > g
? r
... ... @@ -270,9 +292,16 @@ class PdfColorCmyk extends PdfColor {
: b)),
super(r, g, b, a);
/// Cyan component
final double cyan;
/// Magenta component
final double magenta;
/// Yellow component
final double yellow;
/// Black component
final double black;
@override
... ... @@ -306,6 +335,7 @@ double _getHue(
/// starting at the red primary at 0°, passing through the green primary
/// at 120° and the blue primary at 240°, and then wrapping back to red at 360°
class PdfColorHsv extends PdfColor {
/// Creates an HSV color
factory PdfColorHsv(double hue, double saturation, double value,
[double alpha = 1.0]) {
final chroma = saturation * value;
... ... @@ -352,6 +382,7 @@ class PdfColorHsv extends PdfColor {
assert(value >= 0 && value <= 1),
super(red, green, blue, alpha);
/// Creates an HSV color from red, green, blue components
factory PdfColorHsv.fromRgb(double red, double green, double blue,
[double alpha = 1.0]) {
final max = math.max(red, math.max(green, blue));
... ... @@ -433,7 +464,9 @@ class PdfColorHsv extends PdfColor {
String toString() => '$runtimeType($hue, $saturation, $value, $alpha)';
}
/// Represents an HSL color
class PdfColorHsl extends PdfColor {
/// Creates an HSL color
factory PdfColorHsl(double hue, double saturation, double lightness,
[double alpha = 1.0]) {
final chroma = (1.0 - (2.0 * lightness - 1.0).abs()) * saturation;
... ... @@ -485,6 +518,7 @@ class PdfColorHsl extends PdfColor {
assert(lightness >= 0 && lightness <= 1),
super(red, green, blue, alpha);
/// Creates an HSL color from red, green, and blue components
factory PdfColorHsl.fromRgb(double red, double green, double blue,
[double alpha = 1.0]) {
final max = math.max(red, math.max(green, blue));
... ... @@ -500,8 +534,13 @@ class PdfColorHsl extends PdfColor {
return PdfColorHsl._(hue, saturation, lightness, alpha, red, green, blue);
}
/// Hue component
final double hue;
/// Saturation component
final double saturation;
/// Lightness component
final double lightness;
@override
... ...
... ... @@ -14,8 +14,11 @@
* limitations under the License.
*/
// ignore_for_file: public_member_api_docs
part of pdf;
/// Material design colors
class PdfColors {
PdfColors._();
... ... @@ -393,6 +396,7 @@ class PdfColors {
deepOrangeAccent,
];
/// Get a pseudo-random color
static PdfColor getColor(int index) {
final hue = index * 137.508;
final PdfColor color = PdfColorHsv(hue % 360, 1, 1);
... ...
... ... @@ -16,6 +16,7 @@
part of pdf;
/// Display hint for the PDF viewer
enum PdfPageMode {
/// This page mode indicates that the document
/// should be opened just with the page visible. This is the default
... ... @@ -35,6 +36,7 @@ enum PdfPageMode {
fullscreen
}
/// Callback used to compress the data
typedef DeflateCallback = List<int> Function(List<int> data);
/// This class is the base of the Pdf generator. A [PdfDocument] class is
... ... @@ -44,8 +46,6 @@ typedef DeflateCallback = List<int> Function(List<int> data);
/// document's internal structures are kept in sync.
class PdfDocument {
/// This creates a Pdf document
/// @param pagemode an int, determines how the document will present itself to
/// the viewer when it first opens.
PdfDocument({
PdfPageMode pageMode = PdfPageMode.none,
DeflateCallback deflate,
... ... @@ -113,8 +113,9 @@ class PdfDocument {
/// This holds the current fonts
final Set<PdfFont> fonts = <PdfFont>{};
/// Generates the document ID
Uint8List _documentID;
/// Generates the document ID
Uint8List get documentID {
if (_documentID == null) {
final rnd = math.Random();
... ... @@ -132,16 +133,11 @@ class PdfDocument {
/// This returns a specific page. It's used mainly when using a
/// Serialized template file.
///
/// ?? How does a serialized template file work ???
///
/// @param page page number to return
/// @return [PdfPage] at that position
PdfPage page(int page) {
return pdfPageList.getPage(page);
}
/// @return the root outline
/// The root outline
PdfOutline get outline {
if (_outline == null) {
_outline = PdfOutline(this);
... ... @@ -156,19 +152,10 @@ class PdfDocument {
return _graphicStates;
}
/// This document has at least one graphic state
bool get hasGraphicStates => _graphicStates != null;
/// This writes the document to an OutputStream.
///
/// Note: You can call this as many times as you wish, as long as
/// the calls are not running at the same time.
///
/// Also, objects can be added or amended between these calls.
///
/// Also, the OutputStream is not closed, but will be flushed on
/// completion. It is up to the caller to close the stream.
///
/// @param os OutputStream to write the document to
void _write(PdfStream os) {
final pos = PdfOutput(os);
... ... @@ -180,6 +167,7 @@ class PdfDocument {
pos.close();
}
/// Generate the PDF document as a memory file
Uint8List save() {
final os = PdfStream();
_write(os);
... ...
... ... @@ -16,8 +16,11 @@
part of pdf;
/// Encryption object
abstract class PdfEncryption extends PdfObject {
/// Creates an encryption object
PdfEncryption(PdfDocument pdfDocument) : super(pdfDocument, null);
/// Encrypt some data
Uint8List encrypt(Uint8List input, PdfObject object);
}
... ...
... ... @@ -16,7 +16,9 @@
part of pdf;
/// Jpeg metadata extraction
class PdfJpegInfo {
/// Load a Jpeg image's metadata
factory PdfJpegInfo(Uint8List image) {
assert(image != null);
... ... @@ -73,14 +75,18 @@ class PdfJpegInfo {
PdfJpegInfo._(this.width, this.height, this._color, this.tags);
/// Width of the image
final int width;
/// Height of the image
final int height;
final int _color;
/// Is the image color or greyscale
bool get isRGB => _color == 3;
/// Exif tags discovered
final Map<PdfExifTag, dynamic> tags;
/// EXIF version
... ... @@ -94,6 +100,7 @@ class PdfJpegInfo {
? null
: utf8.decode(tags[PdfExifTag.FlashpixVersion]);
/// Rotation angle of this image
PdfImageOrientation get orientation {
if (tags == null || tags[PdfExifTag.Orientation] == null) {
return PdfImageOrientation.topLeft;
... ... @@ -106,21 +113,25 @@ class PdfJpegInfo {
}
}
/// Exif horizontal resolution
double get xResolution => tags == null || tags[PdfExifTag.XResolution] == null
? null
: tags[PdfExifTag.XResolution][0].toDouble() /
tags[PdfExifTag.XResolution][1].toDouble();
/// Exif vertical resolution
double get yResolution => tags == null || tags[PdfExifTag.YResolution] == null
? null
: tags[PdfExifTag.YResolution][0].toDouble() /
tags[PdfExifTag.YResolution][1].toDouble();
/// Exif horizontal pixel dimension
int get pixelXDimension =>
tags == null || tags[PdfExifTag.PixelXDimension] == null
? width
: tags[PdfExifTag.PixelXDimension];
/// Exif vertical pixel dimension
int get pixelYDimension =>
tags == null || tags[PdfExifTag.PixelYDimension] == null
? height
... ... @@ -440,111 +451,280 @@ orientation: $orientation''';
};
}
/// Possible Exif tags
enum PdfExifTag {
// version tags
ExifVersion, // EXIF version
FlashpixVersion, // Flashpix format version
/// EXIF version
ExifVersion,
/// Flashpix format version
FlashpixVersion,
// colorspace tags
ColorSpace, // Color space information tag
/// Color space information tag
ColorSpace,
// image configuration
PixelXDimension, // Valid width of meaningful image
PixelYDimension, // Valid height of meaningful image
ComponentsConfiguration, // Information about channels
CompressedBitsPerPixel, // Compressed bits per pixel
/// Valid width of meaningful image
PixelXDimension,
/// Valid height of meaningful image
PixelYDimension,
/// Information about channels
ComponentsConfiguration,
/// Compressed bits per pixel
CompressedBitsPerPixel,
// user information
MakerNote, // Any desired information written by the manufacturer
UserComment, // Comments by user
/// Any desired information written by the manufacturer
MakerNote,
/// Comments by user
UserComment,
// related file
RelatedSoundFile, // Name of related sound file
/// Name of related sound file
RelatedSoundFile,
// date and time
DateTimeOriginal, // Date and time when the original image was generated
DateTimeDigitized, // Date and time when the image was stored digitally
SubsecTime, // Fractions of seconds for DateTime
SubsecTimeOriginal, // Fractions of seconds for DateTimeOriginal
SubsecTimeDigitized, // Fractions of seconds for DateTimeDigitized
/// Date and time when the original image was generated
DateTimeOriginal,
/// Date and time when the image was stored digitally
DateTimeDigitized,
/// Fractions of seconds for DateTime
SubsecTime,
/// Fractions of seconds for DateTimeOriginal
SubsecTimeOriginal,
/// Fractions of seconds for DateTimeDigitized
SubsecTimeDigitized,
// picture-taking conditions
ExposureTime, // Exposure time (in seconds)
FNumber, // F number
ExposureProgram, // Exposure program
SpectralSensitivity, // Spectral sensitivity
ISOSpeedRatings, // ISO speed rating
OECF, // Optoelectric conversion factor
ShutterSpeedValue, // Shutter speed
ApertureValue, // Lens aperture
BrightnessValue, // Value of brightness
ExposureBias, // Exposure bias
MaxApertureValue, // Smallest F number of lens
SubjectDistance, // Distance to subject in meters
MeteringMode, // Metering mode
LightSource, // Kind of light source
Flash, // Flash status
SubjectArea, // Location and area of main subject
FocalLength, // Focal length of the lens in mm
FlashEnergy, // Strobe energy in BCPS
SpatialFrequencyResponse, //
FocalPlaneXResolution, // Number of pixels in width direction per FocalPlaneResolutionUnit
FocalPlaneYResolution, // Number of pixels in height direction per FocalPlaneResolutionUnit
FocalPlaneResolutionUnit, // Unit for measuring FocalPlaneXResolution and FocalPlaneYResolution
SubjectLocation, // Location of subject in image
ExposureIndex, // Exposure index selected on camera
SensingMethod, // Image sensor type
FileSource, // Image source (3 == DSC)
SceneType, // Scene type (1 == directly photographed)
CFAPattern, // Color filter array geometric pattern
CustomRendered, // Special processing
ExposureMode, // Exposure mode
WhiteBalance, // 1 = auto white balance, 2 = manual
DigitalZoomRation, // Digital zoom ratio
FocalLengthIn35mmFilm, // Equivalent foacl length assuming 35mm film camera (in mm)
SceneCaptureType, // Type of scene
GainControl, // Degree of overall image gain adjustment
Contrast, // Direction of contrast processing applied by camera
Saturation, // Direction of saturation processing applied by camera
Sharpness, // Direction of sharpness processing applied by camera
DeviceSettingDescription, //
SubjectDistanceRange, // Distance to subject
/// Exposure time (in seconds)
ExposureTime,
/// F number
FNumber,
/// Exposure program
ExposureProgram,
/// Spectral sensitivity
SpectralSensitivity,
/// ISO speed rating
ISOSpeedRatings,
/// Optoelectric conversion factor
OECF,
/// Shutter speed
ShutterSpeedValue,
/// Lens aperture
ApertureValue,
/// Value of brightness
BrightnessValue,
/// Exposure bias
ExposureBias,
/// Smallest F number of lens
MaxApertureValue,
/// Distance to subject in meters
SubjectDistance,
/// Metering mode
MeteringMode,
/// Kind of light source
LightSource,
/// Flash status
Flash,
/// Location and area of main subject
SubjectArea,
/// Focal length of the lens in mm
FocalLength,
/// Strobe energy in BCPS
FlashEnergy,
/// Spatial Frequency Response
SpatialFrequencyResponse,
/// Number of pixels in width direction per FocalPlaneResolutionUnit
FocalPlaneXResolution,
/// Number of pixels in height direction per FocalPlaneResolutionUnit
FocalPlaneYResolution,
/// Unit for measuring FocalPlaneXResolution and FocalPlaneYResolution
FocalPlaneResolutionUnit,
/// Location of subject in image
SubjectLocation,
/// Exposure index selected on camera
ExposureIndex,
/// Image sensor type
SensingMethod,
/// Image source (3 == DSC)
FileSource,
/// Scene type (1 == directly photographed)
SceneType,
/// Color filter array geometric pattern
CFAPattern,
/// Special processing
CustomRendered,
/// Exposure mode
ExposureMode,
/// 1 = auto white balance, 2 = manual
WhiteBalance,
/// Digital zoom ratio
DigitalZoomRation,
/// Equivalent foacl length assuming 35mm film camera (in mm)
FocalLengthIn35mmFilm,
/// Type of scene
SceneCaptureType,
/// Degree of overall image gain adjustment
GainControl,
/// Direction of contrast processing applied by camera
Contrast,
/// Direction of saturation processing applied by camera
Saturation,
/// Direction of sharpness processing applied by camera
Sharpness,
/// Device Setting Description
DeviceSettingDescription,
/// Distance to subject
SubjectDistanceRange,
// other tags
/// Interoperability IFD Pointer
InteroperabilityIFDPointer,
ImageUniqueID, // Identifier assigned uniquely to each image
//// Identifier assigned uniquely to each image
ImageUniqueID,
// tiff Tags
/// ImageWidth
ImageWidth,
/// ImageHeight
ImageHeight,
/// ExifIFDPointer
ExifIFDPointer,
/// GPSInfoIFDPointer
GPSInfoIFDPointer,
/// BitsPerSample
BitsPerSample,
/// Compression
Compression,
/// PhotometricInterpretation
PhotometricInterpretation,
/// Orientation
Orientation,
/// SamplesPerPixel
SamplesPerPixel,
/// PlanarConfiguration
PlanarConfiguration,
/// YCbCrSubSampling
YCbCrSubSampling,
/// YCbCrPositioning
YCbCrPositioning,
/// XResolution
XResolution,
/// YResolution
YResolution,
/// ResolutionUnit
ResolutionUnit,
/// StripOffsets
StripOffsets,
/// RowsPerStrip
RowsPerStrip,
/// StripByteCounts
StripByteCounts,
/// JPEGInterchangeFormat
JPEGInterchangeFormat,
/// JPEGInterchangeFormatLength
JPEGInterchangeFormatLength,
/// TransferFunction
TransferFunction,
/// WhitePoint
WhitePoint,
/// PrimaryChromaticities
PrimaryChromaticities,
/// YCbCrCoefficients
YCbCrCoefficients,
/// ReferenceBlackWhite
ReferenceBlackWhite,
/// DateTime
DateTime,
/// ImageDescription
ImageDescription,
/// Make
Make,
/// Model
Model,
/// Software
Software,
/// Artist
Artist,
/// Copyright
Copyright,
}
... ...
... ... @@ -16,84 +16,96 @@
part of pdf;
/// Pdf font object
abstract class PdfFont extends PdfObject {
/// Constructs a [PdfFont]. This will attempt to map the font from a known
/// font name to that in Pdf, defaulting to Helvetica if not possible.
///
/// @param name The document name, ie /F1
/// @param subtype The pdf type, ie /Type1
/// @param baseFont The font name, ie /Helvetica
PdfFont._create(PdfDocument pdfDocument, {@required this.subtype})
: assert(subtype != null),
super(pdfDocument, '/Font') {
pdfDocument.fonts.add(this);
}
/// Monospaced slab serif typeface.
factory PdfFont.courier(PdfDocument pdfDocument) {
return PdfType1Font._create(
pdfDocument, 'Courier', 0.910, -0.220, const <double>[]);
}
/// Bold monospaced slab serif typeface.
factory PdfFont.courierBold(PdfDocument pdfDocument) {
return PdfType1Font._create(
pdfDocument, 'Courier-Bold', 0.910, -0.220, const <double>[]);
}
/// Bold and Italic monospaced slab serif typeface.
factory PdfFont.courierBoldOblique(PdfDocument pdfDocument) {
return PdfType1Font._create(
pdfDocument, 'Courier-BoldOblique', 0.910, -0.220, const <double>[]);
}
/// Italic monospaced slab serif typeface.
factory PdfFont.courierOblique(PdfDocument pdfDocument) {
return PdfType1Font._create(
pdfDocument, 'Courier-Oblique', 0.910, -0.220, const <double>[]);
}
/// Neo-grotesque design sans-serif typeface
factory PdfFont.helvetica(PdfDocument pdfDocument) {
return PdfType1Font._create(
pdfDocument, 'Helvetica', 0.931, -0.225, _helveticaWidths);
}
/// Bold Neo-grotesque design sans-serif typeface
factory PdfFont.helveticaBold(PdfDocument pdfDocument) {
return PdfType1Font._create(
pdfDocument, 'Helvetica-Bold', 0.962, -0.228, _helveticaBoldWidths);
}
/// Bold and Italic Neo-grotesque design sans-serif typeface
factory PdfFont.helveticaBoldOblique(PdfDocument pdfDocument) {
return PdfType1Font._create(pdfDocument, 'Helvetica-BoldOblique', 0.962,
-0.228, _helveticaBoldObliqueWidths);
}
/// Italic Neo-grotesque design sans-serif typeface
factory PdfFont.helveticaOblique(PdfDocument pdfDocument) {
return PdfType1Font._create(pdfDocument, 'Helvetica-Oblique', 0.931, -0.225,
_helveticaObliqueWidths);
}
/// Serif typeface commissioned by the British newspaper The Times
factory PdfFont.times(PdfDocument pdfDocument) {
return PdfType1Font._create(
pdfDocument, 'Times-Roman', 0.898, -0.218, _timesWidths);
}
/// Bold serif typeface commissioned by the British newspaper The Times
factory PdfFont.timesBold(PdfDocument pdfDocument) {
return PdfType1Font._create(
pdfDocument, 'Times-Bold', 0.935, -0.218, _timesBoldWidths);
}
/// Bold and Italic serif typeface commissioned by the British newspaper The Times
factory PdfFont.timesBoldItalic(PdfDocument pdfDocument) {
return PdfType1Font._create(
pdfDocument, 'Times-BoldItalic', 0.921, -0.218, _timesBoldItalicWidths);
}
/// Italic serif typeface commissioned by the British newspaper The Times
factory PdfFont.timesItalic(PdfDocument pdfDocument) {
return PdfType1Font._create(
pdfDocument, 'Times-Italic', 0.883, -0.217, _timesItalicWidths);
}
/// Complete unaccented serif Greek alphabet (upper and lower case) and a
/// selection of commonly used mathematical symbols.
factory PdfFont.symbol(PdfDocument pdfDocument) {
return PdfType1Font._create(
pdfDocument, 'Symbol', 1.010, -0.293, _symbolWidths);
}
/// Hermann Zapf ornament glyphs or spacers, often employed to create box frames
factory PdfFont.zapfDingbats(PdfDocument pdfDocument) {
return PdfType1Font._create(
pdfDocument, 'ZapfDingbats', 0.820, -0.143, _zapfDingbatsWidths);
... ... @@ -110,17 +122,22 @@ See https://github.com/DavBfr/dart_pdf/wiki/Fonts-Management
/// The df type of the font, usually /Type1
final String subtype;
/// Internal name
String get name => '/F$objser';
/// The font's real name
String get fontName => null;
/// Spans the distance between the baseline and the top of the glyph that
/// reaches farthest from the baseline
double get ascent => null;
/// Spans the distance between the baseline and the lowest descending glyph
double get descent => null;
/// Default width of a glyph
static const double defaultGlyphWidth = 0.600;
/// @param os OutputStream to send the object to
@override
void _prepare() {
super._prepare();
... ... @@ -130,14 +147,18 @@ See https://github.com/DavBfr/dart_pdf/wiki/Fonts-Management
params['/Encoding'] = const PdfName('/WinAnsiEncoding');
}
/// How many units to move for the next glyph
@Deprecated('Use `glyphMetrics` instead')
double glyphAdvance(int charCode) => glyphMetrics(charCode).advanceWidth;
/// Calculate the [PdfFontMetrics] for this glyph
PdfFontMetrics glyphMetrics(int charCode);
/// Calculate the dimensions of this glyph
@Deprecated('Use `glyphMetrics` instead')
PdfRect glyphBounds(int charCode) => glyphMetrics(charCode).toPdfRect();
/// Calculate the [PdfFontMetrics] for this string
PdfFontMetrics stringMetrics(String s, {double letterSpacing = 0}) {
if (s.isEmpty) {
return PdfFontMetrics.zero;
... ... @@ -157,9 +178,11 @@ See https://github.com/DavBfr/dart_pdf/wiki/Fonts-Management
}
}
/// Calculage the bounding box for this string
@Deprecated('Use `stringMetrics` instead')
PdfRect stringBounds(String s) => stringMetrics(s).toPdfRect();
/// Calculage the unit size of this string
PdfPoint stringSize(String s) {
final metrics = stringMetrics(s);
return PdfPoint(metrics.width, metrics.height);
... ... @@ -168,6 +191,7 @@ See https://github.com/DavBfr/dart_pdf/wiki/Fonts-Management
@override
String toString() => 'Font($fontName)';
/// Draw some text
void putText(PdfStream stream, String text) {
try {
PdfString(latin1.encode(text), PdfStringFormat.litteral).output(stream);
... ...
... ... @@ -16,7 +16,9 @@
part of pdf;
/// Font descriptor object
class PdfFontDescriptor extends PdfObject {
/// Create a Font descriptor object
PdfFontDescriptor(
this.ttfFont,
this.file,
... ... @@ -24,8 +26,10 @@ class PdfFontDescriptor extends PdfObject {
assert(file != null),
super(ttfFont.pdfDocument, '/FontDescriptor');
/// File data
final PdfObjectStream file;
/// Truetype font
final PdfTtfFont ttfFont;
@override
... ...
... ... @@ -16,8 +16,10 @@
part of pdf;
/// Describe dimensions for glyphs in a font
@immutable
class PdfFontMetrics {
/// Create a PdfFontMetrics object
const PdfFontMetrics(
{@required this.left,
@required this.top,
... ... @@ -37,6 +39,7 @@ class PdfFontMetrics {
assert(top <= bottom),
assert((descent ?? top) <= (ascent ?? bottom));
/// Add another metric
factory PdfFontMetrics.append(
Iterable<PdfFontMetrics> metrics, {
double letterSpacing = 0,
... ... @@ -76,42 +79,59 @@ class PdfFontMetrics {
advanceWidth: right - spacing);
}
/// Zero-sized dimensions
static const PdfFontMetrics zero =
PdfFontMetrics(left: 0, top: 0, right: 0, bottom: 0);
/// Left most of the bounding box
final double left;
/// Top most of the bounding box
final double top;
/// Bottom most of the bounding box
final double bottom;
/// Right most of the bounding box
final double right;
/// Spans the distance between the baseline and the top of the glyph that
/// reaches farthest from the baseline
final double ascent;
/// Spans the distance between the baseline and the lowest descending glyph
final double descent;
/// distance to move right to draw the next glyph
final double advanceWidth;
/// Width of the glyph
double get width => right - left;
/// Height of the glyph
double get height => bottom - top;
double get maxHeight => ascent - descent;
/// Maximum Width any glyph from this font can have
double get maxWidth =>
math.max(advanceWidth, right) + math.max(-leftBearing, 0.0);
/// Maximum Height any glyph from this font can have
double get maxHeight => ascent - descent;
/// Real left position. The glyph may overflow on the left
double get effectiveLeft => math.min(leftBearing, 0);
/// Starting point
double get leftBearing => left;
/// Ending point
double get rightBearing => advanceWidth - right;
@override
String toString() =>
'PdfFontMetrics(left:$left, top:$top, right:$right, bottom:$bottom, ascent:$ascent, descent:$descent, advanceWidth:$advanceWidth)';
/// Make a copy of this object
PdfFontMetrics copyWith(
{double left,
double top,
... ... @@ -130,6 +150,7 @@ class PdfFontMetrics {
advanceWidth: advanceWidth ?? this.advanceWidth);
}
/// Multiply this metrics object with a font size
PdfFontMetrics operator *(double factor) {
return copyWith(
left: left * factor,
... ... @@ -142,5 +163,6 @@ class PdfFontMetrics {
);
}
/// Get the bounding box
PdfRect toPdfRect() => PdfRect.fromLTRB(left, top, right, bottom);
}
... ...
... ... @@ -16,7 +16,9 @@
part of pdf;
/// Form XObject
class PdfFormXObject extends PdfXObject {
/// Create a Form XObject
PdfFormXObject(PdfDocument pdfDocument) : super(pdfDocument, '/Form') {
params['/FormType'] = const PdfNum(1);
params['/BBox'] = PdfArray.fromNum(const <int>[0, 0, 1000, 1000]);
... ... @@ -28,7 +30,7 @@ class PdfFormXObject extends PdfXObject {
/// The xobjects or other images in the pdf
final Map<String, PdfXObject> xobjects = <String, PdfXObject>{};
/// set matrix
/// Transformation matrix
void setMatrix(Matrix4 t) {
final s = t.storage;
params['/Matrix'] =
... ... @@ -39,8 +41,7 @@ class PdfFormXObject extends PdfXObject {
void _prepare() {
super._prepare();
// Now the resources
/// This holds any resources for this FormXObject
// This holds any resources for this FormXObject
final resources = PdfDict();
// fonts
... ...
... ... @@ -18,10 +18,13 @@
part of pdf;
/// Graphic state
@immutable
class PdfGraphicState {
/// Create a new graphic state
const PdfGraphicState({this.opacity});
/// The opacity to apply to this graphic state
final double opacity;
@protected
... ... @@ -48,13 +51,16 @@ class PdfGraphicState {
int get hashCode => opacity.hashCode;
}
/// Stores all the graphic states used in the document
class PdfGraphicStates extends PdfObject {
/// Create a new Graphic States object
PdfGraphicStates(PdfDocument pdfDocument) : super(pdfDocument);
final List<PdfGraphicState> _states = <PdfGraphicState>[];
static const String _prefix = '/a';
/// Generate a name for a state object
String stateName(PdfGraphicState state) {
var index = _states.indexOf(state);
if (index < 0) {
... ...
... ... @@ -16,6 +16,7 @@
part of pdf;
/// Helper functions for graphic objects
mixin PdfGraphicStream on PdfObject {
/// Isolated transparency: If this flag is true, objects within the group
/// shall be composited against a fully transparent initial backdrop;
... ... @@ -38,24 +39,28 @@ mixin PdfGraphicStream on PdfObject {
/// The xobjects or other images in the pdf
final Map<String, PdfXObject> xObjects = <String, PdfXObject>{};
/// Add a font to this graphic object
void addFont(PdfFont font) {
if (!fonts.containsKey(font.name)) {
fonts[font.name] = font;
}
}
/// Add a shader to this graphic object
void addShader(PdfShading shader) {
if (!shading.containsKey(shader.name)) {
shading[shader.name] = shader;
}
}
/// Add an XObject to this graphic object
void addXObject(PdfXObject object) {
if (!xObjects.containsKey(object.name)) {
xObjects[object.name] = object;
}
}
/// Get the default font of this graphic object
PdfFont getDefaultFont() {
if (pdfDocument.fonts.isEmpty) {
PdfFont.helvetica(pdfDocument);
... ... @@ -64,6 +69,7 @@ mixin PdfGraphicStream on PdfObject {
return pdfDocument.fonts.elementAt(0);
}
/// Generate a name for the graphic state object
String stateName(PdfGraphicState state) {
return pdfDocument.graphicStates.stateName(state);
}
... ... @@ -114,7 +120,9 @@ mixin PdfGraphicStream on PdfObject {
}
}
/// Graphic XObject
class PdfGraphicXObject extends PdfXObject with PdfGraphicStream {
/// Creates a Graphic XObject
PdfGraphicXObject(
PdfDocument pdfDocument, [
String subtype,
... ...
... ... @@ -76,7 +76,9 @@ class _PdfGraphicsContext {
_PdfGraphicsContext copy() => _PdfGraphicsContext(ctm: ctm.clone());
}
/// Pdf drawing operations
class PdfGraphics {
/// Create a new graphic canvas
PdfGraphics(this._page, this.buf) {
_context = _PdfGraphicsContext(ctm: Matrix4.identity());
}
... ... @@ -90,22 +92,29 @@ class PdfGraphics {
final PdfGraphicStream _page;
/// Buffer where to write the graphic operations
final PdfStream buf;
/// Default font if none selected
PdfFont get defaultFont => _page.getDefaultFont();
/// Draw a surface on the previously defined shape
void fillPath() {
buf.putString('f\n');
}
/// Draw the contour of the previously defined shape
void strokePath() {
buf.putString('S\n');
}
/// Close the path with a line
void closePath() {
buf.putString('s\n');
}
/// Create a clipping surface from the previously defined shape,
/// to prevent any further drawing outside
void clipPath() {
buf.putString('W n\n');
}
... ... @@ -130,26 +139,13 @@ class PdfGraphics {
}
}
/// Save the graphc context
void saveContext() {
// save graphics context
buf.putString('q\n');
_contextQueue.addLast(_context.copy());
}
/// Draws an image onto the page.
///
/// This method is implemented with [Ascii85Encoder] encoding and the
/// zip stream deflater. It results in a stream that is anywhere
/// from 3 to 10 times as big as the image. This obviously needs some
/// improvement, but it works well for small images
///
/// @param img The Image
/// @param x coordinate on page
/// @param y coordinate on page
/// @param w Width on page
/// @param h height on page
/// @param bgcolor Background colour
/// @return true if drawn
void drawImage(PdfImage img, double x, double y, [double w, double h]) {
w ??= img.width.toDouble();
h ??= img.height.toDouble() * w / img.width.toDouble();
... ... @@ -190,19 +186,12 @@ class PdfGraphics {
}
/// Draws a line between two coordinates.
///
/// If the first coordinate is the same as the last one drawn
/// (i.e. a previous drawLine, moveto, etc) it is ignored.
///
/// @param x1 coordinate
/// @param y1 coordinate
/// @param x2 coordinate
/// @param y2 coordinate
void drawLine(double x1, double y1, double x2, double y2) {
moveTo(x1, y1);
lineTo(x2, y2);
}
/// Draws an ellipse
void drawEllipse(double x, double y, double r1, double r2) {
moveTo(x, y - r2);
curveTo(x + _m4 * r1, y - r2, x + r1, y - _m4 * r2, x + r1, y);
... ... @@ -212,11 +201,6 @@ class PdfGraphics {
}
/// Draws a Rectangle
///
/// @param x coordinate
/// @param y coordinate
/// @param w width
/// @param h height
void drawRect(
double x,
double y,
... ... @@ -228,13 +212,6 @@ class PdfGraphics {
}
/// Draws a Rounded Rectangle
///
/// @param x coordinate
/// @param y coordinate
/// @param w width
/// @param h height
/// @param rh horizontal radius
/// @param rv vertical radius
void drawRRect(double x, double y, double w, double h, double rv, double rh) {
moveTo(x, y + rv);
curveTo(x, y - _m4 * rv + rv, x - _m4 * rh + rh, y, x + rh, y);
... ... @@ -283,10 +260,6 @@ class PdfGraphics {
}
/// This draws a string.
///
/// @param x coordinate
/// @param y coordinate
/// @param s String to draw
void drawString(
PdfFont font,
double size,
... ... @@ -316,16 +289,12 @@ class PdfGraphics {
}
/// Sets the color for drawing
///
/// @param c Color to use
void setColor(PdfColor color) {
setFillColor(color);
setStrokeColor(color);
}
/// Sets the fill color for drawing
///
/// @param c Color to use
void setFillColor(PdfColor color) {
if (color is PdfColorCmyk) {
PdfNumList(<double>[color.cyan, color.magenta, color.yellow, color.black])
... ... @@ -338,8 +307,6 @@ class PdfGraphics {
}
/// Sets the stroke color for drawing
///
/// @param c Color to use
void setStrokeColor(PdfColor color) {
if (color is PdfColorCmyk) {
PdfNumList(<double>[color.cyan, color.magenta, color.yellow, color.black])
... ... @@ -371,18 +338,12 @@ class PdfGraphics {
}
/// This adds a line segment to the current path
///
/// @param x coordinate
/// @param y coordinate
void lineTo(double x, double y) {
PdfNumList(<double>[x, y]).output(buf);
buf.putString(' l\n');
}
/// This moves the current drawing point.
///
/// @param x coordinate
/// @param y coordinate
void moveTo(double x, double y) {
PdfNumList(<double>[x, y]).output(buf);
buf.putString(' m\n');
... ... @@ -391,13 +352,6 @@ class PdfGraphics {
/// Draw a cubic bézier curve from the current point to (x3,y3)
/// using (x1,y1) as the control point at the beginning of the curve
/// and (x2,y2) as the control point at the end of the curve.
///
/// @param x1 first control point
/// @param y1 first control point
/// @param x2 second control point
/// @param y2 second control point
/// @param x3 end point
/// @param y3 end point
void curveTo(
double x1, double y1, double x2, double y2, double x3, double y3) {
PdfNumList(<double>[x1, y1, x2, y2, x3, y3]).output(buf);
... ... @@ -546,11 +500,13 @@ class PdfGraphics {
}
}
/// Draw an SVG path
void drawShape(String d, {bool stroke = true}) {
final proxy = _PathProxy(this, stroke);
writeSvgPathDataToPath(d, proxy);
}
/// Set line starting and ending cap type
void setLineCap(PdfLineCap cap) {
buf.putString('${cap.index} J\n');
}
... ... @@ -560,16 +516,22 @@ class PdfGraphics {
buf.putString('${join.index} j\n');
}
/// Set line width
void setLineWidth(double width) {
PdfNum(width).output(buf);
buf.putString(' w\n');
}
/// Set line joint miter limit, applies if the
void setMiterLimit(double limit) {
PdfNum(limit).output(buf);
buf.putString(' M\n');
}
/// The dash array shall be cycled through, adding up the lengths of dashes and gaps.
/// When the accumulated length equals the value specified by the dash phase
///
/// Example: [2 1] will create a dash pattern with 2 on, 1 off, 2 on, 1 off, ...
void setLineDashPattern([List<int> array = const <int>[], int phase = 0]) {
PdfArray.fromNum(array).output(buf);
buf.putString(' $phase d\n');
... ...
... ... @@ -19,16 +19,32 @@ part of pdf;
/// Represents the position of the first pixel in the data stream
/// This corresponds to the exif orientations
enum PdfImageOrientation {
/// Rotated 0°
topLeft,
/// Rotated 90°
topRight,
/// Rotated 180°
bottomRight,
/// Rotated 270°
bottomLeft,
/// Rotated 0° mirror
leftTop,
/// Rotated 90° mirror
rightTop,
/// Rotated 180° mirror
rightBottom,
/// Rotated 270° mirror
leftBottom,
}
/// Image object stored in the Pdf document
class PdfImage extends PdfXObject {
/// Creates a new [PdfImage] instance.
factory PdfImage(
... ... @@ -77,6 +93,7 @@ class PdfImage extends PdfXObject {
return im;
}
/// Create an image from a jpeg file
factory PdfImage.jpeg(
PdfDocument pdfDocument, {
@required Uint8List image,
... ... @@ -107,6 +124,7 @@ class PdfImage extends PdfXObject {
return im;
}
/// Create an image from an [im.Image] object
factory PdfImage.fromImage(
PdfDocument pdfDocument, {
@required im.Image image,
... ... @@ -124,6 +142,7 @@ class PdfImage extends PdfXObject {
);
}
/// Create an image from an image file
factory PdfImage.file(
PdfDocument pdfDocument, {
@required Uint8List bytes,
... ... @@ -185,12 +204,14 @@ class PdfImage extends PdfXObject {
params['/Height'] = PdfNum(_height);
}
/// Image width
final int _width;
/// Image width
int get width => orientation.index >= 4 ? _height : _width;
/// Image height
final int _height;
/// Image height
int get height => orientation.index < 4 ? _height : _width;
/// The internal orientation of the image
... ...
... ... @@ -16,8 +16,9 @@
part of pdf;
/// Information object
class PdfInfo extends PdfObject {
/// @param title Title of this document
/// Create an information object
PdfInfo(PdfDocument pdfDocument,
{this.title,
this.author,
... ... @@ -53,15 +54,21 @@ class PdfInfo extends PdfObject {
static const String _libraryName = 'https://github.com/DavBfr/dart_pdf';
/// Author of this document
final String author;
/// Creator of this document
final String creator;
/// Title of this document
final String title;
/// Subject of this document
final String subject;
/// Keywords of this document
final String keywords;
/// Application that created this document
final String producer;
}
... ...
... ... @@ -16,12 +16,14 @@
part of pdf;
/// Pdf Name object
class PdfNames extends PdfObject {
/// This constructs a Pdf Name object
PdfNames(PdfDocument pdfDocument) : super(pdfDocument);
final Map<String, PdfDataType> _dests = <String, PdfDataType>{};
/// Add a named destination
void addDest(
String name,
PdfPage page, {
... ...
... ... @@ -16,12 +16,14 @@
part of pdf;
/// Base Object used in the PDF file
class PdfObject {
/// This is usually called by extensors to this class, and sets the
/// Pdf Object Type
/// @param type the Pdf Object Type
PdfObject(this.pdfDocument, [String type])
: assert(pdfDocument != null),
PdfObject(
this.pdfDocument, [
String type,
]) : assert(pdfDocument != null),
objser = pdfDocument._genSerial() {
if (type != null) {
params['/Type'] = PdfName(type);
... ... @@ -43,12 +45,6 @@ class PdfObject {
final PdfDocument pdfDocument;
/// Writes the object to the output stream.
/// This method must be overridden.
///
/// Note: It should not write any other objects, even if they are
/// it's Kids, as they will be written by the calling routine.
///
/// @param os OutputStream to send the object to
void _write(PdfStream os) {
_prepare();
_writeStart(os);
... ... @@ -62,10 +58,6 @@ class PdfObject {
/// The write method should call this before writing anything to the
/// OutputStream. This will send the standard header for each object.
///
/// Note: There are a few rare cases where this method is not called.
///
/// @param os OutputStream to write to
void _writeStart(PdfStream os) {
os.putString('$objser $objgen obj\n');
}
... ... @@ -79,15 +71,10 @@ class PdfObject {
/// The write method should call this after writing anything to the
/// OutputStream. This will send the standard footer for each object.
///
/// Note: There are a few rare cases where this method is not called.
///
/// @param os OutputStream to write to
void _writeEnd(PdfStream os) {
os.putString('endobj\n');
}
/// Returns the unique serial number in Pdf format
/// @return the serial number in Pdf format
PdfIndirect ref() => PdfIndirect(objser, objgen);
}
... ...
... ... @@ -16,16 +16,14 @@
part of pdf;
/// Stream Object
class PdfObjectStream extends PdfObject {
/// Constructs a stream. The supplied type is stored in the stream's header
/// and is used by other objects that extend the [PdfStream] class (like
/// [PdfImage]).
/// By default, the stream will be compressed.
///
/// @param type type for the stream
/// @see [PdfImage]
PdfObjectStream(PdfDocument pdfDocument, {String type, this.isBinary = false})
: super(pdfDocument, type);
/// Constructs a stream object to store some data
PdfObjectStream(
PdfDocument pdfDocument, {
String type,
this.isBinary = false,
}) : super(pdfDocument, type);
/// This holds the stream's content.
final PdfStream buf = PdfStream();
... ...
... ... @@ -16,6 +16,7 @@
part of pdf;
/// Outline mode
enum PdfOutlineMode {
/// When jumping to the destination, display the whole page
fitPage,
... ... @@ -24,6 +25,7 @@ enum PdfOutlineMode {
fitRect
}
/// Outline style
enum PdfOutlineStyle {
/// Normal
normal,
... ... @@ -31,16 +33,17 @@ enum PdfOutlineStyle {
/// Italic
italic,
// Bold
/// Bold
bold,
/// Italic and Bold
italicBold,
}
/// Pdf Outline object
class PdfOutline extends PdfObject {
/// Constructs a Pdf Outline object. When selected, the specified region
/// is displayed.
/// Constructs a Pdf Outline object.
/// When selected, the specified region is displayed.
PdfOutline(
PdfDocument pdfDocument, {
this.title,
... ... @@ -82,6 +85,7 @@ class PdfOutline extends PdfObject {
/// How to display the outline text
final PdfOutlineStyle style;
/// External level for this outline
int effectiveLevel;
/// This method creates an outline, and attaches it to this one.
... ... @@ -91,7 +95,6 @@ class PdfOutline extends PdfObject {
outlines.add(outline);
}
/// @param os OutputStream to send the object to
@override
void _prepare() {
super._prepare();
... ... @@ -162,22 +165,15 @@ class PdfOutline extends PdfObject {
/// This is called by children to find their position in this outlines
/// tree.
///
/// @param outline [PdfOutline] to search for
/// @return index within Vector
int getIndex(PdfOutline outline) => outlines.indexOf(outline);
/// Returns the last index in this outline
/// @return last index in outline
int getLast() => outlines.length - 1;
/// Returns the outline at a specified position.
/// @param i index
/// @return the node at index i
PdfOutline getNode(int i) => outlines[i];
/// Returns the total number of descendants below this one.
/// @return the number of descendants below this one
int descendants() {
var c = outlines.length; // initially the number of kids
... ...
... ... @@ -16,10 +16,9 @@
part of pdf;
/// PDF document writer
class PdfOutput {
/// This creates a Pdf [PdfStream]
///
/// @param os The output stream to write the Pdf file to.
PdfOutput(this.os) {
os.putString('%PDF-1.4\n');
os.putBytes(const <int>[0x25, 0xC2, 0xA5, 0xC2, 0xB1, 0xC3, 0xAB, 0x0A]);
... ... @@ -44,8 +43,6 @@ class PdfOutput {
PdfSignature signatureID;
/// This method writes a [PdfObject] to the stream.
///
/// @param ob [PdfObject] Object to write
void write(PdfObject ob) {
// Check the object to see if it's one that is needed in the trailer
// object
... ... @@ -146,8 +143,6 @@ class PdfOutput {
}
/// Writes a block of references to the Pdf file
/// @param firstid ID of the first reference in this block
/// @param block Vector containing the references in this block
void writeblock(int firstid, List<PdfXref> block) {
os.putString('$firstid ${block.length}\n');
... ...
... ... @@ -16,14 +16,10 @@
part of pdf;
/// Page object, which will hold any contents for this page.
class PdfPage extends PdfObject with PdfGraphicStream {
/// This constructs a Page object, which will hold any contents for this
/// page.
///
/// Once created, it is added to the document via the [PdfDocument.add()] method.
///
/// @param pdfDocument Document
/// @param pageFormat [PdfPageFormat] describing the page size
PdfPage(PdfDocument pdfDocument, {this.pageFormat = PdfPageFormat.standard})
: super(pdfDocument, '/Page') {
pdfDocument.pdfPageList.pages.add(this);
... ... @@ -46,8 +42,6 @@ class PdfPage extends PdfObject with PdfGraphicStream {
/// on to this page. If a previous [PdfGraphics] object was used, this object
/// is appended to the page, and will be drawn over the top of any previous
/// objects.
///
/// @return a new [PdfGraphics] object to be used to draw this page.
PdfGraphics getGraphics() {
final stream = PdfObjectStream(pdfDocument);
final g = PdfGraphics(this, stream.buf);
... ... @@ -56,11 +50,6 @@ class PdfPage extends PdfObject with PdfGraphicStream {
}
/// This adds an Annotation to the page.
///
/// As with other objects, the annotation must be added to the pdf
/// document using [PdfDocument.add()] before adding to the page.
///
/// @param ob Annotation to add.
void addAnnotation(PdfObject ob) {
annotations.add(ob);
}
... ...
... ... @@ -16,6 +16,7 @@
part of pdf;
/// PdfPageList object
class PdfPageList extends PdfObject {
/// This constructs a [PdfPageList] object.
PdfPageList(PdfDocument pdfDocument) : super(pdfDocument, '/Pages');
... ... @@ -24,8 +25,6 @@ class PdfPageList extends PdfObject {
final List<PdfPage> pages = <PdfPage>[];
/// This returns a specific page. Used by the Pdf class.
/// @param page page number to return
/// @return [PdfPage] at that position
PdfPage getPage(int page) => pages[page];
@override
... ...
... ... @@ -16,10 +16,15 @@
part of pdf;
/// Generate a TTF font copy with the minimal number of glyph to embedd
/// into the PDF document
///
/// https://opentype.js.org/
class TtfWriter {
/// Create a Truetype Writer object
TtfWriter(this.ttf);
/// original truetype file
final TtfParser ttf;
int _calcTableChecksum(ByteData table) {
... ... @@ -52,6 +57,7 @@ class TtfWriter {
return offset + ((align - (offset % align)) % align);
}
/// Write this list of glyphs
Uint8List withChars(List<int> chars) {
final tables = <String, Uint8List>{};
final tablesLength = <String, int>{};
... ...
... ... @@ -16,6 +16,14 @@
part of pdf;
/// Type 1 font object.
/// this font is a default PDF font available in all PDF readers,
/// but it's only compatible with western latin languages.
///
/// To use other languages, use a [PdfTtfFont] that contains the
/// glyph for the language you will use.
///
/// see https://github.com/DavBfr/dart_pdf/wiki/Fonts-Management
class PdfType1Font extends PdfFont {
/// Constructs a [PdfTtfFont]
PdfType1Font._create(PdfDocument pdfDocument, this.fontName, this.ascent,
... ... @@ -27,7 +35,6 @@ class PdfType1Font extends PdfFont {
}()),
super._create(pdfDocument, subtype: '/Type1');
/// The font's real name
@override
final String fontName;
... ... @@ -37,9 +44,9 @@ class PdfType1Font extends PdfFont {
@override
final double descent;
/// Width of each glyph
final List<double> widths;
/// @param os OutputStream to send the object to
@override
void _prepare() {
super._prepare();
... ...
... ... @@ -16,11 +16,15 @@
part of pdf;
/// Unicode character map object
class PdfUnicodeCmap extends PdfObjectStream {
/// Create a Unicode character map object
PdfUnicodeCmap(PdfDocument pdfDocument, this.protect) : super(pdfDocument);
/// List of characters
final List<int> cmap = <int>[0];
/// Protects the text from being "seen" by the PDF reader.
final bool protect;
@override
... ...
... ... @@ -16,11 +16,9 @@
part of pdf;
/// Cross-reference for a Pdf Object
class PdfXref {
/// Creates a cross-reference for a Pdf Object
/// @param id The object's ID
/// @param offset The object's position in the file
/// @param generation The object's generation, usually 0
PdfXref(this.id, this.offset, {this.generation = 0});
/// The id of a Pdf Object
... ... @@ -32,7 +30,7 @@ class PdfXref {
/// The generation of the object, usually 0
int generation = 0;
/// @return The xref in the format of the xref section in the Pdf file
/// The xref in the format of the xref section in the Pdf file
String ref() {
final rs = offset.toString().padLeft(10, '0') +
' ' +
... ...
... ... @@ -149,8 +149,9 @@ class _BarcodeWidget extends Widget {
}
}
/// Draw a barcode using String data
class BarcodeWidget extends StatelessWidget {
/// Draw a barcode using String data
/// Create a BarcodeWidget
factory BarcodeWidget({
@required String data,
@required Barcode barcode,
... ...