开发者

How to calculate how many lines (or records) can fit in the given page size

开发者 https://www.devze.com 2023-03-14 13:21 出处:网络
My problem is to calculate the data (string) that can fit into the given page size (in inches). I ha开发者_C百科ve an application which creates plain vanilla HTML report without using any reporting c

My problem is to calculate the data (string) that can fit into the given page size (in inches).

I ha开发者_C百科ve an application which creates plain vanilla HTML report without using any reporting controls. Now I have to provide paging support in this report. the report is dynamic in nature i.e. columns are decided at run time.

Depending upon the page width, I want to wrap columns in multiple lines. For example, if the page width is 8", i want to fit only first 'n' columns in first line and rest columns can be displayed in second line (or more lines if required). For this I need to calculate how much data can fit in a 8" wide line.

Similarly, I want to calculate the height of data that can fit into the given height of page.

To summarize, how can I calculate how much data can fit into the given page size in inches.

Note: The calculation should also consider the font as it is decided at run time.


I have written a function to get the width of a span as rendered by the browser by adding it to the DOM checking for OffsetWidth and then removing it again. You could probably adapt the principle for other html elements although i doubt that going down that road will be very efficient. My application required this and i only used it to find the longest rendered pixelwidth in a list of strings. If i was you i would consider other approaches for large tables.

Nonetheless here's the function:

function GetTextWidth(text, font, fontSize) {
    var size = 0;
    var spanWidthTestEle = document.createElement("span");
    spanWidthTestEle.id = "spanWidthTest";
    spanWidthTestEle.style.fontFamily = font;
    spanWidthTestEle.style.fontSize = fontSize;
    spanWidthTestEle.innerText = text;
    document.body.appendChild(spanWidthTestEle);
    var spanWidthTest = document.getElementById("spanWidthTest");
    size = spanWidthTest.offsetWidth;
    document.body.removeChild(spanWidthTest);
    return size;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号