How to calculate the length in mm of a string in a PDF document created with jsPDF library? - pdf

I use jsPDF library to create and print a PDF document. This library exposes low level methods which are ok, but i have tons of fields to create, many of which are similar, and i need to create higher level abstractions.
For example i have a createLabel function that i want to call instead of this low level stuff.
var doc = new jsPDF('portrait', 'mm', 'a4');
doc.addFont('Arial', "sans-serif", "normal");
// name
doc.setFontSize(14);
doc.text(10, 19, "name:");
doc.setLineWidth(0.1);
doc.line(25, 19, 100, 19); // meaning x1, y1, x2, y2
// CUI
doc.setFontSize(14);
doc.text(10, 29, "CUI:");
doc.setLineWidth(0.1);
doc.line(21, 29, 100, 29);
// same stuff but use functions instead.
createLabel("name: ", 10,50, 100); // meaning (labelName, x, y, totalWidth)
createLabel("CUI: ", 10,60, 100);
As you can see, the lines for the second group of labels are not placed in the right position. They are too much on the left. Their starting postion is generated based on the length of the labelName, and this length calculation fails. How can i make this work properly? The code so far is:
function createLabel(name, x, y, totalWidth) {
//draw name
doc.setFontSize(14);
doc.text(x, y, name);
// draw line
const nameLength = (measureLength(name)) + 2;
doc.setLineWidth(0.1);
// i want to start the line after the name ends + 2 mm.
// and end the line in such a way that nameLength + lineLength == totalWidth of the compoenent.
doc.line(x + nameLength, y, x + totalWidth, y);
}
function measureLength(str) {
let canvas = document.createElement('canvas'); // in memory canvas.. not rendered anywere..
let ctx = canvas.getContext("2d")
ctx.font = "14px Arial";
let width = ctx.measureText(str).width;
let mm = ( width * 25.4 ) / 149 // meaning (px * 25.4) / screen DPI
console.log (mm);
return mm; // of course, this calculation turns out wrong..
}
How to make this measureLength function work correctly? Most solutions i found involve DOM but this is PDF.
Notice: I use the same font ('14px Arial') for the PDF document and for the canvas. jsPDF live demo.
Any insight is appreciated, thanks :)

This might resolve your problem:
createLabel(name, x, y, totalWidth) {
doc.setFontSize(14);
doc.text(x, y, name);
// draw line
const nameLength = (doc.getTextDimensions(name).w / (72 / 25.6) ) + 2;
console.log('nameLength', nameLength); // todo remove
doc.setLineWidth(0.1);
// i want to start the line after the name ends + 2 mm.
// and end the line in such a way that nameLength + lineLength == totalWidth of the compoenent.
doc.line(x + nameLength, y, x + totalWidth, y);
}
Check how I calculate nameLength - using build in jsPDF function and converting to mm.
Helpful links:
how to calculate text size
why sometimes calculation might be wrong by few pixels
This is the result:
Remember that you use x + totalWidth for line width, so lines are longer by x compared to manual example at the top

Related

OpenCV Error using function matchTemplate

While using the matchTemplate function in OpenCV, I get the error that the template image is larger than the original image. How to overcome that?
The code is as follows:
def imagecheck(name1):
os.chdir('/content/drive/My Drive/Mad Street Den/Images')
main_image = cv2.imread('image_name_100.jpg')
gray_image = cv2.cvtColor(main_image, cv2.COLOR_BGR2GRAY)
#open the template as gray scale image
os.chdir('/content/drive/My Drive/Mad Street Den/Crops')
template = cv2.imread(name1, 0)
width, height = template.shape[::-1] #get the width and height
#match the template using cv2.matchTemplate
match = cv2.matchTemplate(gray_image, template, cv2.TM_CCOEFF_NORMED)
threshold = 0.9
position = np.where(match >= threshold) #get the location of template in the image
for point in zip(*position[::-1]): #draw the rectangle around the matched template
cv2.rectangle(main_image, point, (point[0] + width, point[1] + height), (0, 204, 153), 2)
#result=[position[1][0],position[0][0],position[0][1],position[0][2]]
result=[]
if (all (position)):
result.append(int(position[1]))
result.append(int(position[0]))
result.append(int(position[1]+width))
result.append(int(position[0]+height))
return (result)
#cv2_imshow(main_image)
for i in range(0,273):
name1='image_name_'+str(i)+'.jpg'
result=imagecheck(name1)
print(name1, ' : ',result)
The Error is
error: OpenCV(3.4.3) /io/opencv/modules/imgproc/src/templmatch.cpp:1107: error: (-215:Assertion failed) _img.size().height <= _templ.size().height && _img.size().width <= _templ.size().width in function 'matchTemplate' site:stackoverflow.com
You can avoid the issue by not attempting to match a template against an image if the template is larger. Compare the template dimensions to the image dimensions and, in this case, return [] if they template is larger in any dimension.

how to draw lines in Pine script (Tradingview)?

Pine editor still does not have built-in functions to plot lines (such as support lines, trend lines).
I could not find any direct or indirect method to draw lines.
I want to build function that look like below (for example only)
draw_line(price1, time1,price2, time2)
any Ideas or suggestions ?
Unfortunately I don't think this is something they want to provide. Noticing several promising posts from 4 years ago that never came through. The only other way, seem to involve some calculations, by approximating your line with some line plots, where you hide the non-relevant parts.
For example:
...
c = close >= open ? lime : red
plot(close, color = c)
would produce something like this:
Then, you could try to replace red with na to get only the green parts.
Example 2
I've done some more experiments. Apparently Pine is so crippled you can't even put a plot in function, so the only way seem to be to use the point slope formula for a line, like this:
//#version=3
study(title="Simple Line", shorttitle='AB', overlay=true)
P1x = input(5744)
P1y = input(1.2727)
P2x = input(5774)
P2y = input(1.2628)
plot(n, color=na, style=line) // hidden plot to show the bar number in indicator
// point slope
m = - (P2y - P1y) / (P2x - P1x)
// plot range
AB = n < P1x or n > P2x ? na : P1y - m*(n - P1x)
LA = (n == P1x) ? P1y : na
LB = (n == P2x) ? P2y : na
plot(AB, title="AB", color=#ff00ff, linewidth=1, style=line, transp=0)
plotshape(LA, title='A', location=location.absolute, color=silver, transp=0, text='A', textcolor=black, style=shape.labeldown)
plotshape(LB, title='B', location=location.absolute, color=silver, transp=0, text='B', textcolor=black, style=shape.labelup )
The result is quite nice, but too inconvenient to use.
UPDATE: 2019-10-01
Apparently they have added some new line functionality to Pinescript 4.0+.
Here is an example of using the new vline() function:
//#version=4
study("vline() Function for Pine Script v4.0+", overlay=true)
vline(BarIndex, Color, LineStyle, LineWidth) => // Verticle Line, 54 lines maximum allowable per indicator
return = line.new(BarIndex, -1000, BarIndex, 1000, xloc.bar_index, extend.both, Color, LineStyle, LineWidth)
if(bar_index%10==0.0)
vline(bar_index, #FF8000ff, line.style_solid, 1) // Variable assignment not required
As for the other "new" line function, I have not tested it yet.
This is now possible in Pine Script v4:
//#version=4
study("Line", overlay=true)
l = line.new(bar_index, high, bar_index[10], low[10], width = 4)
line.delete(l[1])
Here is a vertical line function by midtownsk8rguy on TradingView:
vline(BarIndex, Color, LineStyle, LineWidth) => // Verticle Line Function, ≈50-54 lines maximum allowable per indicator
// return = line.new(BarIndex, 0.0, BarIndex, 100.0, xloc.bar_index, extend.both, Color, LineStyle, LineWidth) // Suitable for study(overlay=false) and RSI, Stochastic, etc...
// return = line.new(BarIndex, -1.0, BarIndex, 1.0, xloc.bar_index, extend.both, Color, LineStyle, LineWidth) // Suitable for study(overlay=false) and +/-1.0 oscillators
return = line.new(BarIndex, low - tr, BarIndex, high + tr, xloc.bar_index, extend.both, Color, LineStyle, LineWidth) // Suitable for study(overlay=true)
if(bar_index%10==0.0) // Generically plots a line every 10 bars
vline(bar_index, #FF8000ff, line.style_solid, 1) // Variable assignment not required
You can also use if barstate.islast if you only draw your lines once instead of on each candle, this way you don't need to delete the previous lines.
More compact code for draw lines:
//#version=3
study("Draw line", overlay=true)
plot(n, color=na, style=line)
AB(x1,x2,y1,y2) => n < x1 or n > x2 ? na : y1 + (y2 - y1) / (x2 - x1) * (n - x1)
plot(AB(10065,10136,3819,3893), color=#ff00ff, linewidth=1, style=line,
transp=0)
plot(AB(10091,10136,3966.5,3931), color=#ff00ff, linewidth=1, style=line,
transp=0)
Here is an example that might answer the original question:
//#version=4
study(title="trendline example aapl", overlay=true)
//#AAPL
line12= line.new(x1=int(1656322200000),
y1=float(143.49),
x2=int(1659519000000),
y2=float(166.59),
extend=extend.right,
xloc=xloc.bar_time)
(to calculate the time it needs to be calculated as the *bar open time in unix milliseconds see: https://currentmillis.com/ ; can be calculated in excel with this formula =
= (([date eg mm/dd/yyyy]+[bar open time eg 9.30am])- 0/24 - DATE(1970,1,1)) * 86400000
= ((6/27/2022+9:30:00 AM)- 0/24 - DATE(1970,1,1)) * 86400000
= ((44739+0.395833333333333)- 0/24 - DATE(1970,1,1)) * 86400000
= 1656322200000
)
adjust the zero/24 to offset the time zone if needed eg 1/24

Fabricjs line coordinates after (moved, scaled, rotated) - canvas.on('object:modified'…

I need to find the Line coordinates(x1,y1,x2,y2) after the object has been modified. (moved, scaled, rotated)
I thought to use the oCoords information and based on angle and flip information to decide which corners are the line ends, but it seems that it will not be too accurate…
Any help?
Example:
x1: 164,
y1: 295.78334045410156,
x2: 451,
y2: 162.78334045410156
x: 163, y: 161.78334045410156 - top left corner
x: 452, y: 161.78334045410156 - top right corner
x: 163, y: 296.78334045410156 - bottom left corner
x: 452, y: 296.78334045410156 - bottom right corner
When Fabric.js calculates oCoords - i.e. object's corners' coordinates - it takes into account the object's strokeWidth:
// fabric.Object.prototype
_getNonTransformedDimensions: function() {
var strokeWidth = this.strokeWidth,
w = this.width + strokeWidth,
h = this.height + strokeWidth;
return { x: w, y: h };
},
For most objects, stroke is kind of a border that outlines the outer edges, so it makes perfect sense to account for strokeWidth it when calculating corner coordinates.
In fabric.Line, though, stroke is used to draw the body of the line. There is no example in the question but I assume this is the reason behind discrepancies between the real end-point coordinates and those in oCoords.
So, if you really want to use oCoords to detect the coordinates of the end points, you'll have to adjust for strokeWidth / 2, e.g.
const realx1 = line.oCoords.tl.x + line.strokeWidth / 2
const realy1 = line.oCoords.tl.y + line.strokeWidth / 2
Keep in mind that fabric.Line's own _getNonTransformedDimensions() does adjust for strokeWidth, but only when the line's width or height equal 0:
// fabric.Line.prototype
_getNonTransformedDimensions: function() {
var dim = this.callSuper('_getNonTransformedDimensions');
if (this.strokeLineCap === 'butt') {
if (this.width === 0) {
dim.y -= this.strokeWidth;
}
if (this.height === 0) {
dim.x -= this.strokeWidth;
}
}
return dim;
},

Convert from latitude, longitude to x, y

I want to convert GPS location (latitude, longitude) into x,y coordinates.
I found many links about this topic and applied it, but it doesn't give me the correct answer!
I am following these steps to test the answer:
(1) firstly, i take two positions and calculate the distance between them using maps.
(2) then convert the two positions into x,y coordinates.
(3) then again calculate distance between the two points in the x,y coordinates
and see if it give me the same result in point(1) or not.
one of the solution i found the following, but it doesn't give me correct answer!
latitude = Math.PI * latitude / 180;
longitude = Math.PI * longitude / 180;
// adjust position by radians
latitude -= 1.570795765134; // subtract 90 degrees (in radians)
// and switch z and y
xPos = (app.radius) * Math.sin(latitude) * Math.cos(longitude);
zPos = (app.radius) * Math.sin(latitude) * Math.sin(longitude);
yPos = (app.radius) * Math.cos(latitude);
also i tried this link but still not work with me well!
any help how to convert from(latitude, longitude) to (x,y) ?
Thanks,
No exact solution exists
There is no isometric map from the sphere to the plane. When you convert lat/lon coordinates from the sphere to x/y coordinates in the plane, you cannot hope that all lengths will be preserved by this operation. You have to accept some kind of deformation. Many different map projections do exist, which can achieve different compromises between preservations of lengths, angles and areas. For smallish parts of earth's surface, transverse Mercator is quite common. You might have heard about UTM. But there are many more.
The formulas you quote compute x/y/z, i.e. a point in 3D space. But even there you'd not get correct distances automatically. The shortest distance between two points on the surface of the sphere would go through that sphere, whereas distances on the earth are mostly geodesic lengths following the surface. So they will be longer.
Approximation for small areas
If the part of the surface of the earth which you want to draw is relatively small, then you can use a very simple approximation. You can simply use the horizontal axis x to denote longitude λ, the vertical axis y to denote latitude φ. The ratio between these should not be 1:1, though. Instead you should use cos(φ0) as the aspect ratio, where φ0 denotes a latitude close to the center of your map. Furthermore, to convert from angles (measured in radians) to lengths, you multiply by the radius of the earth (which in this model is assumed to be a sphere).
x = r λ cos(φ0)
y = r φ
This is simple equirectangular projection. In most cases, you'll be able to compute cos(φ0) only once, which makes subsequent computations of large numbers of points really cheap.
I want to share with you how I managed the problem. I've used the equirectangular projection just like #MvG said, but this method gives you X and Y positions related to the globe (or the entire map), this means that you get global positions. In my case, I wanted to convert coordinates in a small area (about 500m square), so I related the projection point to another 2 points, getting the global positions and relating to local (on screen) positions, just like this:
First, I choose 2 points (top-left and bottom-right) around the area where I want to project, just like this picture:
Once I have the global reference area in lat and lng, I do the same for screen positions. The objects containing this data are shown below.
//top-left reference point
var p0 = {
scrX: 23.69, // Minimum X position on screen
scrY: -0.5, // Minimum Y position on screen
lat: -22.814895, // Latitude
lng: -47.072892 // Longitude
}
//bottom-right reference point
var p1 = {
scrX: 276, // Maximum X position on screen
scrY: 178.9, // Maximum Y position on screen
lat: -22.816419, // Latitude
lng: -47.070563 // Longitude
}
var radius = 6371; //Earth Radius in Km
//## Now I can calculate the global X and Y for each reference point ##\\
// This function converts lat and lng coordinates to GLOBAL X and Y positions
function latlngToGlobalXY(lat, lng){
//Calculates x based on cos of average of the latitudes
let x = radius*lng*Math.cos((p0.lat + p1.lat)/2);
//Calculates y based on latitude
let y = radius*lat;
return {x: x, y: y}
}
// Calculate global X and Y for top-left reference point
p0.pos = latlngToGlobalXY(p0.lat, p0.lng);
// Calculate global X and Y for bottom-right reference point
p1.pos = latlngToGlobalXY(p1.lat, p1.lng);
/*
* This gives me the X and Y in relation to map for the 2 reference points.
* Now we have the global AND screen areas and then we can relate both for the projection point.
*/
// This function converts lat and lng coordinates to SCREEN X and Y positions
function latlngToScreenXY(lat, lng){
//Calculate global X and Y for projection point
let pos = latlngToGlobalXY(lat, lng);
//Calculate the percentage of Global X position in relation to total global width
pos.perX = ((pos.x-p0.pos.x)/(p1.pos.x - p0.pos.x));
//Calculate the percentage of Global Y position in relation to total global height
pos.perY = ((pos.y-p0.pos.y)/(p1.pos.y - p0.pos.y));
//Returns the screen position based on reference points
return {
x: p0.scrX + (p1.scrX - p0.scrX)*pos.perX,
y: p0.scrY + (p1.scrY - p0.scrY)*pos.perY
}
}
//# The usage is like this #\\
var pos = latlngToScreenXY(-22.815319, -47.071718);
$point = $("#point-to-project");
$point.css("left", pos.x+"em");
$point.css("top", pos.y+"em");
As you can see, I made this in javascript, but the calculations can be translated to any language.
P.S. I'm applying the converted positions to an HTML element whose id is "point-to-project". To use this piece of code on your project, you shall create this element (styled as position absolute) or change the "usage" block.
Since this page shows up on top of google while i searched for this same problem, I would like to provide a more practical answers. The answer by MVG is correct but rather theoratical.
I have made a track plotting app for the fitbit ionic in javascript. The code below is how I tackled the problem.
//LOCATION PROVIDER
index.js
var gpsFix = false;
var circumferenceAtLat = 0;
function locationSuccess(pos){
if(!gpsFix){
gpsFix = true;
circumferenceAtLat = Math.cos(pos.coords.latitude*0.01745329251)*111305;
}
pos.x:Math.round(pos.coords.longitude*circumferenceAtLat),
pos.y:Math.round(pos.coords.latitude*110919),
plotTrack(pos);
}
plotting.js
plotTrack(position){
let x = Math.round((this.segments[i].start.x - this.bounds.minX)*this.scale);
let y = Math.round(this.bounds.maxY - this.segments[i].start.y)*this.scale; //heights needs to be inverted
//redraw?
let redraw = false;
//x or y bounds?
if(position.x>this.bounds.maxX){
this.bounds.maxX = (position.x-this.bounds.minX)*1.1+this.bounds.minX; //increase by 10%
redraw = true;
}
if(position.x<this.bounds.minX){
this.bounds.minX = this.bounds.maxX-(this.bounds.maxX-position.x)*1.1;
redraw = true;
};
if(position.y>this.bounds.maxY){
this.bounds.maxY = (position.y-this.bounds.minY)*1.1+this.bounds.minY; //increase by 10%
redraw = true;
}
if(position.y<this.bounds.minY){
this.bounds.minY = this.bounds.maxY-(this.bounds.maxY-position.y)*1.1;
redraw = true;
}
if(redraw){
reDraw();
}
}
function reDraw(){
let xScale = device.screen.width / (this.bounds.maxX-this.bounds.minX);
let yScale = device.screen.height / (this.bounds.maxY-this.bounds.minY);
if(xScale<yScale) this.scale = xScale;
else this.scale = yScale;
//Loop trough your object to redraw all of them
}
For completeness I like to add my python adaption of #allexrm code which worked really well. Thanks again!
radius = 6371 #Earth Radius in KM
class referencePoint:
def __init__(self, scrX, scrY, lat, lng):
self.scrX = scrX
self.scrY = scrY
self.lat = lat
self.lng = lng
# Calculate global X and Y for top-left reference point
p0 = referencePoint(0, 0, 52.526470, 13.403215)
# Calculate global X and Y for bottom-right reference point
p1 = referencePoint(2244, 2060, 52.525035, 13.405809)
# This function converts lat and lng coordinates to GLOBAL X and Y positions
def latlngToGlobalXY(lat, lng):
# Calculates x based on cos of average of the latitudes
x = radius*lng*math.cos((p0.lat + p1.lat)/2)
# Calculates y based on latitude
y = radius*lat
return {'x': x, 'y': y}
# This function converts lat and lng coordinates to SCREEN X and Y positions
def latlngToScreenXY(lat, lng):
# Calculate global X and Y for projection point
pos = latlngToGlobalXY(lat, lng)
# Calculate the percentage of Global X position in relation to total global width
perX = ((pos['x']-p0.pos['x'])/(p1.pos['x'] - p0.pos['x']))
# Calculate the percentage of Global Y position in relation to total global height
perY = ((pos['y']-p0.pos['y'])/(p1.pos['y'] - p0.pos['y']))
# Returns the screen position based on reference points
return {
'x': p0.scrX + (p1.scrX - p0.scrX)*perX,
'y': p0.scrY + (p1.scrY - p0.scrY)*perY
}
pos = latlngToScreenXY(52.525607, 13.404572);
pos['x] and pos['y] contain the translated x & y coordinates of the lat & lng (52.525607, 13.404572)
I hope this is helpful for anyone looking like me for the proper solution to the problem of translating lat lng into a local reference coordinate system.
Best
Its better to convert to utm coordinates, and treat that as x and y.
import utm
u = utm.from_latlon(12.917091, 77.573586)
The result will be (779260.623156606, 1429369.8665238516, 43, 'P')
The first two can be treated as x,y coordinates, the 43P is the UTM Zone, which can be ignored for small areas (width upto 668 km).

Image scale from center of display using matrix

every one.
I'm a android developer.
I want to scale my image from center of displayed part of image with matrix.
So, I scaled my image with matrix. And then moved it with the calculated pointer.
But, the Application not work correctly.
This can't find the correct center, so when it does, it moved right.
Why this is?
I can't find the problem.
The code followed.
matrix.reset();
curScale += 0.02f;
orgImage.getHeight();
w = orgImage.getWidth();
matrix.postScale(curScale, curScale);
rtnBitmap = Bitmap.createBitmap(orgImage, 0, 0, w, h, matrix, true);
curImageView.setImageBitmap(rtnBitmap);
Matrix curZoomOutMatrix = new Matrix();
pointerx =(int ) ((mDisplayWidth/2 - curPosX) * curScale);
curPosX = - pointerx;
pointery =(int ) ((mDisplayWidth/2 - curPosY) * curScale);
curPosY = - pointery;
Log.i("ZoomOut-> posX = ", Integer.toString(curPosX));
Log.i("ZoomOut-> posY = ", Integer.toString(curPosY));
curZoomOutMatrix.postTranslate(curPosX, curPosY);
curImageView.setImageMatrix(curZoomOutMatrix);
curImageView.invalidate();
Did you have any sample code for center zoomIn and zoomOut the imageView with matrix?
Who can explain for that?
Please help me.
Or, It's my fault.
First, I scale the image from original one.
So, The image is (width, height) * scale;
Then I calculate the absolute position of the point that is displayed center. And then, move my ImageView to the calculated position from which the view is. My fault are here.
When i calculate view position, I change the position from now scale.
So, when it scaled, the position is not <original position> * <now scale>. It was <original position * <scale> * <now scale>, the result was strange position.
So i remade add to calculate the center position from original one.
That mode is now following.
public void calculate(float offset) {
float tmpScale = curScale - offset;
float orgWidth = (mDisplayWidth / 2 - curPosX) / tmpScale;
float orgHeight = (mDisplayHeight / 2 - curPosY) / tmpScale;
int tmpPosX = (int)(mDisplayWidth / 2 - orgWidth * curScale);
int tmpPosY = (int)(mDisplayHeight / 2 - orgHeight * curScale);
curPosX = tmpPosX;
curPosY = tmpPosY;
Matrix matrix = new Matrix();
matrix.postTranslate(tmpPosX, tmpPosY);
curImageView.setImageMatrix(matrix);
curImageView.invalidate();
}
Thank you. every one.