How can I stamp all PDF pages with a rotated and centered text stamp?

257 views
Skip to first unread message

Support

unread,
Jul 19, 2007, 5:42:37 PM7/19/07
to PDFTron PDFNet SDK
Q:

How can I stamp all PDF pages with a rotated and centered text stamp?

----
A:

You can use the following utility function to stamp the pages
(attached is a modification to one of PDFView sample files that
automatically adds the stamp to every page in the document):

//----------------------------------------------------------
// Add a rotated and centered text stamp to every page in the
document.
//
// @param pdfdoc - A document to stamp.
// @param text - A text string used to stamp pages.
// @param font_sz - The font size.
// @param rot_angle - The rotation angle, in degrees.
// @param fill_color - The fill color represented in RGB color space
where each
// color component is in the range [0..1].
//----------------------------------------------------------
static void Stamp(PDFDoc pdfdoc, string text, double font_sz,
ColorPt fill_color, double rot_angle)
{
ElementBuilder eb = new ElementBuilder();
ElementWriter writer = new ElementWriter();
pdftron.PDF.Font myFont = pdftron.PDF.Font.Create(pdfdoc,
pdftron.PDF.Font.StandardType1Font.e_times_roman);
pdftron.PDF.ColorSpace fill_cs = ColorSpace.CreateDeviceRGB();

double deg2rad = 3.1415926535 / 180.0;
Matrix2D rot_mtx = Matrix2D.RotationMatrix(rot_angle * deg2rad);

PageIterator itr = pdfdoc.PageBegin();
PageIterator end = pdfdoc.PageEnd();
for (; itr != end; itr.Next())
{
Page page = itr.Current();
writer.Begin(page, false);
Element element = eb.CreateTextBegin(myFont, font_sz);
writer.WriteElement(element);
element = eb.CreateTextRun(text);
GState gs = element.GetGState();
gs.SetFillColorSpace(fill_cs);
gs.SetFillColor(fill_color);

// Position the text run
Matrix2D mtx = new Matrix2D(rot_mtx);
// scale the stamp relative to standard 'letter' page.
double scale_factor = page.GetPageWidth() / 612.0;
mtx.Scale(scale_factor, scale_factor);
mtx.Translate(
(page.GetPageWidth() - element.GetTextLength() * Math.Cos(rot_angle *
deg2rad)) / 2,
(page.GetPageHeight() + element.GetTextLength() * Math.Sin(rot_angle *
deg2rad)) / 2);

element.SetTextMatrix(mtx);
writer.WriteElement(element);
writer.WriteElement(eb.CreateTextEnd());
writer.End();
}
}


Sample use case:

ColorPt txt_color = new ColorPt(252 / 255.0, 210 / 255.0, 193 /
255.0); Stamp(_pdfdoc, "Hello World!", 64, txt_color, 45);

Support

unread,
Aug 9, 2013, 3:05:35 PM8/9/13
to pdfne...@googlegroups.com
 
Note: More recent version of PDFNet include ‘pdftron.PDF.Stamper’ as shown in Stamper sample:
http://www.pdftron.com/pdfnet/samplecode.html#Stamper

however using ElementBuilder/Writer is still suitable when you need more low-level control or features that are not provided via Stamper.

Reply all
Reply to author
Forward
0 new messages