I have been trying to add a watermark in a pdf using Itext 7. The watermark needs to be at the left side of each page and should be vertical. Something like shown in the following image:
Instead of being in centre, it should be at the left side of the page.
I tried the following code, but any angle I try it does not work for me -
File mergedDoc = new File(mergedFileName + ".pdf");
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(mergedDoc));
Document document = new Document(pdfDoc);
PdfFont font = PdfFontFactory.createFont(FontProgramFactory.createFont(FontConstants.HELVETICA));
Paragraph verticalWatermark = new Paragraph("My vertical watermark").setFont(font).setFontSize(30);
for (int i = 1 + pdfDoc.getNumberOfPages(); i <= k; i++) {
PdfPage page = pdfDoc.getPage(i);
page.setIgnorePageRotationForContent(false);
over = new PdfCanvas(pdfDoc.getPage(i));
over.saveState();
over.setExtGState(gs1);
document.showTextAligned(verticalWatermark, 30f, 25f, i, TextAlignment.LEFT, VerticalAlignment.BOTTOM, 90);
over.restoreState();
pdfDoc.close();
document.close();
}
Any help would be appreciated.
Your code is wrong in many places.
You combine low-level operations such saveState()/restoreState() on a PdfCanvas in combination with the high-level Document class' showTextAligned() method.
You start counting at 1 + pdfDoc.getNumberOfPages() which is weird. Your code sample is not a SSCCE. No one but you can run it because no one but you knows what variables such as k and gs1 are about. Not providing a SSCCE is often interpreted as "I am asking a question, but I'm not interested in getting an answer."
You are defining a value in degrees where a value in radians is expected, see the API docs: showTextAligned(Paragraph p, float x, float y, int pageNumber, TextAlignment textAlign, VerticalAlignment vertAlign, float radAngle)
I have taken the iText 7 Jump-Start Tutorial, and I have added a vertical watermark to the left of the page:
This was the code I used:
PdfReader reader = new PdfReader(src);
PdfWriter writer = new PdfWriter(dest);
PdfDocument pdf = new PdfDocument(reader, writer);
Document document = new Document(pdf);
Paragraph p = new Paragraph("My vertical watermark");
for (int i = 1; i <= pdf.getNumberOfPages(); i++) {
document.showTextAligned(
p, 36, 72, i, TextAlignment.LEFT, VerticalAlignment.BOTTOM,
(float)Math.PI / 2);
}
document.close();
As you can see: there's no need for a PdfCanvas and it's Math.PI / 2 radians instead of 90 degrees.
Related
I would like to position cubes in a rectangular/square like grid. I'm having trouble trying to create some methodology in depending on what I pick through an HTML form input (checkboxes) to have it arrange left to right and up to down, a series of cubes, in a prearranged grid all on the same plane.
What measurement units is three.js in? Right now, I'm setting up my shapes using the built-in geometries, for instance.
var planeGeometry = new THREE.PlaneGeometry(4, 1, 1, 1);
The 4 and 1; I'm unsure what that measures up to in pixels, although I do see it rendered. I'm resorting to eyeballing it (guess and checking) every time so that it looks acceptable.
Without a fair bit of extra math THREE is not measured in pixels.
To make a simple grid (I leave optimizations, colors, etc for future refinements) try something like:
var hCount = from_my_web_form('horiz'),
vCount = from_my_web_form('vert'),
size = 1,
spacing = 1.3;
var grid = new THREE.Object3d(); // just to hold them all together
for (var h=0; h<hCount; h+=1) {
for (var v=0; v<vCount; v+=1) {
var box = new THREE.Mesh(new THREE.BoxGeometry(size,size,size),
new THREE.MeshBasicMaterial());
box.position.x = (h-hCount/2) * spacing;
box.position.y = (v-vCount/2) * spacing;
grid.add(box);
}
}
scene.add(grid);
I have a situation where i am generating several graphs in web page and showing them in canvas and my requirement is that on click of download button,i should be able to export all canvas images to pdf.
I have successfully done this for single canvas element using html2canvas and Jspdf but cannot figure out how to do the same for all.
I followed this JSFiddle code for generating pdf from Html2canvas and jspdf.
jsfiddle
$(document).ready(function() {
var d_canvas = document.getElementById('canvas');
var context = d_canvas.getContext('2d');
context.moveTo(20, 20);
context.lineTo(100, 20);
context.fillStyle = "#999";
context.beginPath();
context.arc(100, 100, 75, 0, 2 * Math.PI);
context.fill();
context.fillStyle = "orange";
context.fillRect(20, 20, 50, 50);
context.font = "24px Helvetica";
context.fillStyle = "#000";
context.fillText("Canvas", 50, 130);
$('#ballon').draggable();
$('#download').click(function() {
html2canvas($("#canvas"), {
onrendered: function(canvas) {
var imgData = canvas.toDataURL(
'image/png');
var doc = new jsPDF('p', 'mm');
doc.addImage(imgData, 'PNG', 10, 10);
doc.save('sample-file.pdf');
}
});
});
});
Kindly help,thanks in advance.
It was very simple ,I just changed the argument to this line
html2canvas($("#canvas"), {
Instead of passing seperate canvases and then trying to export them to single pdf rather i kept different canvases in on Div and passed the Div id to the above mentioned line and both canvases were exported to single pdf file
There should be no need to use html2canvas for this. It will only deliver you another canvas element at a cost. You can use the original canvas element and toDataURL() directly with jsPdf.
Example (partly pseudo)
This will collect all canvases in the page and put them in a PDF. The pseudo part is the missing variables for width, deltas, factor etc. But you should get the gist of it.
Note: The size for images must be given in the same unit you're using for the document, so you need to convert pixel positions and sizes into millimeter representation using a pre-calculated factor based on document DPI (not shown here, but this may help).
var x = someX,
y = someY,
dx = somDeltaForX,
dy = somDeltaForY,
i,
canvases = document.querySelectorAll("canvas"),
pdf = new jsPDF('p', 'mm'),
f = convertionFactorFromPixelstoMM;
for(i = 0; i < canvases.length; i++) {
var url = canvases[i].toDataURL("image/jpeg", 0.75);
doc.addImage(url, "JPEG", x * f, y * f, canvases[i].width * f, canvases[i].height * f);
x += dx; // tip: dx could also be based on previous canvas width in non-uniform sizes
if (x > widthOfPage) {
x = 0;
y += dy;
}
}
I would like to find all vertex (e.g. return x, y positions) for the black object.
I will use Java and JavaCV to implements. Is there any API or algorithm can help?
Sorry for not enough reputation to post images. I post the link here.
The original image like this:
http://i.stack.imgur.com/geubs.png
The expected result like this:
http://i.stack.imgur.com/MA7uq.png
Here is what you should do (for explanation, see comments with code),
CODE
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
// Load the image
String path = "/home/bikz05/Desktop/geubs.png";
Mat original = Highgui.imread(path);
Mat image = new Mat();
Imgproc.cvtColor(original, image, Imgproc.COLOR_BGR2GRAY);
// Threshold the image
Mat threshold = new Mat();
Imgproc.threshold(image, threshold, 127, 255, 1);
// Find the contours
List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Imgproc.findContours(threshold, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);
// Get contour index with largest area
double max_area = -1;
int index = 0;
for(int i=0; i< contours.size();i++) {
if (Imgproc.contourArea(contours.get(i)) > max_area) {
max_area = Imgproc.contourArea(contours.get(i));
index = i;
}
}
// Approximate the largest contour
MatOfPoint2f approxCurve = new MatOfPoint2f();
MatOfPoint2f oriCurve = new MatOfPoint2f( contours.get(index).toArray() );
Imgproc.approxPolyDP(oriCurve, approxCurve, 6.0, true);
// Draw contour points on the original image
Point [] array = approxCurve.toArray();
for(int i=0; i < array.length;i++) {
Core.circle(original, array[i], 2, new Scalar(0, 0 ,255), 2);
}
INPUT IMAGE
OUTPUT IMAGE
OpenCV allows you to take a binary image and carry out contour analysis.
http://docs.opencv.org/doc/tutorials/imgproc/shapedescriptors/find_contours/find_contours.html
You could use findContours to find all of the contours (all of the edge points) then simply average them or pick and choose the ones that suit your purpose.
Here is a good example for JavaCV..
opencv/javacv: How to iterate over contours for shape identification?
I am trying to detect doctor's tools from endoscopy video using the following code
static void video_tracking(){
//read image
IplImage orgImg = cvLoadImage("C:/Users/Ioanna/Desktop/pic.png");
IplImage thresholdImage = hsvThreshold(orgImg);
cvSaveImage("hsvthreshold.jpg", thresholdImage);
Dimension position = getCoordinates(thresholdImage);
System.out.println("Dimension of original Image : " + thresholdImage.width() + " , " + thresholdImage.height());
System.out.println("Position of red spot : x : " + position.width + " , y : " + position.height);
}
static Dimension getCoordinates(IplImage thresholdImage) {
int posX = 0;
int posY = 0;
CvMoments moments = new CvMoments();
cvMoments(thresholdImage, moments, 1);
double momX10 = cvGetSpatialMoment(moments, 1, 0); // (x,y)
double momY01 = cvGetSpatialMoment(moments, 0, 1);// (x,y)
double area = cvGetCentralMoment(moments, 0, 0);
posX = (int) (momX10 / area);
posY = (int) (momY01 / area);
return new Dimension(posX, posY);
}
static IplImage hsvThreshold(IplImage orgImg) {
// Convert the image into an HSV image
IplImage imgHSV = cvCreateImage(cvGetSize(orgImg), 8, 3);
cvCvtColor(orgImg, imgHSV, CV_BGR2HSV);
//create a new image that will hold the threholded image
// 1- color = monochrome
IplImage imgThreshold = cvCreateImage(cvGetSize(orgImg), orgImg.depth(), 1);
//do the actual thresholding
cvInRangeS(imgHSV, cvScalar(13, 0, 0, 0), cvScalar(40, 117, 124, 88), imgThreshold);
cvReleaseImage(imgHSV);
cvSmooth(imgThreshold, imgThreshold, CV_MEDIAN, 13);
// save
return imgThreshold;
}
The input of the above code is a color image with 2 doctor's object and the output is a grayscale image that detect the tools. Sorry, but the system doesn't allow to upload the images.
The problem is I don't know how to find the position of 2 tools and draw a rectangle. Please can some one explain how to archive my objective using javacv/opencv?
It can be achieve using Haar Casacde files .Some of the bulit-In Haar files provided by google can found in opencv\data\haarcascades directory .These files are XML files generated by heavy training sections.Some of the sample haar files are used for face detection,ear detection etc.A sample project can be fount at here.You can generate your own haar cascade file for any purpose.one of the method for generate Haar cascade file can be found at here
I try to integrate Box2D inside my game for WP7. However, the bodies that I add, do not respond as expected to the gravity. Basically, it seems that whatever property I modify, the object that I add still seems to be very "light" and does not actually respond to gravity changes.
Here is the code:
void Init
{
world = new World(new Vector2(0, 100), false);
world.ContinuousPhysics = true;
// add ground
BodyDef bd = new BodyDef();
Body ground = world.CreateBody(bd);
PolygonShape shape = new PolygonShape();
shape.SetAsEdge(new Vector2(0.0f, bbheight), new Vector2(bbwidth, bbheight));
ground.CreateFixture(shape, 0.0f);
AddObject(new Vector2(450,0));
}
private void AddObject(Vector2 position)
{
float PTM = 32;
Vector2 pos = new Vector2(position.X / PTM, position.Y / PTM);
var circle = new CircleShape();
circle._radius = 1.0f;
var fd = new FixtureDef();
fd.shape = circle;
fd.restitution = 0.5f;
fd.friction = 1.0f;
fd.density = 1000.0f;
BodyDef bd = new BodyDef();
bd.type = BodyType.Dynamic;
bd.fixedRotation = true;
bd.allowSleep = false;
bd.position = pos;
var body = world.CreateBody(bd);
body.CreateFixture(fd);
body.SetUserData(Red);
}
I would be grateful if you could give some help.
Thanks!
Box2D Engine is designed in pixels but in units and it likes small units.
Example if you try scale 1 pixel = 1 unit when you make and object that is 100 pixels wide it is large as a big planet for Box2D. So if the distance between two objects is 300 it will take forever to colide
What you nees to do is to change the scale as Box2D was designed to.
I recommend you to read or watch some Box2D tutorials like this one http://www.kerp.net/box2d/ this tutorial is for Flash Box2D version but main difference is Class names.