Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

addImage produces an blur or too low quality image in the pdf #762

Closed
Balaji-Gopal opened this issue May 25, 2016 · 67 comments
Closed

addImage produces an blur or too low quality image in the pdf #762

Balaji-Gopal opened this issue May 25, 2016 · 67 comments

Comments

@Balaji-Gopal
Copy link

I am using the latest version of jsPDF 1.2.61, While adding an image it adds an blur image even though the image is of high quality, if I the same base64 in on-line decoder it produces the perfect image as the original, but the base64 produces low quality when I use addImage functionality of jsPDF.

Snippet:

var doc = new jsPDF('landscape');
var Imagebase64=null;
doc.setFontSize(20);
doc.text(35, 25, "GoodYear");
var Imagebase64='data:image/jpeg;base64,/';
doc.addImage(imagePath, 'jpeg',0, 5, 210, 35);
doc.save("mypdf.pdf");

@zipzit
Copy link

zipzit commented May 26, 2016

I'm seeing the same thing. I just migrated to 1.2.61 from 1.0.272 (I didn't change anything else in my code) and images and texts drawn on canvas get very blurred when it gets pushed to pdf. This seems different then my previous results.

Canvas in browser.
tubenotcherissue_canvas

PDF extract.
tubenotcher_pdf_test

The pixel mapping from canvas to pdf seems off a bit. Oh, and for reference: each of those top 'tick' marks is spaced exactly 1" from each other.

Don't get me wrong, this is an awesome product, and I'm more than grateful. I will say with this many open issues, I'm feeling mighty guilty for not pitching in and trying to close out an item or two. I will say I found this product pretty confusing on the code side.

And for reference, here's the actual site. Its something custom bike frame manufacturers or custom off-road hobbyists would use. http://dogfeatherdesign.com/ttn_js

@banders
Copy link

banders commented Jun 8, 2016

Same problem here when adding an image from a canvas. I can confirm that image quality looks good in 1.0.272, but is very poor in 1.2.61. I see the issue for both PNG and JPG.

@abureviewer3
Copy link

abureviewer3 commented Jun 11, 2016

I'm too getting the same issue.

@lvbeck
Copy link

lvbeck commented Jul 8, 2016

confirmed in 1.2.61, but only for PNG, JPEG quality is ok but with black background:

the png in 1.0.272 looks like:
old version pn

the png in 1.2.61 looks like:
new version pn

the jpeg in 1.2.61 looks like:
new version jpeg

@DaanGeurts
Copy link

DaanGeurts commented Jul 11, 2016

Same issue here, good quality on 1.0.272 and average/low quality on 1.2.61, both JPG as PNG.

@lvbeck
Copy link

lvbeck commented Jul 12, 2016

in prerelease 1.1.135, the quality is ok

@eliassotodo
Copy link

Same issue on 1.2.61

@bmolaga-r7
Copy link

+1 Same issue for me

@bhavik4748
Copy link

Use below code, it will help you in clearing blur image:

$scope.doc.internal.scaleFactor = 1.55;

@lvbeck
Copy link

lvbeck commented Jul 20, 2016

@bhavik4748 tested with the line, the image quality is slightly improved, but still very poor(aliasing), can not be used in production.

png in 1.2.61

Anyway many thanks.

@ido172
Copy link

ido172 commented Jul 20, 2016

same issue for me on 1.2.61
@bhavik4748 thanks that really helped, I've found it better to do doc.internal.scaleFactor = 1.33;

@bhavik4748
Copy link

try scalefactor of 1.7 or 1.8, image will be small be would be more precise.

@ghost
Copy link

ghost commented Jul 29, 2016

Still getting the same problem even after using the scaling line

@bmolaga-r7
Copy link

@Sketched360 ,

notice that you should set right mimetype for the images ("image/jpeg" , "image/png")

@jalgithub
Copy link

I debugged versions 1 and 2 side by side, and came to the conclusion that this is caused by an undocumented change to the jsPDFAPI.arrayBufferToBinaryString function (line 4267 in the jspdf.debug.js). In this function, the following lines have been added:
if('TextDecoder' in window){ var decoder = new TextDecoder('ascii'); return decoder.decode(buffer); }
Commenting these out and the correct way of rendering the PNG is restored. I'm not sure why it's in there, or why it causes this problem, but at least there's a workaround.

@Didjeeh
Copy link

Didjeeh commented Sep 21, 2016

@jalgithub Nice find. Thanks!

@JulienB37
Copy link

@jalgithub thx. Work fine

@MrRio MrRio added the Bug label Oct 3, 2016
@burtontanner
Copy link

@bhavik4748 where do I insert that line of code? in jspdf.debug.js or in my own code?

@jalgithub
Copy link

@burtontanner Read my comment above to properly restore the old working.

@burtontanner
Copy link

@jalgithub Those lines are commented out in the version of jspdf that I have and the final image is still blurry. I am just searching to see if there is anything else that I can do.

@jalgithub
Copy link

@burtontanner Mmm, that's weird, especially since it worked for me and two others at least. Must be something else then... The line @bhavik4748 is talking about (the scaling factor) can be in your code.

@alouiseq
Copy link

alouiseq commented Nov 7, 2016

v1.3.2 of jsPDF has been updated with the lines @jalgithub mentioned commented out, so you don't have to manually change it. Increasing the scaleFactor does improve text quality, although things such as radio buttons still appear a bit blurred. any updates on a viable solution?

@sanknm
Copy link

sanknm commented Jul 4, 2017

Still looking for Solution
Using Cdn still, don't fix the issue.

@pierre03
Copy link

pierre03 commented Dec 8, 2017

I have the same error, quality is really poor, i tried the code, always the same. is there any other solutions?

@UlricW
Copy link

UlricW commented Mar 20, 2018

any news about it ?

@CaptBli
Copy link

CaptBli commented Mar 27, 2018

Still having trouble. It doesn't look like anyone is actively working on this though. We have taken out the code from: jsPDFAPI.arrayBufferToBinaryString and tried the other scaleFactor items without success.

@jalgithub
Copy link

@CaptBli - I'm not sure what you have tried exactly, but removing line 4268-4271 (debug version) worked for us, which is this code:

    if('TextDecoder' in window){
        var decoder = new TextDecoder('ascii');
        return decoder.decode(buffer);
    }

The only other change we made seems non-related, viz. lines 9481-9485 caused an exception on the require, so we removed those as well. It's this code:

    try {
        var buffer = require('buffer');
        if (typeof buffer.Buffer === 'function')
            _Buffer = buffer.Buffer;
    } catch (error) {}

(Dunno why the catch didn't work, it's quite a while ago and I'm no JavaScript expert.)

Nightfirecat added a commit to Nightfirecat/decklist that referenced this issue Apr 10, 2018
In addition to adding the StarCityGames decksheet format, a number of
under-the-covers changes occurred to facilitate generalizing the
codebase to allow multiple decksheet layouts. Some of these changes
are as follows:

- Decklist parsing (decklist.js) has been fully re-written. All new
  functions accept parameters (usually optional to resemble previous
  behavior as much as possible) and utilize return values rather than
  modifying global variables to allow more predictable behavior, better
  compatibility between decksheets (individual decksheets can utilize
  the return value as needed), and improve ease of testing. The primary
  reason for rewriting parsing was to utilize full card objects (like
  those stored in the global `cards` array) in decklist layout rather
  than simple name-quantity arrays.
- All extraeneous global variables have been removed. The only two that
  remain are necessary for the validation and PDF update timers to
  function.
- The page layout has been updated to include a second radio selection
  above the decklist preview with options for layouts. Additionally,
  both radio selection lists have had their `name` attributes updated
  for ease of selection.
- Both SCG and WotC PDF layout functions have been re-ordered such that
  copy-pasting text from PDFs displays in a more sane format
- `eslint` directives have been added to main.js and decklist.js to
  minimize errors
- Extra js files have been removed
- (incidental) A font sizing bug in the WotC decklist layout has been
  fixed. (previously if no last name was set, font size was too small)
- (incidental) Centered text is now actually centered in the WotC
  decklist layout

With all that said, there are some other possible features that have not
been included in this PR, such as:

- Section overflow looping. Currently, the SCG decklist caps each
  section at 15 cards, and does not push overflow into further (or
  previous) sections.
- Adding handling of a new GET parameter to select decklist. As there
  was no handling for deck sorting, similarly support was not added for
  decklist choice in this PR.
- Disabling of unused fields in specific layouts. The SCG decksheet
  layout does not use all of the same fields which are used in the WotC
  format. (specifically, it does not make use of the Event Date, Event
  Location, and Deck Designer fields) Current behavior is to simply
  ignore the value of these fields while parsing, but allow further
  changes to the fields.
- Smooth out added images. For some reason, they show up rather jagged,
  despite being downscaled from their source images. This may be related
  to parallax/jsPDF#762
  Closest example?: parallax/jsPDF#762 (comment)
- Utilize the full-resolution StarCityGames.com logo. Currently, for
  load time consideration, a low-resolution version of the
  StarCityGames.com logo is loaded, though a higher-resolution copy is
  available in the repository. Ideally, this image and others should no
  longer be loaded as base64 strings, but loaded via FileReader or some
  other API.
  Ref: https://stackoverflow.com/a/20285053

Finally, due to the update to parsing, there are some changes to
existing behavior--primarily small changes in behavior of how
unrecognized cards are sorted in lists. As much as possible, the new
parsing code behaves similarly to existing code, with the caveat that
sorting is not necessarily stable, which likely explains the
previously-mentioned sorting discrepancies.

Closes april#8
Fixes april#38
Supersedes april#35
Supersedes april#39
Supersedes april#40
@irathegod
Copy link

When i click my download link for the code below:

<script type="text/javascript">
    function genPDF()
    {
        html2canvas(document.getElementById("invoicing"), {
        onrendered: function(canvas){
        var img=canvas.toDataURL("image/png");
         var doc=new jsPDF();
         doc.addImage(img, 'PNG', 10, 10);
         doc.save('Invoice for {{=invoice.Client_Surname}} {{=invoice.Client_Name}}.pdf');
            }
        });
    }
  </script>

I get the following message in my web developer console and no pdf:

0ms html2canvas: onrendered option is deprecated, html2canvas returns a Promise with the canvas as the value html2canvas.js:2688:17
160ms html2canvas: Document cloned, using computed rendering html2canvas.js:2674:17
160ms html2canvas: Starting node parsing html2canvas.js:2674:17
189ms html2canvas: Finished parsing node tree html2canvas.js:2674:17
190ms html2canvas: Finished loading 0 images
Array []
html2canvas.js:2674:17
190ms html2canvas: Starting renderer html2canvas.js:2674:17
190ms html2canvas: Canvas renderer initialized (700x681 at 333,417) with scale 1 html2canvas.js:2674:17
198ms html2canvas: Render completed

Please Help me!!! What am i doing wrong???!!!

@jalgithub
Copy link

Hi Ira,
This topic is specifically about the blurry image problem. It's not a generic "please help me" topic. Please start a new topic if you have different questions.

@irathegod
Copy link

I did stipulate that I'm getting a blurry PDF in my 2nd comment above & i hoped to get some help, i tweaked up my code & did not get anything that's when i posted the "please help me" comment but thanks anyway.

@Uzlopak
Copy link
Collaborator

Uzlopak commented Dec 15, 2018

TBH I tried to cut out the canvas code out of addimage.js and have direct file actions. Thus avoiding the problems we have here. If you do a build of the snapshot you will maybe have no blurry images anymore. I will do some final changes this weekend and then post a snapshot of the build to test.

@Uzlopak
Copy link
Collaborator

Uzlopak commented Dec 15, 2018

Did necessary changes to avoid the internal use of canvas, #2140. Canvas is now used if the supplied imagedata is a canvas element or if the file you want to load can not be loaded by the file loading algorythm. But if you anyway cant load the file with the file loading algorythm, you will get anyway a tainted canvas error.

If you use canvas element to supply images, to jsPDF you should increase the dpi/scale and then supply the jpeg-dataurl from the canvas to addImage.

Will supply later a snapshot build.

@Uzlopak
Copy link
Collaborator

Uzlopak commented Dec 15, 2018

@irathegod
If you use latest html2canvas you have to handle the result as a Promise.

@irathegod
Copy link

For my solution I used @nats-afs solution above & it worked like a charm, thak you very very very much @nats-afs, my PDFs are clear as day.

@irathegod
Copy link

This fork for me, i use html2canvas

downloadFile() {
let pdfName = "licencia";
var doc = new jsPDF({
format: "a4"
});

  html2canvas(document.getElementById("pdf-doc"), {
    scale: "5"
  }).then(canvas => {
    console.log("Capturando");
    this.imgFile = canvas;
    doc.addImage(this.imgFile, "JPEG", 5, 5, 200, 285);
    doc.save(pdfName + ".pdf");
  });
}

Thanks alot, nice one mate, solved my problem after weeks of struggling!

@Uzlopak
Copy link
Collaborator

Uzlopak commented Dec 16, 2018

Hello @irathegod

It seems like that your problems described have nothing to do with the problem discussed in this issue.
If you need to extend your knowledge about JavaScript you should read about the Promise technology, as mentioned before.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

Please stop hijacking this thread, which is about addimage issues and not about the lack of basic JavaScript knowledge, which can be googled in 5 minutes.

@irathegod
Copy link

Hello @irathegod

It seems like that your problems described have nothing to do with the problem discussed in this issue.
If you need to extend your knowledge about JavaScript you should read about the Promise technology, as mentioned before.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

Please stop hijacking this thread, which is about addimage issues and not about the lack of basic JavaScript knowledge, which can be googled in 5 minutes.

Thank you Mr @arasabbasi for your cordiality and courtesy, I wish you all the best in all your life endeavors taking into consideration your overwhelming knowledge & understanding in all things, your etiquette will take you far & beyond I promise!

@Uzlopak
Copy link
Collaborator

Uzlopak commented Dec 17, 2018

Hello @irathegod

I understand the sarcasm of your post. If you think I violated the code of conduct of this project, you are free to report me to James.

Fact is that a good amount of people have subscribed this thread and want to be informed about the progress.

From now on off-topic will be deleted.

Tonight I will finally supply a snapshot build and I hope soms people will test it.

@Uzlopak
Copy link
Collaborator

Uzlopak commented Dec 18, 2018

@jalgithub
@BrianMikinski
@shaouari
@zipzit
@Balaji-Gopal

And all others who maybe still interested in the issue:

Here is a snapshot/nightly build of the dist files.

#1819 (comment)

Can you test if it works for you?

@Uzlopak
Copy link
Collaborator

Uzlopak commented Dec 20, 2018

Changes released in v. 1.5.2

@Uzlopak Uzlopak closed this as completed Dec 20, 2018
@katiachumakova
Copy link

I am using jspdf version 1.5.3 and the problem persists.

@Jerther
Copy link

Jerther commented Sep 10, 2019

On my side, it looked like the presisting problem was with the canvas I used, not with jsPDF itself. When I set the scale to 5 in the canvas generation with html2canvas, I get a very crisp image in the PDF. However, the PDF file gets substancially larger so I figured 3 was a good tradeoff.

see #762 (comment)

Don't expect this to be "one line / one minute" fix. Since the default scale is 1 (on my device that is), and I specify 3 for the scale, 1 px on the screen does not equal 1 px on the canvas anymore so some additional calculations were needed to adjust positions and sizes.

Hope this helps.

@wufeng87
Copy link

wufeng87 commented May 6, 2020

Here is my code, and I got the same problem with version 1.5.3 too:

      html2canvas(doc.getElementsByTagName('html')[0]).then(canvas => {
            if (window.fsscConfig.debugPrint) {
                document.body.appendChild(canvas);
                canvas.style.position = 'absolute';
            }

            let contentWidth = canvas.width;
            let contentHeight = canvas.height;
            // 一页pdf显示html页面生成的canvas高度
            let pageHeight = contentWidth / 592.28 * 841.89;
            // 未生成pdf的html页面高度
            let leftHeight = contentHeight;
            // a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
            let imgWidth = 595.28;
            let imgHeight = 592.28 / contentWidth * contentHeight;
            var position = 0;
            let pageData = canvas.toDataURL('image/jpeg', 1.0);
            let pdf = new jsPDF('', 'pt', 'a4');
            // 有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
            // 当内容未超过pdf一页显示的范围,无需分页
            if (leftHeight < pageHeight) {
                pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
            } else {
                while (leftHeight > 0) {
                    pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
                    leftHeight -= pageHeight;
                    position -= 841.89;
                    if (leftHeight > 0) {
                        pdf.addPage();
                    }
                }
            }
            // let pdf = new jsPDF('', 'mm', [canvas.width, canvas.height]);
            // pdf.addImage(pageData, 'png', 0, 0, canvas.width, canvas.height);

            let newServer = server.webServer || server.server;
            let parm;
            // 判断是否以/结尾
            if (newServer.charAt(newServer.length - 1) === '/') {
                parm = `${newServer}#/printToPdf?TOKEN=${sessionStorageUtil.get('TOKEN') || ''}&MenuId=${sessionStorageUtil.get('menuId')}&rdm=${Math.random() * 10}`;
            } else {
                parm = `${newServer}/#/printToPdf?TOKEN=${sessionStorageUtil.get('TOKEN') || ''}&MenuId=${sessionStorageUtil.get('menuId')}&rdm=${Math.random() * 10}`;
            }
            let src = pdf.output('datauristring');
            localStorageUtil.set('billPrint', src);
            let browserInfo = getBrowserInfo();
            if (browserInfo.type === 'IE' && browserInfo.version !== 'edge') {
                pdf.save('打印.pdf');
            } else {
                window.open(parm);
            };
        });

@AndreySurzhan
Copy link

Same issue
+1

  • html2canvas@1.0.0-rc.7
  • @types/jspdf@1.3.3
  • jspdf@2.1.0

@stijnvanderlaan
Copy link

Same issue still available on 2.1.1

@tahir-jamil
Copy link

any update?

@skreamozz
Copy link

same issue for me on 1.2.61
@bhavik4748 thanks that really helped, I've found it better to do doc.internal.scaleFactor = 1.33;


const scaleFactor = 3

doc.internal.scaleFactor = scaleFactor;

canvas.height = canvas.height * scaleFactor;
canvas.width = canvas.width * scaleFactor;

ctx.scale(scaleFactor,scaleFactor);

@ParthSanghavi1031499
Copy link

This fork for me, i use html2canvas
downloadFile() {
let pdfName = "licencia";
var doc = new jsPDF({
format: "a4"
});

  html2canvas(document.getElementById("pdf-doc"), {
    scale: "5"
  }).then(canvas => {
    console.log("Capturando");
    this.imgFile = canvas;
    doc.addImage(this.imgFile, "JPEG", 5, 5, 200, 285);
    doc.save(pdfName + ".pdf");
  });
}

Thanks alot, nice one mate, solved my problem after weeks of struggling!

Worked for me. Thanks

@leo-desbureaux-tellae
Copy link

Hello !

I am encountering blur issues when using addImage.

Seeing the last comments I see that people were still using workarounds, but this was back in 2021.
Is the problem considered as solved now ? I don't see any solution outstanding from this thread, nor in the few stackoverflow posts about this blur issue.

I am not quite used to unit conversions and canvas manipulations, so maybe the problem is on me, but I just wanted to make sure.

@jalgithub
Copy link

Seeing the last comments I see that people were still using workarounds, but this was back in 2021. Is the problem considered as solved now ? I don't see any solution outstanding from this thread, nor in the few stackoverflow posts about this blur issue.

The last version of jsPDF seems to be from around that time, so it's not really actively maintained, unfortunately.

@anhtaw
Copy link

anhtaw commented Jul 5, 2024

please help me

@jalgithub
Copy link

please help me

Help you with what?

@anhtaw
Copy link

anhtaw commented Jul 5, 2024

please help me

Help you with what?

I convert html to pdfjs but open file pdf error front character ( ư ụ ủ v.v )

@jalgithub
Copy link

jalgithub commented Jul 5, 2024

I convert html to pdfjs but open file pdf error front character ( ư ụ ủ v.v )

That has nothing to do with this issue. This is a bugtracker, and the specific topic is blurry images. Please open a new bug for your problem. Also, you can't ask for help: you need to report a bug. This is not a forum.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests