ITextSharp - Draw Rectangle top left corner - itext

I'm trying to draw a rectangle to the very top left of a page using ITextSharp (5.5.13). I want to draw in the page margins. However, the rectangle is around 25 pixels too low. How can I draw the rectangle in the top left corner?
Below is how I'm adding the rectangle to the page:
using (PdfReader reader = new PdfReader(inputPdf.FullName))
using (PdfStamper stamper = new PdfStamper(reader, new FileStream(outputPdf.FullName, FileMode.Create)))
{
PdfContentByte contentByte = stamper.GetOverContent(1);
PdfDocument doc = contentByte.PdfDocument;
float X = 0.0f;
float Y = 0.0f;
float Height = Utilities.InchesToPoints(0.50f);
float Width = Utilities.InchesToPoints(0.50f);
float llx = (doc.Left - doc.LeftMargin) + X;
float lly = (doc.Top - doc.TopMargin) - (Height + Y);
float urx = (doc.Left - doc.LeftMargin) + Width + X;
float ury = (doc.Top - doc.TopMargin) - Y;
Rectangle rectangle = new Rectangle(llx, lly, urx, ury)
{
BackgroundColor = BaseColor.BLACK
};
contentByte.Rectangle(rectangle);
}
Below are the debug values for each aforementioned variable:

Whenever you use a PdfStamper, the PdfDocument you can retrieve from its parts does not contain sensible information, it merely is a dummy object.
Thus, don't try to determine the page size from that PdfDocument doc, instead use the appropriate methods or properties of your PdfReader reader, e.g.
/** Gets the crop box without taking rotation into account. This
* is the value of the /CropBox key. The crop box is the part
* of the document to be displayed or printed. It usually is the same
* as the media box but may be smaller. If the page doesn't have a crop
* box the page size will be returned.
* #param index the page number. The first page is 1
* #return the crop box
*/
virtual public Rectangle GetCropBox(int index)

Related

Unity: Dynamically build UI elements on Canvas: ScreenSpace-Camera, previously ScreenSpace-Overlay

My application works fine, 100% expected results with Canvas set on ScreenSpace-Overlay. I have written a function that takes an array of integers and based on its values it dynamically builds vertical bars inside a panel. I have an UI-Image as a prefab and that I instantiated multiple time, set its anchor to bottom left position and increase the x-offset from that point in increments of its width+padding. Everything works fine, check the screenshots.
I have now a fancy idea of animating the vertical bars... to have Unity Particle Effects on the top of each bar and to play it. From what I searched... you cannot get Particle Effects working on Canvas-UI unless the Canvas is set as ScreenSpace-Camera. I managed to obtain success with Particle Effects and ScreenSpace-Camera canvas... everything works... but now the same code that dynamically builds the UI doesnt work anymore... the vertical bars are set on a total new position outside the UI.
My Canvas
Working algorithm
My code:
private void ArrangeImagesOnCanvas(List<int> varArray)
{
Canvas canvas = FindObjectOfType<Canvas>();
//float h = canvas.GetComponent<RectTransform>().rect.height * canvas.GetComponent<RectTransform>().localScale.y;
//float w = canvas.GetComponent<RectTransform>().rect.width * canvas.GetComponent<RectTransform>().localScale.x;
float h = _panelImageForSortingAlgorithm.GetComponent<RectTransform>().rect.height * canvas.GetComponent<RectTransform>().localScale.y;
float w = _panelImageForSortingAlgorithm.GetComponent<RectTransform>().rect.width * canvas.GetComponent<RectTransform>().localScale.x;
float minH = 20.0f;
float maxH = h - 20;
int minList = varArray.Min();
int maxList = varArray.Max();
_imageWidth = (w - (varArray.Count * _PADDING)) / varArray.Count;
List<float> heightsList = new List<float>();
float _tempFloat = 0;
for (int i = 0; i < varArray.Count; i++)
{
_tempFloat = ScaleIntervals(varArray[i], new Vector2(minList, maxList), new Vector2(minH, maxH));
heightsList.Add(_tempFloat);
}
for(int i = 0; i<_instancesOfImages.Count;i++)
{
Destroy(_instancesOfImages[i]);
}
_instancesOfImages.Clear();
for (int i = 0; i < varArray.Count; i++)
{
GameObject instantiatedImage = Instantiate(_imageToInstance, _imageToInstance.transform.position, Quaternion.identity);
instantiatedImage.transform.SetParent(_panelImageForSortingAlgorithm.transform);
Image img = instantiatedImage.GetComponent<Image>();
img.rectTransform.anchorMin = new Vector2(0, 0);
img.rectTransform.anchorMax = new Vector2(0, 0);
img.rectTransform.pivot = new Vector2(0, 0);
img.rectTransform.position = new Vector3(i * (_imageWidth + _PADDING), 0, 0);
img.rectTransform.sizeDelta = new Vector2(_imageWidth, heightsList[i]);
_instancesOfImages.Add(instantiatedImage);
}
}
For the same code the vertical bars can be seen in this image...
Broken bars 1
if I put
float h = _panelImageForSortingAlgorithm.GetComponent<RectTransform>().rect.height;
float w = _panelImageForSortingAlgorithm.GetComponent<RectTransform>().rect.width;
then the vertical bars are like in this image.
Broken bars 2
How can I position correctly the vertical bars as in ScreenSpace-Overlay but this time to be on ScreenSpace-Camera ? Please help or give me some advices or tips...

how to copy a part of a raw image

I want to copy selected part of a raw image to another image
I get start and end position as percentage and by that I can calculate the start and end position in width
how can I copy that selected part to another raw image?
Assuming it's a Texture2D, you can do the following:
Calculate A texture start/end X (dX)
Create a new Texture2D (B), sized as dX and full Y
Call A.GetPixels()
Iterate on array copying pixels to new texture
Apply on new texture
Pseudo code:
var aPixels = aTexture.GetPixels();
var bWidth = endX - startX;
var bTexture = new Texture2D(bWidth, endY);
var bPixels = bTexture.GetPixels();
for (int x = startX; x < endX; x++)
{
for (int y = 0; y < endY; y++)
{
var aIndex = x + y * A.width;
var bIndex = (x - startX) + y * bWidth;
bPixels[bIndex] = aPixels[aIndex];
}
}
bTexture.Apply();
Note that my code quite possibly won't work; as I'm typing this on a mobile phone.
Usually, Image Processing is an expensive process for CPUs, so I don't recommend it in Unity,
But anyway, For your image and in this special case, I think you can crop your image by changing the Size and Offset of texture in material.
Update:
This is an example of what I mentioned:
You can calculate Tile and Offset based on the dragged mouse position on Texture. (Check Here)
I found this.
you can set start coordinates and width and height to GetPixels();
void Start () {
public Texture2D mTexture;
Color[] c = mTexture.GetPixels (startX, startY, width, height);
Texture2D m2Texture = new Texture2D (width, height);
m2Texture.SetPixels (c);
m2Texture.Apply ();
gameObject.GetComponent<MeshRenderer> ().material.mainTexture = m2Texture;
}
```

How set rotation angle a page in itext 7

How can i rotate page at a specified angle(for example 25 degrees)?
PdfCanvas content = new PdfCanvas(pdfDoc.addNewPage());
for (int i =1 ; i <= srcDoc.getNumberOfPages(); i++) {
PdfFormXObject page = srcDoc.getPage(i).copyAsFormXObject(pdfDoc);
content.add(page...);
}
Can i set RotationAngle to work with PdfFormXObject ? Or is there another way?
The easiest way is by using an AffineTransform (from com.itextpdf.kernel.geom):
PdfCanvas content = new PdfCanvas(pdfDoc.addNewPage());
PageSize pageSize = pdfDoc.getDefaultPageSize();
PdfFormXObject page = srcDoc.getPage(1).copyAsFormXObject(pdfDoc);
AffineTransform transform = AffineTransform.getRotateInstance(25 * Math.PI / 180, (pageSize.getLeft() + pageSize.getRight())/2, (pageSize.getBottom() + pageSize.getTop())/2);
content.concatMatrix(transform);
content.addXObject(page, 0, 0);
(RotatePageXObject test testAddPage25Degree)
AffineTransform.getRotateInstance is documented to
* Get an affine transformation representing a counter-clockwise rotation over the passed angle,
* using the passed point as the center of rotation
so we feed it the angle (transformed to radians) and the coordinates of the page center.
Applied to this source PDF it creates this result:

JavaFX 8, how to get center location of Scrollpane's Viewport

The Problem
I'm trying to figure out a way to get at which point in the content node the scroll pane's viewport is centered on.
To elaborate on the picture above, the big rectangle is the content (let's say a large image), and the small rectangle is the portion that is shown by the scroll pane. I'm trying to find x and y which would be coordinates from the top left of the content.
What I've Tried
My first thought was to use the getViewportBounds() method of the scroll pane and use its minX and maxX properties to determine the center x point:
Bounds b = scrollPane.getViewportBounds();
double centerX = (b.getMinX() + b.getMaxX()) / 2;
double centerY = (b.getMinY() + b.getMaxY()) / 2;
However, this doesn't work because these numbers are negative and don't seem to accurately describe the x and y I'm looking for anyways.
My next thought was to use the scroll pane's hValue and vValue to get the top left corner of the viewport relative to the content:
Bounds b = scrollPane.getViewportBounds();
double centerX = scrollPane.getHvalue() + b.getWidth() / 2;
double centerY = scrollPane.getVvalue() + b.getHeight() / 2;
This didn't work either though as the hValue and vValue seem to be way too large (when scrolled in only a few pixels, I'm getting numbers like 1600).
My Questions
I seem to have a fundamental misunderstanding of how the viewport works with a scroll pane.
What am I doing wrong here? Can someone explain where these numbers come from? How do I find x and y like in the picture above?
Let (x, y) be the be coordinates of the top, left point shown in the viewport. You can write this as
((contentWidth - viewportWidth) * hValueRel, (contentHeight - viewportHeight) * vValueRel)
vValueRel = vValue / vMax
hValueRel = hValue / hMax
This means assuming hmin and vmin remain 0 you can keep a circle in the center of like this:
// update circle position to be centered in the viewport
private void update() {
Bounds viewportBounds = scrollPane.getViewportBounds();
Bounds contentBounds = content.getBoundsInLocal();
double hRel = scrollPane.getHvalue() / scrollPane.getHmax();
double vRel = scrollPane.getVvalue() / scrollPane.getVmax();
double x = Math.max(0, (contentBounds.getWidth() - viewportBounds.getWidth()) * hRel) + viewportBounds.getWidth() / 2;
double y = Math.max(0, (contentBounds.getHeight() - viewportBounds.getHeight()) * vRel) + viewportBounds.getHeight() / 2;
Point2D localCoordinates = content.parentToLocal(x, y);
circle.setCenterX(localCoordinates.getX());
circle.setCenterY(localCoordinates.getY());
}
private Circle circle;
private Pane content;
private ScrollPane scrollPane;
#Override
public void start(Stage primaryStage) {
// create ui
circle = new Circle(10);
content = new Pane(circle);
content.setPrefSize(4000, 4000);
scrollPane = new ScrollPane(content);
Scene scene = new Scene(scrollPane, 400, 400);
// add listener to properties that may change
InvalidationListener l = o -> update();
content.layoutBoundsProperty().addListener(l);
scrollPane.viewportBoundsProperty().addListener(l);
scrollPane.hvalueProperty().addListener(l);
scrollPane.vvalueProperty().addListener(l);
scrollPane.hmaxProperty().addListener(l);
scrollPane.vmaxProperty().addListener(l);
scrollPane.hminProperty().addListener(l);
scrollPane.vminProperty().addListener(l);
primaryStage.setScene(scene);
primaryStage.show();
}

iText - How to stamp image on existing PDF and create an anchor

I have an existing document, onto which I would like to stamp an image at an absolute position.
I am able to do this, but I would also like to make this image clickable: when a user clicks
on the image I would like the PDF to go to the last page of the document.
Here is my code:
PdfReader readerOriginalDoc = new PdfReader("src/main/resources/test.pdf");
PdfStamper stamper = new PdfStamper(readerOriginalDoc,new FileOutputStream("NewStamper.pdf"));
PdfContentByte content = stamper.getOverContent(1);
Image image = Image.getInstance("src/main/resources/images.jpg");
image.scaleAbsolute(50, 20);
image.setAbsolutePosition(100, 100);
image.setAnnotation(new Annotation(0, 0, 0, 0, 3));
content.addImage(image);
stamper.close();
Any idea how to do this ?
You are using a technique that only works when creating documents from scratch.
Please take a look at the AddImageLink example to find out how to add an image and a link to make that image clickable to an existing document:
public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
Image img = Image.getInstance(IMG);
float x = 10;
float y = 650;
float w = img.getScaledWidth();
float h = img.getScaledHeight();
img.setAbsolutePosition(x, y);
stamper.getOverContent(1).addImage(img);
Rectangle linkLocation = new Rectangle(x, y, x + w, y + h);
PdfDestination destination = new PdfDestination(PdfDestination.FIT);
PdfAnnotation link = PdfAnnotation.createLink(stamper.getWriter(),
linkLocation, PdfAnnotation.HIGHLIGHT_INVERT,
reader.getNumberOfPages(), destination);
link.setBorder(new PdfBorderArray(0, 0, 0));
stamper.addAnnotation(link, 1);
stamper.close();
}
You already have the part about adding the image right. Note that I create parameters for the position of the image as well as its dimensions:
float x = 10;
float y = 650;
float w = img.getScaledWidth();
float h = img.getScaledHeight();
I use these values to create a Rectangle object:
Rectangle linkLocation = new Rectangle(x, y, x + w, y + h);
This is the location for the link annotation we are creating with the PdfAnnotation class. You need to add this annotation separately using the addAnnotation() method.
You can take a look at the result here: link_image.pdf
If you click on the i icon, you jump to the last page of the document.