adding annotations to pdf using perl - perl

I'm using the perl module PDF::API2::Annotation to add annotations to my pdf files.
There is support to decide where the annot will be created using a rect. Something like this:
$annot->text( $text, -rect => [ 10, 10, 10, 10 ] );
which works fine, but I'm having problem to be accurate on where to put my annotations.
I know the lower left corner of the pdf is (0,0). Let's say i want to put an annotation exactly in the middle of the page, any idea how can i achieve that?
according to this https://www.leadtools.com/help/leadtools/v18/dh/to/leadtools.topics.pdf~pdf.topics.pdfcoordinatesystem.html
a pdf is divided to points, and each point is 1/72 inch. and a pdf size is so the middle should be
(306,396)
But thats not even close to the middle.

You can get the size of the page media box and then calculate the middle from that:
# get the mediabox
my ($llx, $lly, $urx, $ury) = $page->get_mediabox;
# print out the page coordinates
say "page mediabox: " . join ", ", $llx, $lly, $urx, $ury;
# output: 0, 0, 612, 792 for the strangely-shaped page I created
# calculate the midpoints
my $midx = $urx/2;
my $midy = $ury/2;
my $annot = $page->annotation;
# create an annotation 20 pts wide and high around the midpoint of the mediabox
$annot->text($text, -rect=>[$midx-10,$midy-10,$midx+10,$midy+10]);
As well as the media box, you can also get the page crop box, trim box, bleed box, and art box:
for my $box ('mediabox', 'cropbox', 'trimbox', 'artbox', 'bleedbox') {
my $get = "get_$box";
say "$box dimensions: " . join ", ", $page->$get;
}
These are usually all the same unless the document has been set up for professional printing with a bleed area, etc.

Related

How to display text in center if use verticalText?

My code
VerticalText vt = new VerticalText(writer.getDirectContent());
vt.setVerticalLayout(marginLeft + squareHeight, 1191.0f - marginTop, squareHeight, 3, 20);
vt.setAlignment(Element.ALIGN_CENTER);
Paragraph p = new Paragraph(imgr.getText(), fontV);
p.setLeading(10);
vt.addText(p);
vt.go();
The result : Text is middle in vertical mode.
I want to display text is center in horizontal mode as below link:
How to solve this problem ?
As documented, left, center and right align has a different meaning in the context of VerticalText. Left is top, center is middle and right is bottom.
With class VerticalText, you always write from right to left. There is currently no way to align the text as shown in the screen shot to the right.
However, you could work around this problem by adding the vertical text in simulation mode first and then calculate the number of lines that have been written.
See for instance the VerticalText1 example from my book. I have adapted the code of that example like this:
BaseFont bf = BaseFont.createFont(
"KozMinPro-Regular", "UniJIS-UCS2-V", BaseFont.NOT_EMBEDDED);
Font font = new Font(bf, 20);
VerticalText vt = new VerticalText(writer.getDirectContent());
vt.setVerticalLayout(390, 570, 540, 12, 30);
vt.addText(new Chunk(MOVIE, font));
vt.go();
System.out.println(vt.getMaxLines());
vt.addText(new Phrase(TEXT1, font));
vt.go();
System.out.println(vt.getMaxLines());
vt.setAlignment(Element.ALIGN_RIGHT);
vt.addText(new Phrase(TEXT2, font));
vt.go();
System.out.println(vt.getMaxLines());
The output of the System.out calls is:
11
4
1
These numbers are the number of lines that are available after each go().
We start with 12 lines as defined in the setVerticalLayout() method.
We add MOVIE and there are 11 lines left. We've defined a leading of 30, which means we've already consumed (12 - 11) x 30pt = 30pt.
Then we add TEXT1 which is distributed over 7 lines, which take 7 * 30pt in width. In total we now have consumed (12 - 4) x 30pt = 240pt.
Finally we add TEXT2 which is distributed over 3 lines. Only 1 line is left. The total horizontal width of all the text is 330pt (we had only 30pt left).
Now that you know this math, you can execute the go() method in simulation mode, calculate the width that was consumed and use that info to add your text for real at the desired position.

Line chart/graph with an irregular threshold field

Looking to create a bar chart with an irregular, colored threshold field in the background, so that each data point has its own individual set of min/max thresholds, which ultimately would look something like this: http://dcalvitti.webs.com/plant/SAMPLE.png
Looked at D3 examples like this one: http://bl.ocks.org/mbostock/4062844
Can the latter example be manipulated to look more like the image I created?
Thanks in advance..
The graph shown in your sample image is actually much easier than the linked example; for that, you don't need to create a clipping path and you don't need to draw the line twice with two different colours.
For drawing the coloured background, use an area-path generator, created with d3.svg.area(). Set the y0 accessor function to be extract your minimum value for each point in your data array, and the y1 accessor function to extract the maximum value.
Then draw the line overtop as a normal line graph with a d3.svg.line() path generator.
Working example, adapted from the fiddles in the comments: http://jsfiddle.net/h45CD/12/
(Note: I commented out half the dataset, since the "year" values were repeated, not sure what that was supposed to represent.)
Key code:
// Define the value line path generator
var line = d3.svg.line()
.x( function(d) { return x(d.year); } )
.y( function(d) { return y(d.temp); } );
// Define the area path generator
var area = d3.svg.area()
.x( function(d) { return x(d.year); } )
.y0( function(d) { return y(d.min); } )
.y1( function(d) { return y(d.max); } );
/* ... */
// Add the background area showing the historic range
svg.append("path")
.datum(data)
.attr("class", "historicRange")
.attr("d", area);
// Add the value line
svg.append("path")
.datum(data)
.attr("class", "dataline")
.attr("d", line);
Edit based on comments
If you do want a line that changes colour depending on historic values, as opposed to a line drawn overtop of a background range, the most straight-forward solution is probably to create a <pattern> element consisting of the different coloured regions, and use this to stroke the value line.
You'll want to familiarize yourself with the different options for the pattern element. This MDN tutorial has a good intro, or you could dive into the full W3 specs.
For this situation, we want the pattern to be sized and positioned relative to the coordinate system used for drawing the line, regardless of the size or shape of the line itself. That means we will be setting both the patternUnits and the patternContentUnits to be userSpaceOnUse. The height and width of the pattern will be the height and width of the plotting area.
Within the pattern we will draw the area that represents the max-min range, but we also need to draw separate areas, with different colours, for values above the max and values below the min. We can use the same area generator for each, but need to change the y0/y1 accessor functions each time.
Key code:
// Add the pattern showing the historic range
var pattern = defs.append("pattern")
.datum(data) //add the data to the <pattern> element
//so it will be inherited by each <path> we append
.attr({
"patternUnits":"userSpaceOnUse",
"patternContentUnits":"userSpaceOnUse",
"width": width,
"height": height
})
.attr("id", "strokePattern");
pattern.append("path")
.attr("class", "historicRange between")
.attr("d", area);
pattern.append("path")
.attr("class", "historicRange above")
.attr("d", area.y1( 0 )
.y0( function(d){return y(d.max);} )
);
pattern.append("path")
.attr("class", "historicRange below")
.attr("d", area.y1( function(d){return y(d.min);} )
.y0( height )
);
// Add the value line
plot.append("path")
.datum(data)
.attr("class", "dataline")
.attr("d", line)
.style("stroke", "url(#strokePattern)");
Working example: http://jsfiddle.net/h45CD/14/
I'm including a web page link with charts authored by myself based on AMCharts and with the help of that web site's founder. Contains several examples of the above question and more..
http://dcalvitti.webs.com/SAMPLE/NEWWEBINDEX.html
The charts provided are still being worked on. For example, AMcharts does have a function that clips the color of a line above/below a certain value which I didn't know about, so there is still work to be done. I spent many weeks on the charts and thought I'd share. I'm sure someone will find something new here down the road...

Add rectangle as inline-element with iText

How do I add a rectangle (or other graphical elements) as inline-elements to an iText PDF?
Example code of what I'm trying to achieve:
foreach (Row r in entrylist)
{
p = new Paragraph();
p.IndentationLeft = 10;
p.SpacingBefore = 10;
p.SpacingAfter = 10;
p.Add(new Rectangle(0, 0, 10, 10)); <<<<<<<<< THAT ONE FAILS
p.Add(new Paragraph(r.GetString("caption"), tahoma12b));
p.Add(new Paragraph(r.GetString("description"), tahoma12));
((Paragraph)p[1]).IndentationLeft = 10;
doc.Add(p);
}
It's something like a column of text-blocks, of which each of them have (only a printed) checkbox.
I've tried various things with DirectContent, but it requires me to provide absolute X and Y values. Which I simply don't have. The elements should be printed at the current position, wherever that may be.
Any clues?
You need a Chunk for which you've defined a generic tag. For instance, in this example listing a number of movies, a snippet of pellicule is drawn around the year a movie was produced and an ellipse was drawn in the background of the link to IMDB.
If you look at the MovieYears example, you'll find out how to use the PdfPageEvent interface and its onGenericTag() method. You're right that you can't add a Rectangle to a Paragraph (IMHO that wouldn't make much sense). As you indicate, you need to draw the rectangle to the direct content, and you get the coordinates of a Chunk by using the setGenericTag() method. As soon as the Chunk is drawn on the page, its coordinates will be passed to the onGenericTag() method.

Modifying pixels in an image using Perl

Suppose I want to take one picture, move all of its pixels one pixel to the right and one to the left, and save it. I tried this code:
my $image_file = "a.jpg";
my $im = GD::Image->newFromJpeg($image_file);
my ($width, $height) = $im->getBounds();
my $outim = new GD::Image($width, $height);
foreach my $x (1..$width)
{
foreach my $y (1..$height)
{
my $index = $im->getPixel($x-1,$y-1);
my ($r,$g,$b) = $im->rgb($index);
my $color = $outim->colorAllocate($r,$g,$b);
$outim->setPixel($x,$y,$color);
}
}
%printing the picture...
That doesn't do the trick; it draws all pixels, except those in which x=0 or y=0, in one color. Where am I going wrong?
Look in the docs:
Images created by reading JPEG images will always be truecolor. To
force the image to be palette-based, pass a value of 0 in the optional
$truecolor argument.
It's not indexed. Try adding a ,0 to your newFromJpeg call.
From the comments, it seems your next problem is the number of colors to allocate. By default, the indexed image is 8-bit, meaning a maximum number of 256 unique colors (2^8=256). The "simple" workaround is of course to use a truecolor image instead, but that depends on whether you can accept truecolor output.
If not, your next challenge will be to come up with "an optimal" set of 256 colors that will minimize the visible defects in the image itself (see http://en.wikipedia.org/wiki/Color_quantization). That used to be a whole topic in itself that we seldom have to worry about today. If you still have to worry about it, you are probably better off offloading that job to some specialized tool like Imagemagik or similar, rather than try to implement it yourself. Unless you like challenges of course.
Here's a solution using Imager because it's a very nice module and I'm more familiar with it, and it handles image transformations nicely.
use Imager;
my $image_file = "a.jpg";
my $src = Imager->new(file => $image_file) or die Imager->errstr;
my $dest = Imager->new(
xsize => $src->getwidth() + 1,
ysize => $src->getheight() + 1,
channels => $src->getchannels
);
$dest->paste(left => 1, top => 1, src => $src);
$dest->write(file => "b.jpg") or die $dest->errstr;
Try reversing the direction of x and y - not from 1 to max but from max to 1. You are not sliding the colors but copying the same again and again.
I realize that this is an old post, but this is a piece of code that I use GD:Thumb for creating resized images.
sub png {
my ($orig,$n) = (shift,shift);
my ($ox,$oy) = $orig->getBounds();
my $r = $ox>$oy ? $ox / $n : $oy / $n;
my $thumb = GD::Image->newFromPng($ox/$r,$oy/$r,[0]);
$thumb->copyResized($orig,0,0,0,0,$ox/$r,$oy/$r,$ox,$oy);
return $thumb, sprintf("%.0f",$ox/$r), sprintf("%.0f",$oy/$r);
}

How can I create a page based on image size in PDF::API2?

I am creating a pdf from a list of image files and I was wondering if it was possible to create each page of my pdf to be the size of whatever image I am currently adding - so they all fit and none of the larger ones get cropped or whatever.
Currently I'm creating pages like this: my $page = $pdf->page();
I have an object of the specific image as well. And if someone could tag this as PDF::API2 that'd be great.
I think you want to look at $pdf->mediabox(), $pdf->cropbox(), $pdf->bleedbox(), and $pdf->trimbox().
You probably want to find the PDF spec to determine how these work, though.
Are you thinking of this purely for on-screen viewing? If print-size doesn't matter, you can do something like this:
use PDF::API2;
my $pdf = PDF::API2->new();
foreach my $filename (#list_of_jpeg_locations) {
my $image = $pdf->image_jpeg($filename);
my $width = $image->width();
my $height = $image->height();
# Set the page size to equal the image size
my $page = $pdf->page();
$page->mediabox($width, $height);
# Place the image in the bottom corner of the page
my $gfx = $page->gfx();
$gfx->image($image, 0, 0);
}
$pdf->saveas('/path/to/file.pdf');
You can tweak this code to scale the images to fit a particular printed page size, if need be.