% This example shows how to use pdfTeX primitives. High-level macros are provided
% by macros packages like LaTeX or ConTeXt. We present basic set of commands,
% extended with some more sophisticated issues (like MP to PDF conversion). All
% the functionality other than provided by pdfTeX itself is commented by default.
% Please follow the code below and uncomment fragments you want.

% Many new features has been implemented since the first release of pdfTeX. To
% make this sample version independent, we use compatibility sections.

\def\ifversion#1.#2#3#4 {% 1.20, 1.30.0 ...
 \ifnum\pdftexversion<#1#2#3
  \notsupported
 \else
  \supported
 \fi}

% to trick \if..\fi balancing
% \def\otherwise{\else}
% \def\endif{\fi}

\def\supported{\expandafter\iftrue}
\def\notsupported{\expandafter\iffalse}

\def\feature#1.#2#3#4#{\dofeature{#1#2#3}{#1.#2#3#4}}
\long\def\dofeature#1#2#3#4\endfeature{%
 \ifnum#1>\pdftexversion
  #3 not supported by this version of \pdfTeX.\par
 \else#4\fi}

\def\pdfTeX{pdf\TeX}
\def\cs#1{{\tt\string#1}}
\def\newpage{\null\vfill\eject}

\parindent=0pt

\input pdfcolor.tex     % simple macros to use color with pdftex;
                        % color names derived from dvicolor.tex

% Unless mentioned explicitly, the default values of new parameters
% are: 1) zero for integer/dimension parameters; 2) empty for tokens
% parameters.

% In previous versions of pdfTeX, integer parameters took their corresponding
% values from pdftex.cfg config file. Starting from pdfTeX 1.20, the config file
% id not read at all. All the parameters are specified in TeX code, optionally
% dumped into format file.

\pdfoutput=1            % positive value turns on PDF output;
                        % this parameter can not be changed after the pdf
                        % output has been opened

\pdfcompresslevel=0     % compression level for text and image; allowed
                        % values are 0..9;
                        % 0 = no compression
                        % 1 = fastest compression
                        % 9 = best compression
                        % 2..8 = something between
                        % numbers out of range will be fixed to the most
                        % closed allowed value. Recommended value for most
                        % cases is 6 or 7.

\ifversion 1.40.0
 \pdfobjcompresslevel=0 % having pdfTeX 1.40.0 or higher and PDF 1.5 or higher,
                        % we can also control non-stream compression level. See
                        % pdfTeX manual for details.
\fi

\pdfdecimaldigits=3     % number of digits after decimal point for real
                        % number in pdf output; the larger value the
                        % better accuracy but also larger output size;
                        % allowed range of values is 0..4

%\pdfmovechars=2         % 1 turns on moving lower chars 0..32 to higher
                        % slots for fonts with last char code < 128,
                        % 2 or larger even for fonts with last char code > 127
                        % (rather obsolete)

\pdfpkresolution=300    % resolution for bitmap (PK) fonts; allowed values
                        % are 72..1200, default is 600

\pdfuniqueresname=0     % positive value turns on prepending unique
                        % prefix for each named resources
                        % pdftex-0.14[ef] has a bug with this feature
                        % turned on

% dimension parameters

\pdfhorigin=1in         % horizontal origin (offset);
                        % for common purposes it is advised to use
                        % \hoffset

\pdfvorigin=1in         % vertical origin (offset); similar to \pdfhorigin,
                        % advised to use \voffset


\pdfpagewidth=8.5in     % paper size of the pdf output (letter in this case)
\pdfpageheight=11in

\pdflinkmargin=1pt      % margin added to dimensions of link (see below)

\pdfdestmargin=10pt     % margin added to dimensions of destination (see
                        % below)

\pdfthreadmargin=1em    % margin added to dimensions of bead in article thread
                        % (see below)

% tokens registers

\pdfpagesattr={/MyPageAttribute /MyValue}
                        % optional attributes for the root Pages object;
                        % all pages inherit these attributes

\pdfpageattr={/MyPagesAttribute /MyValue}
                        % optional attributes for individual pages;
                        % attributes specified here overwrite any
                        % attributes given by `\pdfpagesattr' (see PDF spec for details)

\pdfpageresources{/MyPageResourceAttribute /MyValue}
                        % optional page resources dict content

% And some more parameters that need special care.

\ifversion 1.30.0 \else
 \let\pdfforcepagebox\pdfoptionalwaysusepdfpagebox
\fi

\pdfforcepagebox=0        % a page box of PDF inclusions to be used
                          % as a clipping area. Here we use default (CropBox)
                          % \pdfforcepagebox is a shortened synonym of
                          % obsolete \pdfoptionalwaysusepdfpagebox.

\ifversion 1.30.0 \else
 \let\pdfminorversion\pdfoptionpdfminorversion
\fi

\pdfminorversion=5        % version of created PDF files and allowed PDF inclusions.
                          % The default value is 4 that is enough in most cases (PDF 1.4).
                          % However, some pdfTeX features presented here requires
                          % PDF 1.5. Starting from pdfTeX 1.30.0, the command is called
                          % \pdfminorversion.



\ifversion 1.30.0 \else
 \let\pdfinclusionerrorlevel\pdfoptionpdfinclusionerrorlevel
\fi

\pdfinclusionerrorlevel=0 % If the version of included PDF is greater than
                          % the one being typeset, by default an error is issued.
                          % If \pdfinclusionerrorlevel is set to one, warning only
                          % (synonym of obsolete \pdfoptionpdfinclusionerrorlevel).

\ifversion 1.30.0
\pdfimagehicolor=1      % enables 16-bit colors for PNG inclusions;
                        % defaults to 1 if \pdfminorversion>=5,
\pdfimageapplygamma=1   % enables gamma correction for PNG inclusions,
\pdfgamma=1000          % sets pdfTeX `device gamma,'
\pdfimagegamma=2200     % sets image gamma, if can't be taken from the image itself.
\fi                  % (see below for details).

% Version of pdftex can be accessed via \pdftexversion and \pdftexrevision.

This is version \the\pdftexversion\ (revision \pdftexrevision) of \pdfTeX.

% Version of created PDF (and the highest allowed version of PDF inclusions)
% can be controlled with \pdfminorversion. In pdfTeX versions below 1.30.0, the
% primitive was called \pdfoptionpdfminorversion.

This file is PDF version 1.\the\pdfminorversion.
\bigskip

% Font resource in the pdf output has the form
% "/F<number> <object number> 0 R", where <number> is accessible via
% \pdffontname and <object number> via  \pdffontobjnum.

Font \fontname\font\ has resource name tag
\pdffontname\font\ and object number \pdffontobjnum\font\ in the PDF output.
Font size is \pdffontsize\font.\par

\feature 1.30.0 {Disabling ligatures}

Ligatures: ffont, fint, flint\par
{\font\noli=cmr10 at\pdffontsize\font
 \pdfnoligatures\noli No ligatures: ffont, fint, flint}
\bigskip

\endfeature

% \pdfincludechars can be used to ensure certain characters to be
% included in the font file. Normally only used characters are
% included (subset is created).

\pdfincludechars\font{ABCDEF}

% pdfTeX ignores \special's text if \pdfoutput is set, unless they have
% prefix "pdf:" or "PDF:"  (in this case the prefix is not written out, of
% course). \pdfliteral is intended to replace \special in pdf output mode.

Changing color can be done by inserting `raw' PDF code, like
\pdfliteral direct {0 1 1 0 k} % switch color to cmyk red
this.

\special{PDF:0 g}           % switch color back to black; \special can be
                            % used with prefix "pdf:" or "PDF:", optionally appended with
                            % "direct:"
                            % A `direct' keyword is optional; it ensures that what one
                            % types into \pdfliteral is inserted literally indeed.
                            % Otherwise pdfTeX moves the space origin to the place after
                            % the last types item on the page, inserts the user code and
                            % restores its internal position. It's recommended to use \pdfliteral
                            % instead of \special

A simple picture:
\pdfliteral {q 1 j 0 1 0 rg 0 0 1 RG 0 0 10 10 re B Q}

% pdfTeX keeps the origin point of coordinates in the lower-left corner of the
% page (native PDF space origin). \pdfliteral used without `direct' keyword
% moves this position temporarily to the point user probably expect; current
% position on the page. That is why the rectangle above appears in-line.
% Drawing anything relative to the page origin is a bit problematic. In most
% cases, one can't simply say `\pdfliteral direct {q <paiting operators> Q}'.
% That is because q..Q operators can't appear inside BT..ET blocks.
%
% Starting from pdfTeX 1.30.0, another \pdfliteral modifier can be used instead
% of `direct'. If the keyword is `page', pdfTeX closes internal text block with `ET'
% before putting the literal content; like with `direct', without translation.

\feature 1.30.0 {\cs\pdfliteral{ \tt page} keyword}
...and now look at the lower-left corner of the page.\par
\pdfliteral page {q 1 j 0 1 0 rg 0 0 1 RG 0 0 10 10 re B Q}
\pdfliteral page {q -1 0 0 1 612 0 cm .5 g}\hfill Do you like that?\pdfliteral page {Q}
\endfeature

% Every page in PDF document has its own graphic state, automatically restored
% by the viever application. In example, unless set explicitly, text colour at
% the beginning of the every page is always black, regardless the text color at
% the end of the previous page. This may be a little bit confusing for those
% who get used to dvi output and color macros based on Postscript specials. In
% the case of PDF, passing text colour (as well as any other graphic
% properties) between pages requires much more care. Since normally we don't
% know where TeX is going to break tyhe page, one probably need to use \mark(s)
% register(s) for page-wise graphic stack, as it is in pdfcolor.tex macro input above.

\feature 1.40.0 {Graphic stack}
\def\pdfsetcolor#1{}% disable generic color support of pdfcolor.tex

% pdfTeX 1.40.0 introduces graphic stack support. \pdfcolorstackinit primitive
% introduces new graphic stack and returns its number. Here we create a
% page-wise color stack with black as an initial stack value. \pdfcolorstack
% command operates on graphic stacks.

\chardef\Color=\pdfcolorstackinit page direct{0 g}
default color,
\pdfcolorstack\Color set{1 1 0 0 k}
some new default
\pdfcolorstack\Color push{0 1 1 0 k}
red,
\pdfcolorstack\Color push{1 0 1 0 k}
green,
\vfill\eject
still green,
\pdfcolorstack\Color pop
red again,
\pdfcolorstack\Color pop
default again,
\pdfcolorstack\Color set{0 g}
back to black.

\endfeature

\bigskip

% User-defined object can be inserted into the pdf output by \pdfobj. The
% object is written out as specified, apart from case when \pdfobj is used with
% "stream" option. An object created by \pdfobj is held in memory and will
% not be written to the pdf output, unless 1) the object is referenced by
% saying \pdfrefobj <object number>; or 2) \pdfobj is preceded by
% \immediate. The object number of the last object created by \pdfobj is
% accessible via \pdflastobj

\pdfobj{(Hello)}            % the simplest case: a string "Hello"
\pdfrefobj \pdflastobj      % mark the object to be written out; it can be
                            % understood as a reference to the object

% Note, that the object you type must comply the syntax of one of PDF data
% types (dictionary, array, string, stream, number, ...). The object created
% with `\pdfobj{Hello}' is incorrect and may lead to parser crash. This issue
% may not be noticed until one try to refer to the object anyhow or compress it
% using non-zero \pdfobjectstreams.

\immediate \pdfobj stream   % create the object as a stream a write it to
   {Hello}                  % the pdf output immediately

\pdfobj stream              % create the object as a stream with
    attr {/MyStreamAttribute /MyValue} %  additional attributes
    {Hello}
\pdfrefobj \pdflastobj

\pdfobj file {obj.dat}      % read the object contents from file obj.dat
\pdfrefobj \pdflastobj

\pdfobj stream              % read the stream contents from file obj.dat
    file {obj.dat}
\pdfrefobj \pdflastobj

\pdfobj stream              % read the stream contents from file obj.dat
    attr {/MyStreamAttribute /MyValue} % with additional attributes
    file {obj.dat}
\pdfrefobj \pdflastobj

% \pdflastobj is always global, as all others \pdflast* read-only integers (see
% below). PDF object numbers are unique within the document. One may notice, that
% if \pdfobj is preceded by \immediate, \pdflastobj seems to return subsequent
% values (i.e 5,6,7,8...). Since \pdfobj is not the only command that creates PDF
% objects, one can't simply assume, that if current \pdflastobj returns 5, the
% next one will always return 6. Thus, pdfTeX provides a forward-referencing
% mechanism (introduced in pdfTeX 1.20).

\feature 1.20 {Forward object referencing}

\pdfobj reserveobjnum
We have an access to PDF object numbers, even before defining those objects.
\pdfobj useobjnum\pdflastobj {(This is object number \the\pdflastobj)}
\pdfrefobj\pdflastobj

\endfeature

% TeX boxes can be written into so-called XObject form, which is very
% similar to a normal page in the pdf output. Additional data can be
% inserted to the XObject form dictionary itself as well as the Resource
% dictionary of the XObject form

\setbox0=\hbox{This is a box saved as a XObject form}
\pdfxform
   attr      {/MyXObjectFormAttribute         /MyValue}
   resources {/MyXObjectFormResourceAttribute /MyValue}
   0

% Similarly to \pdfobj, the object created by \pdfxform is held in memory
% and is not written to the pdf output, unless 1) the object is referenced
% by saying \pdfrefxform <object number>; or 2) \pdfxform is preceded by
% \immediate. The object number of the last XObject form created
% by \pdfxform is accessible via \pdflastxform. Note that
% \immediate\pdfxform does not typeset anything; it just ensures that the
% XObject form is written out to the output. To display the form, it is
% necessary to say \pdfrefxform <object number> in the intended place.
% Another point is that \pdfrefxform acts similarly rather to rules than to
% boxes concerning dimensions and space setting. It's highly recommended to
% wrap \pdfrefxform by a box in order to ensure spacing will be correct.

\hbox{\pdfrefxform \pdflastxform}

% Similarly to \pdflastobj, \pdflastxform returns the PDF object number assigned
% for XObject form just created. pdfTeX also provides \pdfxformname primitive, that
% returns a resource name identifier of the XObject written to PDF output with given
% object number.

XObject above has been written as object \the\pdflastxform.

\feature 1.30.0 {Access to XObject names}

Its resource name tag is \pdfxformname\pdflastxform\
({\tt/Fm\pdfxformname\pdflastxform\ \the\pdflastxform\space 0 R}
entry in page resources dictionary).

\endfeature

\bigskip

% Thanks to Taco Hoekwater pdfTeX 1.30.0 and higher provides precise time
% measuring mechanism. \pdfelapsedtime primitive returns the time elapsed from
% the current run start. Time is measured in `scaled seconds' meaning that 65536
% scaled seconds is 1 second. There is also \pdfresettimer primitive that causes
% zeroing the internal clock.

{\catcode`\p=12 \catcode`\t=12 \gdef\WITHOUTPT#1pt{#1}}
 \def\withoutpt#1{\expandafter\WITHOUTPT#1} % returns float-like string

\feature 1.30.0 {Precise timer}

\dimen0=\pdfelapsedtime sp
\pdfresettimer
It took \withoutpt\the\dimen0 \ seconds to typeset the whole stuff above.
To typeset the last two sentences it took \the\pdfelapsedtime\ `scaled seconds'
(1s/65536).
\bigskip

\endfeature

% Taco Hoekwater has also implemented random number support (introduced in 1.30.0)

\feature 1.30.0 {Random numbers}

Random seed initialized to \the\pdfrandomseed.
\pdfsetrandomseed\dimen0 % just saved elapsed time
We may change it, lets say to \the\pdfrandomseed.\par

10 uniformly distributed random numbers [0..100]:
\count100=0 \loop
 \pdfuniformdeviate101
 \advance\count100 by1
 \ifnum\count100<10,
\repeat.\par

10 normally distributed random numbers:
\count100=0 \loop
 \dimen0=\pdfnormaldeviate sp
 $\withoutpt\the\dimen0$%
 \advance\count100 by1
 \ifnum\count100<10,
\repeat.\par

\bigskip

\endfeature

% Starting from pdfTeX 1.30.0, there is an expandable string comparison in pdfTeX.
% You can compare two strings lexicographically using \pdfstrcmp{<str1>}{<str2>}.
% The command returns -1, 0, or 1 as a comparison result.
% Both strings are expanded before being compared.
% \feature 1.30.0 {String comparison}
% \pdfstrcmp{a}{aa}    returns -1 since 'a'<'aa'
% \pdfstrcmp{aa}{aa}   returns 0  since 'aa'='aa'
% \pdfstrcmp{aaa}{abc} returns -1 since 'aaa'<'abc'
% \pdfstrcmp{abc}{ABC} returns 1  since 'aaa'>'ABC'
% \endfeature
% This is still experimental, as well as regex support.

% Starting from version 1.40.0 there are two handy primitives for absolute
% values comparison. This is e-TeX however...
% \feature 1.40.0 {Absolute \cs\if's}\fi\endfeature

% Thanks to Heiko Oberdiek, starting from pdfTeX 1.30.0 a set of expandable
% string handlers are available. \pdfescapestring converts its parameter into a
% form readable for PDF interpreters, escaping those characters that can be used
% in PDF string objects without quotation. Similarly, \pdfescapename converts its
% argument into PDF name, replacing special PDF characters with their hexadecimal
% representation preceded by `#'. \pdfescapehex takes an ASCII code of each
% character of its argument and converts this number into hexadecimal form. Last
% but not least, \pdfunescapehex treats each pair of characters as a hexadecimal
% number and returns an ASCII characters of given codes. All those commands
% expand their arguments before applying conversion.

\feature 1.30.0 {PDF string handling}

\def\sometext{Some text/(1)}
If there is a text `{\tt\sometext}',\par
in PDF string one should use {\tt(\pdfescapestring{\sometext}},\par
and in PDF name it would be  {\tt/\pdfescapename  {\sometext}}.\par
In hex form it looks like {\tt<\pdfescapehex{\sometext}>},\par
but you can always reverse it to get {\tt\pdfunescapehex{\pdfescapehex{\sometext}}}.
\bigskip

\endfeature

% Also handling external files has been greatly improved. Starting from pdfTeX 1.30.0
% you can check external files modification date, file size and even md5 check sum.

\feature 1.30.0 {External file handling}

The source of this document is {\tt\pdffilesize{\jobname}} bytes long. Last modification date
is {\tt\pdffilemoddate{\jobname}}. The md5 sum is {\tt\pdfmdfivesum{\jobname}}.
Bytes 7 to 13 of the source are hex {\tt\pdffiledump offset 7 length 7{\jobname}}
(string `\pdfunescapehex{\pdffiledump offset 7 length 7 {\jobname}}').

\endfeature

% \pdfsavepos saves coordinates of the current position (basepoint) on the page
% relative to lower-left corner. \pdflastxpos and \pdflastypos are available
% while shipping out the page. Both are integers; the position is expressed in
% scaled points. Starting from pdfTeX 1.40.0, availavle also in DVI mode.

\pdfsavepos
\write16{Position: X=\number\pdflastxpos sp, Y=\number\pdflastypos sp.}

\newpage

% pdfTeX 1.20 and higher allows to get the object number of already typeset page

\feature 1.20 {Page object reference}

The previous page has been written as object \pdfpageref1.

\endfeature

% Images can be included with pdftex using \pdfximage. Supported formats
% are determined by file name extension:
%   .pdf/.PDF:              PDF
%   .png/.PNG:              PNG
%   .jpg/.JPG/.jpeg/.JPEG:  JPEG
%
% Sorry, TIFF files are no longer supported.
%
% pdfTeX itself does not support EPS and Postscript codes at all, however
% it's possible to include Metapost output. EPS files can be converted to
% PDF for use with pdfTeX. See below for further info about using Metapost
% and EPS.

\pdfximage {pic.pdf}    % read image pic.pdf (search for it in TEXINPUTS path)

% It also possible to select which page to include. Pages are numbered from
% 1. Out-of-range values are fixed to 1 and bitmapped images have always 1
% page. To include let's say the 2nd page of a pdf image, one can use
% \pdfximage page 2 {file.pdf}

% Similarly to \pdfobj, the image created by \pdfximage is held in memory
% and is not written to the pdf output, unless 1) the image is referenced
% by saying \pdfrefximage <object number>; or 2) \pdfximage is preceded by
% \immediate. The object number of the last image created by \pdfximage is
% accessible via \pdflastximage. Note that \immediate\pdfximage does not
% typeset anything; it just ensures that the image is written out to the
% output. To display the image, it is necessary to say
% \pdfrefximage <object number> in the intended place. Another point is
% \pdfrefximage act similarly rather to rules than to boxes concerning
% dimensions and space setting. In order to make images act as boxes
% (concerning dimensions and spacing), it's necessary to wrap them into a
% box.

\hbox{\pdfrefximage \pdflastximage}

% Since a pdf image may have more than 1 page, the number of the last image
% opened by \pdfximage is accessible via \pdflastximagepages

The last image has \the\pdflastximagepages\ page(s).

% The dimensions of the image can be also controlled via <rule spec>. The
% default values are zero for depth and `running' for height and width. If
% all of them are given, the image will be scaled to fit the specified
% values. If some of them (but not all) are given, the rest will be set to
% a value corresponding to the remaining ones so as to make the image size
% to yield the same proportion of width : (height + depth) as the original
% image size, where depth is treated as zero. If none of them is given then
% the image will take its natural size. An image inserted at its natural
% size often has a resolution of \pdfimageresolution (or 72 if
% \pdfimageresolution is set to zero) given in dots per inch in the output
% file, but some images may contain data specifying the image resolution,
% and in such a case the image will be scaled to the original resolution.
% The dimension of the image can be accessed by enclosing the \pdfrefximage
% command to a box and checking the dimensions of the box.

\pdfximage width 6cm {pic.pdf}  % set the image width and keep the
\pdfrefximage \pdflastximage    % `nature' proportion width : height

\pdfximage height 4cm {pic.png} % set the image height and keep the
                                % `nature' proportion width : height

\edef\MyImg{\the\pdflastximage} % save the image number for later reuse
\pdfrefximage\MyImg

\pdfximage width 6cm height 4cm % set both image width and height; the
   {pic.jpg}                    % final proportion width : height may be
                                % different from the `nature' one

\pdfimageresolution=72          % to open an image at 72 dpi
\pdfximage {pic.pdf}
\setbox0=\hbox{\pdfrefximage\pdflastximage} % get dimensions of the image
                                            % in order to include the image
                                            % at a specific resolution
\dimen0=.06\wd0         % calculate the image width at 1200 dpi (0.06 = 72/1200)
\pdfximage              % include the image at resolution 1200 dpi
    width \dimen0 {pic.pdf}  % by setting image width to the calculated value
\pdfrefximage \pdflastximage

% While working with bitmap graphic it might be more convenient to operate on
% pixels rather then dimension units. Starting from version 1.30.0, pdfTeX offers
% a special, scalable unit called `px'. The real value associated with `px' is controlled
% via \pdfpxdimen primitive. It used to be a count register defaulted to 65536 (1pt = 1px).
% Starting from pdfTeX 1.40.0, \pdfpxdimen is a true dimen defaulted to 1bp, that implies
% 72dpi resolution.


\feature 1.30.0 {Scalable {\tt px} unit}

\ifversion 1.40.0
 \pdfpxdimen=0.06bp % 1200dpi -> 72/1200
\else
 \pdfpxdimen=3946   % 1200dpi -> 72*65781/1200
\fi

640 pixels in 1200dpi makes \dimen0=640px \the\dimen0.

\endfeature


% ... Be aware of rounding error significant for large resolutions
% 1200 pixels in 1200dpi makes \dimen0=1200px \the\dimen0. -> 72.25342pt < 72.27

\newpage

% While embedding PDF image one may decide which area of the image (mediabox,
% cropbox, bleedbox, trimbox or artbox) should be treated as a final (visible)
% bounding box. There is \pdfoptionalwaysusepdfpagebox parameter that specifies
% the default behaviour (1 for mediabox, 2 for cropbox, 3 for bleedbox, 4 for
% trimbox and 5 for artbox). For sake of backward compatibility, if set to 0
% cropbox is used. Starting from pdfTeX 1.30.0, a synonym \pdfforcepagebox is
% used. One may also override the default settings by providing page box
% specification in \pdfximage syntax. In example, \pdfximage trimbox {<file>}
% causes clipping the image to the trimbox area. Obviously, those settings take an
% effect only if the desired box page is defined in the image being included.
% According to PDF spec, PDF page boxes act as follows:
%  mediabox % the entire page area (the only one always present)
%  cropbox  % the visible page area (defaults to mediabox)
%  bleedbox % the page area with trimming margins (defaults to cropbox)
%  trimbox  % the page area without bleeds (defaults to cropbox)
%  artbox   % the logical page content (defaults to cropbox)

% pdfTeX takes care about version of included PDF images. By default, an error is
% issued if this version is newer than the PDF being created (controlled by
% \pdfminorversion). If the \pdfoptionpdfinclusionerrorlevel is set to 0, only
% warning is issued. Starting pdfTeX 1.30.0 \pdfinclusionerrorlevel synonym is used
% instead.

% Thanks to Taco Hoekwater pdfTeX 1.30.0 and higher provides advanced PNG
% inclusions handling. Nonzero \pdfimagehicolor parameter enables embedding
% of PNG images with 16 bit wide color channels at their full color resolution.
% This functionality is automatically disabled if \pdfminorversion<5, and automatically
% enabled if \pdfminorversion>=5
% Another primitive -- \pdfimageapplygamma -- enables gamma correction of embedded
% PNG files on the base of two parameters:
%   \pdfgamma      % device gamma for pdfTex
%   \pdfimagegamma % image gamma (used if one can't be derived from the image)
% Both values are integers measured in promile (1000 = gamma 1.0)
% All the parameters of gamma correction have to be set before any data
% is written to the PDF output; thus we put them at the very beginning of this sample.

% \ifx\undefined\quitvmode % primitive `\leavevmode' introduced in pdfTeX 1.30.0
%  \let\quitvmode\leavevmode
% \fi

\pdfximage width8cm {pic16.png}%
\pdfrefximage\pdflastximage
The image had originally 16 bits-per-channel.

\feature 1.21 {Image color depth info}
Embedded one has \the\pdflastximagecolordepth\ bits-per-channel;
\endfeature

\feature 1.30.0 {16-bit color mode for PNG inclusions}
the image has been read in 16-bit color resolution.
\endfeature

\feature 1.30.0 {Gamma correction}
Try out different gamma parameters. % we have to set them before any data
\endfeature                         % is written to the output

\bigskip

% From pdfTeX 1.21 \pdfximage command can be followed by `colorspace <objnum>',
% where <objnum> is a number of user-defined color space object. Simply speaking,
% we may instructs the viewer, how the image should be rendered. However, this
% works only for JPEGs. Here we perform some sort of `color management' by
% applying a color profile to the JPEG image.

% Be aware; this is viewer dependent.

\feature 1.21 {User-defined image color space hook}

\immediate\pdfobj
  stream
  attr {/N 3 /Alternate /DeviceRGB}
  file {rgb.icc} % color profile

\immediate\pdfobj{[/ICCBased \the\pdflastobj\space 0 R]}

\edef\objnum{\the\pdflastobj}

\pdfximage width 8cm colorspace\objnum {pic.jpg}
\pdfrefximage\pdflastximage
The image is calibrated with ICC profile.

\immediate\pdfobj
 stream attr
 {/FunctionType 4
  /Domain [0 1 0 1 0 1]
  /Range  [0 1 0 1 0 1]}{{exch pop exch pop 0 exch 0 exch}}

\immediate\pdfobj % don't treat it serious %)
 {[/DeviceN [/Red /Green /Blue] /DeviceRGB \the\pdflastobj\space 0 R]}

\edef\objnum{\the\pdflastobj}

\pdfximage width8cm colorspace\objnum {pic.jpg}
\pdfrefximage\pdflastximage
Hacked image color space.

\endfeature

\newpage

% Thanks to Hans Hagen pictures created by Metapost can be easily used with
% pdftex. The following files come from ConTeXt distribution. Another
% place to get them is http://www.tug.org/applications/pdftex/, where
% is also possible to get the latest driver file for using LaTeX graphicx
% package with pdftex.

\input supp-mis.tex     % supp-mis.tex is loaded by supp-pdf.tex
\input supp-pdf.tex     % automatically, so the above line could be left
                        % out (it's given here to make clear what all files
                        % are needed to use \convertMPtoPDF)

% the figure cmr10.103 was created by running Metapost on cmr10.mf

%\convertMPtoPDF {filename} {x scale} {y scale}
%\convertMPtoPDF{cmr10.103}{1}{1}
\newpage

% It is possible to have Metapost code inside the tex sources and call
% Metapost to generate the figure before calling \convertMPtoPDF.

% define some contants that will be used in the Metapost code
\def\pointA{(50, 50)}
\def\pointB{(400, 250)}

\newwrite\mpfile    % temporary file for metapost code
\immediate\openout\mpfile = \jobname.mp

\immediate \write \mpfile {%
prologues := 1;
def drawleaf(expr A, B, C) =
    pickup pencircle scaled 4bp;
    draw (0, 0) {dir 60} .. A .. {dir 60} B withcolor C;
    pickup pencircle scaled 2bp;
    draw A {dir 75} .. {dir 45} B withcolor C;
    draw A {right} .. {dir 75} B withcolor C;
enddef;
beginfig(0);
    drawleaf(\pointA, \pointB, .6green);
    d := .5 xpart \pointB;
    currentpicture := currentpicture reflectedabout ((d, 0), (d, 1));
endfig;
beginfig(1);
    drawleaf(\pointA, \pointB, .6blue);
    currentpicture := currentpicture reflectedabout (\pointA, \pointB);
endfig;
end;
}
\immediate \closeout \mpfile    % close the file before running Metapost

% Now we call Metapost to generate the ps output; this is system-dependent
% and has been tested for web2c only. It is necessary to have
%
% shell_escape = t
%
% in texmf.cnf in order to run it.
%
% Starting from pdfTeX 1.21a, one may test if this option is enabled using
% \ifeof condition (distribution dependent):

\feature 1.21 {Shell escape detection (via \cs{ifeof})}
Shell escape (via \cs{ifeof}) seems to be
\ifeof18 disabled\else enabled\fi.
\endfeature

% ...pdfTeX 1.30.0 introduces its own primitive integer flag

\feature 1.30.0 {Shell escape detection (via \cs\pdfshellescape)}
Shell escape (via \cs\pdfshellescape) seems to be
\ifnum\pdfshellescape=1 disabled\else enabled\fi.
\endfeature

% Uncomment line below, if there is Metapost available in your system (should be!)
% \immediate \write 18 {mpost \jobname.mp} % call Metapost on \jobname.mp
\convertMPtoPDF{\jobname.0}{1}{1}
\convertMPtoPDF{\jobname.1}{1}{1}

\newpage

% EPS pictures cannot be inserted directly by pdfTeX, but it's possible to
% convert them to PDF using a Postscript-to-PDF converter, like Acrobat
% Distiller or Ghostscript. The below example calls epstopdf (available
% from http://www.tug.org/applications/pdftex), which preprocess the EPS
% and afterwards uses Ghostscript to convert to PDF. In order to convert
% EPS with embedded Type 1 fonts, a later version (beta) of Ghostscript is
% required.

% Uncomment line below, if there is epstopdf utility available in your system

%\immediate \write 18 {epstopdf --outfile=tmp.pdf cmr10.103} % call epstopdf
\pdfximage height \vsize {tmp.pdf}      % insert the PDF converted from EPS
\topskip=0pt
\pdfrefximage \pdflastximage
\newpage

% some text to try using threads

\def\text{%
Ah! perhaps a burning match might be some good, if she could draw it from
the bundle and strike it against the wall, just to warm her fingers. She
drew one out---"scratch!" how it sputtered as it burnt! It gave a warm,
bright light, like a little candle, as she held her hand over it. It was
really a wonderful light. It seemed to the little girl that she was sitting
by a large iron stove, with polished brass feet and a brass ornament. How
the fire burned! and seemed so beautifully warm that the child stretched
out her feet as if to warm them, when, lo! the flame of the match went out,
the stove vanished, and she had only the remains of the half-burnt match in
her hand.

    She rubbed another match on the wall. It burst into a flame, and
where its light fell upon the wall it became as transparent as a veil,
and she could see into the room. The table was covered with a snowy
white table-cloth, on which stood a splendid dinner service, and a
steaming roast goose, stuffed with apples and dried plums. And what
was still more wonderful, the goose jumped down from the dish and
waddled across the floor, with a knife and fork in its breast, to
the little girl. Then the match went out, and there remained nothing
but the thick, damp, cold wall before her.

    She lighted another match, and then she found herself sitting
under a beautiful Christmas-tree. It was larger and more beautifully
decorated than the one which she had seen through the glass door at
the rich merchant's. Thousands of tapers were burning upon the green
branches, and colored pictures, like those she had seen in the
show-windows, looked down upon it all. The little one stretched out
her hand towards them, and the match went out.

    The Christmas lights rose higher and higher, till they looked to
her like the stars in the sky. Then she saw a star fall, leaving
behind it a bright streak of fire. "Some one is dying," thought the
little girl, for her old grandmother, the only one who had ever
loved her, and who was now dead, had told her that when a star
falls, a soul was going up to God.

    She again rubbed a match on the wall, and the light shone round
her; in the brightness stood her old grandmother, clear and shining,
yet mild and loving in her appearance. "Grandmother," cried the little
one, "O take me with you; I know you will go away when the match burns
out; you will vanish like the warm stove, the roast goose, and the
large, glorious Christmas-tree." And she made haste to light the whole
bundle of matches, for she wished to keep her grandmother there. And
the matches glowed with a light that was brighter than the noon-day,
and her grandmother had never appeared so large or so beautiful. She
took the little girl in her arms, and they both flew upwards in
brightness and joy far above the earth, where there was neither cold
nor hunger nor pain, for they were with God.
}

\pdfannot               % generic annotation
                        %
    width 10cm          % the dimension of the annotation can be controlled
    height 0cm          % via <rule spec>; if some of dimensions in
    depth  4cm          % <rule spec> is not given, the corresponding
                        % value of the parent box will be used.
{                       %
    /Subtype /Text      % text annotation
    % /Open true        % if given then the text annotation will be opened
                        % by default
    /Contents           % text contents
        (This text is from THE LITTLE MATCH-SELLER by Hans Christian
         Andersen)
}

\def\colsep{\qquad}          % column separator
\setbox0=\vbox{%
    \baselineskip=1.2em plus 1pt minus 1pt
    \hsize=2in
    \tolerance=1000
    \rightskip=0pt plus 1em
    \hfuzz=1em
    \parskip=\baselineskip
    \null                   % will use \vsplit to remove this null box and
                            % insert \splittopskip glue to top of the
                            % first column. I don't know how to make the
                            % first column have the same height as other
                            % columns so have to use this trick to ensure
                            % that all columns will have \splittopskip glue
                            % properly inserted at the top
    \text
    \vfil}

\setbox1=\vsplit0 to 0pt    % remove the null box and insert \splittopskip glue
\setbox3=\copy0             % make a copy of box0 for later use

% Using thread by explicit determination which boxes will belong to a thread

\setbox2=\hbox{}
\loop
    \setbox1=\vsplit0 to .75\vsize
    \setbox2=\hbox{\unhbox2 \vtop{%
        \pdfthread          % add a bead to the thread with id=`num 1' (given
                            % below)
            % <rule spec>   % dimensions of the bead can be controlled
                            % via <rule spec>; if some of dimensions in
                            % <rule spec> is not given, the corresponding
                            % value of the parent box will be used. If
                            % \pdfthreadmargin is not zero then its value
                            % will be added to the margins of the bead
                            %
                            % additional attributes of thread
            attr {/I <</Title (THE LITTLE MATCH-SELLER by Hans Christian)>>}
                            %
                            % identifier specification (exactly one of the
                            % following must be specified):
                            %
            num 1           % num identifier (must be positive), or
          % name {thread1}  % name identifier; \pdfthread with the same id
                            % will be joined together. Attributes of the
                            % final thread is the last one if any was
                            % given.
        \unvbox1}\colsep}
\ifdim \ht0 > 0pt \repeat
\box2

\newpage

% Using thread by automatic determination which boxes will belong to a
% thread; \pdfstartthread has the same syntax as \pdfthread, apart that it
% must be followed by a \pdfendthread. \pdfstartthread and the
% corresponding \pdfendthread must end up in vboxes with the same
% nesting level; all vboxes between them with the same nesting level will
% be added into the thread. Note that during output routine if there are
% other newly created boxes which have the same nesting level as vboxes
% containing \pdfstartthread and \pdfendthread, they will be also added
% into the thread, which is probably not what we want. To avoid such
% unconsidered behaviour, it's often enough to wrap the box that shouldn't
% belong to the thread by another box to change the nesting level.

\setbox0=\vbox{%
    \pdfstartthread
        attr {/I <</Title (THE LITTLE MATCH-SELLER by Hans Christian)>>}%
        name {thread2}%
    \unvbox3
    \pdfendthread
}
\setbox2=\hbox{}
\loop
    \setbox1=\vsplit0 to .75\vsize
    \setbox2=\hbox{\unhbox2 \vtop{\unvbox1}\colsep}
\ifdim \ht0 > 0pt \repeat
\box2

\newpage

\pdfdest                % destination for link and outlines
                        %
                        % identifier specification (exactly one of the
                        % following must be specified):
                        %
    num 1               % num identifier (must be positive), or
  % name {dest1}        % name identifier. Must be unique in one document
                        %
                        % appearance of destination (exactly one of the
                        % following must be specified):
                        %
    fit                 % fit whole page in window
  % fith                % fit whole width of page
  % fitv                % fit whole height of page
  % fitb                % fit whole "Bounding Box" page
  % fitbh               % fit whole width of "Bounding Box" of page
  % fitbv               % fit whole height of "Bounding Box" of page
  % fitr <rule spec>    % fit the rectangle specified by <rule spec>; if
                        % some of dimensions in <rule spec> is not given,
                        % the corresponding value of the parent box will be
                        % used. If \pdfdestmargin is not zero then its
                        % value will be added to the margins of the
                        % rectangle
  % xyz                 % goto the current position

This is a page containing destination `num 1'

\newpage

% \pdfstartlink and \pdfendlink are similar to \pdfstartthread and
% \pdfendthread, but they must end up in hboxes instead of vboxes

\leftline{This is a link to destination
\pdfstartlink           % start a link
                        %
    height 10pt         % dimensions of the link can be controlled
    depth 3pt           % via <rule spec>; if some of dimensions in
                        % <rule spec> is not given, the corresponding
                        % value of the parent box will be used. If
                        % \pdflinkmargin is not zero then its value
                        % will be added to the margins of the link
                        %
    attr{/C [0.9 0 0]   % additional attributes of link
    /Border [0 0 2]}    %
                        %
                        % action specification (exactly one of the
                        % following must be specified):
                        %
   goto                 % goto action
                        %
       % file{file.pdf} % optional file specification; can be used only with
                        % `goto' action or `thread' action (see below). If
                        % action identifier is name then there should be a
                        % destination or a thread with same name identifier
                        % in the file; if action identifier is number then it
                        % means page number for `goto' action (in this case it
                        % will take effect as `fitb' specification) and index
                        % number of thread for `thread' action (the first
                        % thread in a document has index number 0)
                        %
                        % goto action identifier (exactly one of the following
                        % must be specified):
                        %
         num 1          % goto destination with num identifier
       % name{dest1}    % goto destination with name identifier
       % page 1 {/Fit}  % goto page 1 and fit the whole page
                        %
                        %
  % thread              % thread action; start to read a thread
                        %
        %file{file.pdf} % optional file specification
                        %
                        % thread action type (exactly one of the following
                        % must be specified):
                        %
       % num 1          % read thread with num identifier id=`num 1'
       % name{thread2}  % read thread with name identifier id=`name{thread2}'
                        %
                        %
  % user{               % user-defined action; a URI action can be specified
  %                     % as below
  %      /Subtype /Link
  %      /A <<
  %          /Type /Action
  %          /S /URI
  %          /URI (http://www.tug.org/)
  %      >>}
`num 1'%
\pdfendlink             % end of link; if \pdfstartlink and
                        % \pdfendlink end up in different hboxes (in this
                        % case the boxes must have the same box nesting
                        % level), all hboxes between them will be treated
                        % as part of the link. Line breaks and even page
                        % breaks are allowed between \pdfstartlink and
                        % \pdfendlink
}

\feature 1.40.0 {Last link object}
The link is object \the\pdflastlink.
\endfeature

% more link examples

\leftline{%
   This is a link to the
    \pdfstartlink
        goto
        page 1 {/FitB}% % goto the 1st page and fit the page BBox in the
                        % window
    first page%
    \pdfendlink}

\leftline{%
   This is a link to the
    \pdfstartlink
        thread num 1    % read the thread `num 1'
    thread `num 1'%
    \pdfendlink}

\leftline{%
    This is a link to
    \pdfstartlink
        attr{ /Border [0 0 0]}  % make the bbox of the link invisible
        user {%                 % a named action (undocumented in PDF spec)
            /Subtype /Link
            /A <<
                /S /Named
                /N /GoBack
            >>}%
    \Cyan the previous view\Black         % color text inside the link
    \pdfendlink}

\leftline{%
   This is a link to
    \pdfstartlink user{%
        /Subtype /Link
        /A <<
            /Type /Action
            /S /URI
            /URI (http://www.fi.muni.cz/)
        >>}%
    \Red our faculty\Black
    \pdfendlink}

{\hsize2in \raggedright \noindent
    This is an example of
    \pdfstartlink
        attr{ /Border [0 0 0]}  % make the bbox of the link invisible
        goto page 1 {/FitB}%
    \Red multiple line link. Make sure that the link and
    its end must be in horizontal mode and the parent boxes must have the
    same box nesting level.\Black
    \pdfendlink
    A common mistake here is using \cs{\pdfstartlink} at the
    beginning of the text without \cs{\indent}, \cs{\noindent}
    or \cs{\leavevmode}, so \cs{\pdfstartlink}
    will end up in vertical mode and cause an error.
    \par}

% A sound or movie annotation can be created as below. Using such kinds of
% annotation or Java script causes the pdf output to be system-dependent.
% More info about this topic can be found in PDF spec.

% \leftline{%
%     \pdfannot width 4in height 0in depth 3in {%
%         /Subtype /Movie
%         /Movie << /F (MovieFile.mov) >>}
%     An example of movie annotation}

% \leftline{%
%     \pdfannot width 0in height 0in depth 0in {%
%         /Subtype /Sound
%         /Sound << /F (SoundFile.wav) >>}
%     An example of sound annotation}

% \leftline{%
%     \pdfannot width 0in height 0in depth 0in {%
%         /Subtype /Movie
%         /Movie << /F (SoundFile.wav) >>}
%     Sound can be also embedded using Movie annotation}

% outlines (bookmarks):
\pdfoutline             % outline entry specification
                        %
    goto num 1          % action specification. This is the same as the action
                        % specification of `\pdfstartlink'
                        %
    count 3             % number of direct subentries of this entry, 0 if this
                        % entry has no subentries (in this case it may be
                        % omitted). If after `count' follows an negative number
                        % then all subentries will be closed and the absolute
                        % value of this number specifies the number of
                        % direct subentries (see the following entries)
                        %
    {Outline 1}         % text contents of outline entry

    \pdfoutline goto num 1 count -2{Outline 1.1}
        \pdfoutline goto num 1 {Outline 1.1.1}
        \pdfoutline goto num 1 {Outline 1.1.2}
    \pdfoutline goto num 1 {Outline 1.2}
    \pdfoutline goto num 1 {Outline 1.3}
\pdfoutline goto page 1 {/Fit} {Outline 2}

\newpage

% Transformations are done by changing transformation matrices. See PDF spec for
% more details how to use it. Generally, a transformation matrix is given as six
% real numbers followed by operator `cm'. Before doing any transformation we must
% store current graphic state (by operator `q') and restore it (by operator `Q')
% after transformation. `q' and `Q' operators acts more or less like `gsave' and
% `grestore' in Postscript. See examples below. Make sure that *no spacing*
% can be produced during transformation and afterwards we must adjust spacing `by
% hand'.

\font\f=cmb10 at 50pt
\setbox0=\hbox{\f Rotated text}
\setbox1=\hbox{\f Scaled text}
\setbox2=\hbox{\f Skewed text}

\newdimen\d
\newbox\tmpbox
\def\avoidboxdimen#1{%
    \setbox\tmpbox=\hbox{\box#1}%
    \wd\tmpbox=0pt
    \ht\tmpbox=0pt
    \dp\tmpbox=0pt
    \box\tmpbox}

\hrule

% rotation by `t' degrees counterclockwise is specified as
% `cos(t) sin(t) -sin(t) cos(t) 0 0'.
\vskip\wd0
\leftline{\hskip\ht0\hskip\dp0%
\pdfliteral{q 0 1 -1 0 0 0 cm}%
\avoidboxdimen 0
\pdfliteral{Q}}

\hrule

% scaling is specified as `Sx 0 0 Sy 0 0'
\d=\ht1 \advance\d by \dp1
\vskip3\d
\pdfliteral{q 2 0 0 3 0 0 cm}%
\avoidboxdimen 1
\pdfliteral{Q}%

\hrule

% skewing x-axis by `u' degrees and y-axis by `v' degrees is specified as
% `1 tan(u) tan(v) 1 0 0'.
\d=\ht2 \advance\d by \dp2
\vskip\d
\d=0.57735\wd2 %tan(30) = 0.57735
\pdfliteral{q 1 -0.57735 0 1 0 0 cm}%
\avoidboxdimen 2
\pdfliteral{Q}
\vskip\d

% For better understaing \pdfliteral rules, play with the transformations above using
% `direct' and `page' modifiers. Expect surprises, including corrupted output...

% One may already notice that any transformation applied to text or some other
% page graphic object do not affect active rectangles of links and other
% annotations. This is because those rectangles are kept in PDF as a different
% structure then the page content. pdfTeX is not aware of any transformation
% shown above (\pdfliteral content is not analyzed anyhow), so any annotation
% related to the box being transformed remains untouched.

% Check it out:
% \pdfliteral{q 0.87 -0.5 0.5 0.87 0 0 cm}
% \setbox0\hbox{\f\pdfstartlink goto page \pageno{/FitH}Link\pdfendlink}
% \avoidboxdimen0
% \pdfliteral{Q}

% pdfTeX 1.40.0 comes with three extra primitives that fixes this problem.
% \pdfsetmatrix primitive inserts first four numbers of the afine
% transformation matrix into the page content stream and updates annotations
% accordingly. \pdfsave saves the current matrix, \pdfrestore resores the
% previously saved matrix.

\bigskip

\feature 1.40.0 {Saving/restoring transformation matrix}

\setbox0\hbox{\f\pdfstartlink goto page \pageno{/FitH}Link\pdfendlink}
\pdfsave
\pdfsetmatrix{0.87 -0.5 0.5 0.87}
\avoidboxdimen0
\pdfrestore

\endfeature

% To have a smoothly readable PDF output one may use a newline character to
% separate entries written directly do PDF code. No matter for the viewer.

\def\n{^^J}

% If the file is modified are released oftenly (as this one) it might be convenient to
% keep trace of modification time. In pdfTeX 1.30.0 there is a
% \pdfcreationdate that returns a date of the file being created.
% Date is formated in PDF way.

\ifversion 1.30.0 \else

\count100=\time
\divide\count100 by60
\edef\pdfcreationdate{\ifnum\count100<10 0\fi\the\count100} % hours
\multiply\count100 by-60
\advance\count100 by\time
\edef\pdfcreationdate{%
  \pdfcreationdate
  \ifnum\count100<10 0\fi\the\count100 00} % minutes (seconds zeroed)
\edef\pdfcreationdate{%
  D:\the\year
  \ifnum\month<10 0\fi\the\month
  \ifnum\day<10 0\fi\the\day
  \pdfcreationdate} % time zone discarded

\fi

\pdfinfo{%                              % Info dictionary of PDF output;
                                        % all keys are optional.
    /Author (Han The Thanh)
  \n/CreationDate (D:20001212000000)    % (D:YYYYMMDDhhmmss)
                                        % YYYY  year
                                        % MM    month
                                        % DD    day
                                        % hh    hour
                                        % mm    minutes
                                        % ss    seconds
                                        %
                                        % default: the actual date
                                        %
  \n/ModDate (\pdfcreationdate)         % ModDate is similar
  \n/Creator (TeX)                      % default: "TeX"
  \n/Producer (pdfTeX)                  % default: "pdfTeX" + pdftex version
  \n/Title (samplepdf.pdf)              %
  \n/Subject (Example)                  %
  \n/Keywords (PDF TeX)                 %
}

\pdfcatalog{                            % Catalog dictionary of PDF output.
    /PageMode /UseOutlines              %
    /URI (http://www.fi.muni.cz/)       %
% pdfscreen-like setting might look like:
%     /PageMode /none
%     /ViewerPreferences <<
%         /HideToolbar true
%         /HideMenubar true
%         /HideWindowUI true
%         /FitWindow true
%         /CenterWindow true
%     >>
}
openaction goto page 1 {/Fit}           % the action to be activated when
                                        % opening the document; this is the
                                        % same as <action spec> for links
                                        % and outlines
\end
