How to improve display quality in pdf.js - pdf-generation

I'm using open source library for PDF documents from mozilla(pdf.JS).
When i'm trying to open pdf documents with bad quality, viewer displays it with VERY BAD quality.
But if I open it in reader, or in browser (drag/drop into new window), whis document displays well
Is it possible to change?
Here is this library on github mozilla pdf.js

You just have to change the scaling of your pdf i.e. when rendering a page:
pdfDoc.getPage(num).then(function(page) {
var viewport = page.getViewport(scale);
canvas.height = viewport.height;
canvas.width = viewport.width;
...
It is the scale value you have to change. Then, the resulting rendered image will fit into the canvas given its dimensions e.g. in CSS. What this means is that you produce a bigger image, fit it into the container you had before and so you effectively improve the resolution.

There is renderPage function in web/viewer.js and print resolution is hard-coded in there as 150 DPI.
function renderPage(activeServiceOnEntry, pdfDocument, pageNumber, size) {
var scratchCanvas = activeService.scratchCanvas;
var PRINT_RESOLUTION = 150;
var PRINT_UNITS = PRINT_RESOLUTION / 72.0;
To change print resolution to 300 DPI, simply change the line below.
var PRINT_RESOLUTION = 300;
See How to increase print quality of PDF file with PDF.js viewer for more details.

Maybe it's an issue related with pixel ratio, it used to happen to me when device pixel ratio is bigger than 1 (for example iPhone, iPad, etc.. you can read this question for a better explanation.
Just try that file on PDF.js Viewer. If it works like expected, you must check how PDF.js works with pixel ratio > 1 here. What library basically does is:
canvas.width = viewport.width * window.devicePixelRatio;
canvas.styles.width = viewport.width + 'px'; // Note: The px unit is required here
But you must check how PDF.js works for better perfomance

I ran into the same issue and I used the intent option of renderContent to fix that.
const renderContext = {
intent: 'print',
// ....
}
var renderTask = page.render(renderContext);
As per docs renderContext accepts intent which supports three values - display, print or any. The default is display. When I used print instead the render quality was extremely good, at par with any desktop app.

Related

Resizing image proportionally via css

I know this question has been asked a million times before, however I'm trying to do this a different way, a much simpler way because I don't have to support all the major browsers.
For every image on our site, we know the width and the height before runtime as the cdn returns this info for us, once an image registers I basically extract the CURRENT width and figure out the percentage decrease (if any) of that image.
Example:
var originalWidth = 640;
var originalHeight = 480;
var actualWidth = 431;
var decrease = (originalWidth-actualWidth)/originalWidth*100;
Now that I've got the decrease from it's original size, I wanted to do something with the calc css method, seeing as all our images resize proportionally. I've tried this:
$element.css('height', `calc(${originalHeight}px - (${originalHeight}px * ${decrease} / 100 ))` );
I've can't even get this to apply to the element, if I make a much simpler calc css method it works, but this wont even apply, I'm assuming it's because the actual evaluation is failing, but I can't seem to get the units correct
Maybe it's only a parenthesis problem, try with this
$element.css('height', `calc((${originalHeight}px - ((${originalHeight}px * ${decrease}) / 100 )))` );

How to achieve high quality cropped images from canvas?

I am desperately searching for a good cropping tool. There are a bunch out there, for example:
Croppic
Cropit
Jcrop
The most important thing that I am trying to find is a cropping tool, that crops images without making the cropped image low in resolution. You can hack this by using the canvas tag by resizing the image. This way the image itself stays native, only the representation is smaller.
DarkroomJS was also something near the solution, but, unfortunately, the downloaded demo did not work. I'll try to figure out whats wrong. Does someone know some great alternatives, or how to get the cropped images in...let's say "native" resolution?
Thanks in advance!
You are relying on the cropping tool to provide an interface for the users. the problem is that the image returned is sized to the interface and not the original image. Rather than me sifting through the various API's to see if they provide some way of controlling this behaviour (I assume at least some of them would) and because it is such a simple procedure I will show how to crop the image manually.
To use JCrop as an example
Jcrop provides various events for cropstart, cropmove, cropend... You can add a listener to listen to these events and keep a copy of the current cropping interface state
var currentCrop;
jQuery('#target').on('cropstart cropmove cropend',function(e,s,crop){
currentCrop = crop;
}
I don't know where you have set the interface size and I am assuming the events return the crop details at the interface scale
var interfaceSize = { //you will have to work this out
w : ?,
h : ?.
}
Your original image
var myImage = new Image(); // Assume you know how to load
So when the crop button is clicked you can create the new image by scaling the crop details back to the original image size, creating a canvas at the cropped size, drawing the image so that the cropped area is corectly positioned and returning the canvas as is or as a new image.
// image = image to crop
// crop = the current cropping region
// interfaceSize = the size of the full image in the interface
// returns a new cropped image at full res
function myCrop(image,crop,interfaceSize){
var scaleX = image.width / interfaceSize.w; // get x scale
var scaleY = image.height / interfaceSize.h; // get y scale
// get full res crop region. rounding to pixels
var x = Math.round(crop.x * scaleX);
var y = Math.round(crop.y * scaleY);
var w = Math.round(crop.w * scaleX);
var h = Math.round(crop.h * scaleY);
// Assume crop will never pad
// create an drawable image
var croppedImage = document.createElement("canvas");
croppedImage.width = w;
croppedImage.height = h;
var ctx = croppedImage.getContext("2d");
// draw the image offset so the it is correctly cropped
ctx.drawImage(image,-x,-y);
return croppedImage
}
You then only need to call this function when the crop button is clicked
var croppedImage;
myButtonElement.onclick = function(){
if(currentCrop !== undefined){ // ensure that there is a selected crop
croppedImage = myCrop(myImage,currentCrop,interfaceSize);
}
}
You can convert the image to a dataURL for download, and upload via
imageData = croppedImage.toDataURL(mimeType,quality) // quality is optional and only for "image/jpeg" images

Draw Element's Contents onto a Canvas Element / Capture Website as image using (?) language

I asked a question on SO about compiling an image file from HTML. Michaƫl Witrant responded and told me about the canvas element and html5.
I'm looked on the net and SO, but i haven't found anything regarding drawing a misc element's contents onto a canvas. Is this possible?
For example, say i have a div with a background image. Is there a way to get this element and it's background image 'onto' the canvas? I ask because i found a script that allows one to save the canvas element as a PNG, but what i really want to do is save a collection of DOM elements as an image.
EDIT
It doesn't matter what language, if it could work, i'm willing to attempt it.
For the record, drawWindow only works in Firefox.
This code will only work locally and not on the internet, using drawWindow with an external element creates a security exception.
You'll have to provide us with a lot more context before we can answer anything else.
http://cutycapt.sourceforge.net/
CutyCapt is a command line utility that uses Webkit to render HTML into PNG, PDF, SVG, etc. You would need to interface with it somehow (such as a shell_exec in PHP), but it is pretty robust. Sites render exactly as they do in Webkit browsers.
I've not used CutyCapt specifically, but it came to me highly recommended. And I have used a similar product called WkHtmlToPdf, which has been awesome in my personal experience.
After many attempts using drawWindow parameters, that were drawing wrong parts or the element, I managed to do it with a two steps processing : first capture the whole page in a canvas, then draw a part of this canvas in another one.
This was done in a XUL extension. drawWindow will not work in other browsers, and may not work in a non-privileged context due to security reasons.
function nodeScreenshot(aSaveLocation, aFileName, aDocument, aCSSSelector) {
var doc = aDocument;
var win = doc.defaultView;
var body = doc.body;
var html = doc.documentElement;
var selection = aCSSSelector
? Array.prototype.slice.call(doc.querySelectorAll(aCSSSelector))
: [];
var coords = {
top: 0,
left: 0,
width: Math.max(body.scrollWidth, body.offsetWidth,
html.clientWidth, html.scrollWidth, html.offsetWidth),
height: Math.max(body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight)
var canvas = document.createElement("canvas");
canvas.width = coords.width;
canvas.height = coords.height;
var context = canvas.getContext("2d");
// Draw the whole page
// coords.top and left are 0 here, I tried to pass the result of
// getBoundingClientRect() here but drawWindow was drawing another part,
// maybe because of a margin/padding/position ? Didn't solve it.
context.drawWindow(win, coords.top, coords.left,
coords.width, coords.height, 'rgb(255,255,255)');
if (selection.length) {
var nodeCoords = selection[0].getBoundingClientRect();
var tempCanvas = document.createElement("canvas");
var tempContext = tempCanvas.getContext("2d");
tempCanvas.width = nodeCoords.width;
tempCanvas.height = nodeCoords.height;
// Draw the node part from the whole page canvas into another canvas
// void ctx.drawImage(image, sx, sy, sLargeur, sHauteur,
dx, dy, dLargeur, dHauteur)
tempContext.drawImage(canvas,
nodeCoords.left, nodeCoords.top, nodeCoords.width, nodeCoords.height,
0, 0, nodeCoords.width, nodeCoords.height);
canvas = tempCanvas;
context = tempContext;
}
var dataURL = canvas.toDataURL('image/jpeg', 0.95);
return dataURL;
}

Photoshop Action to fill image to make a certain ratio

I am looking to make a photoshop action (maybe this isn't possible, any other application recommendations would be helpful as well). I want to take a collection of photos and make them a certain aspect ration, ex: 4:3.
So I have an image that is 150px wide by 200px high. What I would like to happen is the image's canvas is made to be 267px wide, with the new area filled with a certain color.
So there are two possibilities I can think of:
1) Photoshop actions could do this, but I would have to pull current height, multiply by 1.333333 and then put that value in the width box of the canvas resize. Is it possible to have calculated values in Photoshop actions?
2) Some other application has this feature built in.
Any help is greatly appreciated.
Wow, I see now (after writing the answer) that this was asked a long time ago. . . oh well. This script does the trick.
This Photoshop script will resize any image's canvas so that it has a 4:5 aspect ratio. You can change the aspect ratio applied by changing arWidth and arHeight. The fill color will be set to the current background color. You could create an action to open a file, apply this script, then close the file to do a batch process.
Shutdown Photoshop.
Copy this javascript into a new file named "Resize Canvas.jsx" in Photoshop's Presets\Scripts folder.
Start Photoshop and in the File - Scripts menu it should appear.
#target photoshop
main ();
function main ()
{
if (app.documents.length < 1)
{
alert ("No document open to resize.");
return;
}
// These can be changed to create images with different aspect ratios.
var arHeight = 4;
var arWidth = 5;
// Apply the resize to Photoshop's active (selected) document.
var doc = app.activeDocument;
// Get the image size in pixels.
var pixelWidth = new UnitValue (doc.width, doc.width.type);
var pixelHeight = new UnitValue (doc.height, doc.height.type);
pixelWidth.convert ('px');
pixelHeight.convert ('px');
// Determine the target aspect ratio and the current aspect ratio of the image.
var targetAr = arWidth / arHeight;
var sourceAr = pixelWidth / pixelHeight;
// Start by setting the current dimensions.
var resizedWidth = pixelWidth;
var resizedHeight = pixelHeight;
// The source image aspect ratio determines which dimension, if any, needs to be changed.
if (sourceAr < targetAr)
resizedWidth = (arWidth * pixelHeight) / arHeight;
else
resizedHeight = (arHeight * pixelWidth) / arWidth;
// Apply the change to the image.
doc.resizeCanvas (resizedWidth, resizedHeight, AnchorPosition.MIDDLECENTER);
}
Mind that the accepted answer from #user268911 may not work for you if the source image has different pixels/inch than 72. Because the UnitValue.convert function works correctly only with 72 px/inch. To be sure the conversion is correct for ever pixel/inch value, set baseUnit property as follows:
...
var pixelWidth = new UnitValue (doc.width, doc.width.type);
pixelWidth.baseUnit = UnitValue (doc.width.baseUnit, "in");
var pixelHeight = new UnitValue (doc.height, doc.height.type);
pixelHeight.baseUnit = UnitValue (doc.height.baseUnit, "in");
...
For more details about the conversion see "Converting pixel and percentage values" section of the Adobe JavaScript Tools Guide.
What languages do you know? ImageMagick has command line tools that can do this, but you'd need to know a scripting language to get the values and calculate the new ones.
For .NET, my company's product, DotImage Photo, is free and can do this (need to know C# or VB.NET)

Codeigniter image manipulation class rotates image during resize

I'm using Codeigniter's image manipulation library to re-size an uploaded image to three sizes, small, normal and large.
The re-sizing is working great. However, if I'm resizing a vertical image, the library is rotating the image so it's horizontal.
These are the config settings I have in place:
$this->resize_config['image_library'] = 'gd2';
$this->resize_config['source_image'] = $this->file_data['full_path'];
$this->resize_config['maintain_ratio'] = TRUE;
// These change based on the type (small, normal, large)
$this->resize_config['new_image'] = './uploads/large/'.$this->new_file_name.'.jpg';
$this->resize_config['width'] = 432;
$this->resize_config['height'] = 288;
I'm not setting the master_dim property because the default it set to auto, which is what I want.
My assumption is that the library would take a vertical image, see that the height is greater than the width and translate the height/width config appropriately so the image remains vertical.
What is happening (apparently) is that the library is rotating the image when it is vertical and sizing it per the configuration.
This is the code in place I have to do the actual re-sizing:
log_message('debug', 'attempting '.$size.' photo resize');
$this->CI->load->library('image_lib');
$this->CI->image_lib->initialize($this->resize_config);
if ($this->CI->image_lib->resize())
{
$return_value = TRUE;
log_message('debug', $size.' photo resize successful');
}
else
{
$this->errors[] = $this->CI->image_lib->display_errors();
log_message('debug', $size.' photo resize failed');
}
$this->CI->image_lib->clear();
return $return_value;
EDIT
I think the problem may be from the upload library. When I get the image_height and image_width back from the upload, the width seems to be larger even though I uploaded a vertical image.
This is a portion of the code I'm using to upload the photo:
$this->upload_config['allowed_types'] = 'jpg|jpeg';
$this->upload_config['max_size'] = '2000';
$this->upload_config['max_width'] = '0';
$this->upload_config['max_height'] = '0';
$this->upload_config['upload_path'] = './uploads/working/';
$this->CI->load->library('upload', $this->upload_config);
if ($this->CI->upload->do_upload($this->posted_file))
{
$this->file_data = $this->CI->upload->data();
$return_value = TRUE;
log_message('debug', 'upload successful');
}
I added some logging to check the values:
$this->is_vertical = $this->file_data['image_height'] > $this->file_data['image_width'];
log_message('debug', 'image height:'.$this->file_data['image_height']);
log_message('debug', 'image width:'.$this->file_data['image_width']);
if ($this->is_vertical)
{
$this->resize_config['master_dim'] = 'height';
}
else
{
$this->resize_config['master_dim'] = 'width';
}
log_message('debug', 'master_dim setting:'.$this->resize_config['master_dim']);
These are the results of the log:
DEBUG - 2010-03-16 18:35:06 --> image height:1536
DEBUG - 2010-03-16 18:35:06 --> image width:2048
DEBUG - 2010-03-16 18:35:06 --> master_dim setting:width
Looking at the image in photoshop, these are the dimensions:
height: 2048
width: 1536
Anyone know what might be causing the upload library to do this?
I've never used this library, but having read the documentation, I wonder whether the master_dim property might help. If you set this to 'height' for vertical images that might keep them the right way up. You could just parse each image through a conditional to see if the image is vertically aligned and then only set this property if need be.
My other thought is about the maintain_ratio property. The documentation says that with this set to 'TRUE' it will resize as close to the target values as possible whilst maintaining the aspect ratio. I wonder if it thinks that rotating the image allows it to preserve this ratio more accurately? As an experiment, try setting this value to 'FALSE' for vertical images.
Ok - I decided not to trust photoshop and opened the images I was testing in quicktime and safari. I discovered that they were actually still horizontal.
So Codeigniter was operating exactly as expected.
I went back into photoshop, did a save for web on the test images, re-uploaded them and it worked as expected.
I then stripped out the extra code that I had added to test whether the image was vertical and the library works as I expected it would.
Now - I need to figure out how to prevent end users from doing this exact thing.
Thanks for taking the time to answer my question musoNic80. Hopefully someone else can learn from my mistakes here.

Resources