Giter Club home page Giter Club logo

pdf-lib's People

Contributors

andrew-trefethen avatar bockoblur avatar btecu avatar cocoliliace avatar cshenks avatar cymen avatar dependabot[bot] avatar dkdavid avatar ggrossetie avatar hopding avatar jbeuckm avatar jlmessenger avatar jwoodrow avatar lucashmorais avatar masterwow3 avatar mcshaz avatar milesnash avatar mohamedsalem401 avatar oktapodia avatar pjm4 avatar sebastinez avatar soadzoor avatar ssssota avatar taxilian avatar tessi avatar thebenlamm avatar trapfether avatar zackdotcomputer avatar ztoben avatar zwaldowski avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pdf-lib's Issues

Is it possible to compress images in an existing PDF?

I'm building an app that allows users to upload PDFs to a server. I'd like to compress the images in the PDFs to cut down on the file size, since sometimes the PDFs can be over 30MB.

I see that pdf-lib has many options for modifying existing PDFs, but that it is mainly to add text or images to the existing document, or to add pages. Can pdf-lib compress the existing images, and if not, is that a feature it may support in the future?

Issue embedding fonts

Hi!
Your library is fantastic, thanks so much for your work here. I'm having some kind of problem embedding fonts. I'm using pdf-lib to write to files, and pdf.js to display them. Here's my scenario. I have a pdf that I've embedded a non standard font in, and written some text, I can view it in pdf.js without issue. If I then write another string of text to it in a different font, either standard or non-standard, I get warnings from pdfjs about not being able to find the first font I embedded.

Here's an example error from pdf.js:

Warning: fontRef not available
Warning: Error during font loading: Font La Belle Aurore is not available

Here's some of my code I'm using to draw text in the pdf:

drawText: function(pageIndex, x, y, text, fontFamily, fontSize){
    var me = this;
  
    var pages = me.pdfDoc.getPages();
    var page  = pages[pageIndex];
  
    //https://github.com/Hopding/pdf-lib/issues/10#issuecomment-402326518
    var toWidth = page.get('MediaBox').array[2].number;
    var toHeight = page.get('MediaBox').array[3].number;
  
    var embeddedFont = null;
    if(me.isStandardFont(fontFamily)){
      embeddedFont = me.pdfDoc.embedStandardFont(fontFamily)[0];
    }
    else{
      embeddedFont = me.pdfDoc.embedFont(me.getFontData(fontFamily))[0];
    }
  
    fontSize = +fontSize.split('px')[0];
    
    page.addFontDictionary(fontFamily, embeddedFont);
    var contentStream = me.pdfDoc.createContentStream(
      window.PDFLib.drawText(text, {
        x: x,
        y: toHeight - y - fontSize,
        size: fontSize,
        font: fontFamily,
        colorRgb: [0,0,0],
      })
    );
  
    page.addContentStreams(me.pdfDoc.register(contentStream));
 }

It appears that if I re-embed the first non-standard font I used, things seem to work. In order to view the changes I made, I call PDFLib.PDFDocumentWriter.saveToBytes(), process that into a base 64 string, and pass that into pdf.js. It works except for this font issue.

I know that's complicated, and involves a library that isn't yours. Does that make sense? Do you have any ideas I could try? Thanks for your help!

Working with a PDF document encrypted with User Password

Hi @Hopding. Is it possible to perform any manipulations with a PDF document encrypted with User Password?

Now when trying to open a user password encrypted PDF the lib fails at node_modules/pdf-lib/lib/core/pdf-parser/parseDict.js:55 line:

var _a = parseName_1.default(remainder) || utils_1.error('Failed to parse dictionary key'), key = _a[0], r1 = _a[1];

Draw Text with fixed Width

Hi, guys. That would be great if you to add drawing text with fixed width so that the text would wrap the next lines.

Invalid PDFs on modification

I cannot get this to work as intended - it always results in a PDF that cannot be opened due to errors.

Even if I run the modification example within the repo, it's the same thing.

Am I missing something? No errors are being generated and the output file is produced but just looks like the resulting PDF is corrupted or something.

Let me know if you need more info.

Thanks.

Missing PDFDictionary entry "MediaBox"

Hi @Hopding,
Sorry for another ticket, but I have another pdf that's throwing errors during drawText(). I'm trying to detect the size of the page, using this call, which I picked up from here

var toHeight = page.get('MediaBox').array[3].number;

The file is attached, and here's the exception:

Error: Missing PDFDictionary entry "MediaBox".
    at error (pdf-lib.js:1061)
    at PDFPage.PDFDictionary$$1._this.get (pdf-lib.js:1953)
    at constructor.drawText (PDFGenerationHelper.js?_dc=1546970445137:97)

text_only_pdfa1b.pdf

Thanks for your help!

Text in multiple lines

Hi! First of all, thanks a lot for this library.

I am trying to paint a long and dynamic text that comes from an API, the text is content of multiple paragraphs that must be painted on one or several pages, the characters have not been identified, I use "drawText (text, options);" the result is painted on a single line, it outside the canvas. (Attached image)

captura de pantalla 2019-01-28 a las 10 20 16

How can it be achieved so that the text is painted in multiple lines and pages?

On the other hand, when a text contains characters like '\ r' or '\ n' (manually split), I use "drawLinesOfText (text.split ('\ n'), options);", and the result is correct, but If the text is too long, how should a new page be generated with the remaining text?
(attached image)

captura de pantalla 2019-01-28 a las 10 39 39
How can it be achieved so that the text is painted on multiple pages?

Thansk!

Problem with PDFDocumentFactory.load some usual non-encrypted PDF documents

Hi @Hopding. There are problems with importing some usual non-encrypted PDF documents via PDFDocumentFactory.load method. While these documents are still could be opened by common viewer programs and even other libraries still can manage with that files (e.d. modify and so on). Problems I faced so far:

at node_modules/pdf-lib/es/core/pdf-document/PDFDocument.js:249
validate(catalog, isInstance(PDFCatalog), '"catalog" must be a PDFCatalog object');

at node_modules/pdf-lib/lib/core/pdf-parser/parseDict.js:67
utils_1.error('Failed to parse dictionary value'), pdfObject = _b[0], r2 = _b[1];

If it helps, I think I could even provide those pdf files that cause problems.

Error: Incorrectly parsed object contents

Hi Guys,
I'm seeing an error parsing this pdf. I've attached it, and here's the relevant portion of the stack:

I see this with v0.4.0, and v0.6.0.

error loading pdf-lib Error: Incorrectly parsed object contents
    at mo (pdf-lib.min.js:1)
    at rI (pdf-lib.min.js:1)
    at pdf-lib.min.js:1
    at cI (pdf-lib.min.js:1)
    at Object.parse (pdf-lib.min.js:1)

parsing error.pdf

Thanks for your help!
Kevin

Error: Failed to parse array element

Hi again,
One more load error for you. I'm on v0.6.1-rc2. Thanks again!

Error: Failed to parse array element
    at error (pdf-lib.js:8569)
    at parseArray (pdf-lib.js:46691)
    at parseDict (pdf-lib.js:46635)
    at parseDictOrStream (pdf-lib.js:46908)
    at parseIndirectObj (pdf-lib.js:46947)
    at parseBodySection (pdf-lib.js:47174)
    at parseDocument (pdf-lib.js:47226)
    at PDFParser.parse (pdf-lib.js:47257)
    at Function.PDFDocumentFactory.load (pdf-lib.js:47379)

This is a doc (1).pdf

Failed to parse dictionary value

Hi @Hopding ,
Got another bug for you. I'm on v0.6.1-rc2. Let me know if you have any questions! Thanks again for your help.

Error: Failed to parse dictionary value
    at error (pdf-lib.js:8569)
    at parseDict (pdf-lib.js:46642)
    at parseDictOrStream (pdf-lib.js:46908)
    at parseIndirectObj (pdf-lib.js:46947)
    at parseBodySection (pdf-lib.js:47174)
    at parseDocument (pdf-lib.js:47226)
    at PDFParser.parse (pdf-lib.js:47257)
    at Function.PDFDocumentFactory.load (pdf-lib.js:47379)

test.pdf

Object.values polyfill

Hello Hopding! Thanks for the great library, it's been very useful so far.

I've been struggling with getting it compatible with IE11, though.
Do you have any idea how to get around polyfilling the Object.values() method?

Perhaps I'm just unaware of a good solution, core-js doesn't seem to help me here..

Example of modifying existing "word"

First off, thanks for this great project, it looks like you have made awesome progress on it. I am looking for a way to modify an existing word inside a pdf. For example, say I want to replace any instance of the in the document and replace it with an all caps version THE.

An example of what I'm hoping for might be something like this:

import { PDFDocumentFactory, PDFDocumentWriter, drawText } from 'pdf-lib';

const existingPdfDocBytes = fs.readFileSync('testFiles/test.pdf');
const pdfDoc = PDFDocumentFactory.load(existingPdfDocBytes);
const pages = pdfDoc.getPages();

// Code describing what I think I want to do
pages.forEach(function(page) {
  // Need to look through each word on each page:
  page.Content.magicFunction.words.forEach(function(word){
    let wordText = word.toString();
    if (wordText.match(/^the$/)) {
      wordText = wordText.toUpperCase();
    }

    drawText(
      wordText,
      word.coordinates.x,
      words.coordinates.y,
      ...
    );
  });
});

Is this in the scope of the project? Is it already implemented and I'm just missing it? Thanks for your time. If this isn't in the scope feel free to just close this.

X and Y units

Hi, guys. What are the units for x and y for positioning of a text or image? Have found nothing about this at docs and api.

Error when parsing some PDF documents

Version: [email protected]

Unfortunately I'm unable to provide the offending documents as they come from a customer.

TypeError: Cannot read property '0' of null
  at parseObjData (.../node_modules/pdf-lib/lib/core/pdf-parser/parseObjectStream.js:44:64)
  at Object.parseObjectStream [as default] (.../node_modules/pdf-lib/lib/core/pdf-parser/parseObjectStream.js:67:19)
  at Object.exports.default (.../node_modules/pdf-lib/lib/core/pdf-parser/parseStream.js:82:55)
  at Object.parseDictOrStream [as default] (.../node_modules/pdf-lib/lib/core/pdf-parser/parseDictOrStream.js:28:44)
  at Object.parseIndirectObj [as default] (.../node_modules/pdf-lib/lib/core/pdf-parser/parseIndirectObj.js:43:41)
  at parseBodySection (.../node_modules/pdf-lib/lib/core/pdf-parser/parseDocument.js:24:48)
  at Object.parseDocument [as default] (.../node_modules/pdf-lib/lib/core/pdf-parser/parseDocument.js:78:21)
  at PDFParser.parse (.../node_modules/pdf-lib/lib/core/pdf-parser/PDFParser.js:38:40)
  at Function.PDFDocumentFactory.load (.../node_modules/pdf-lib/lib/core/pdf-document/PDFDocumentFactory.js:45:35)
  at FileModel.<anonymous> (.../src/models/file.model.ts:128:40)

Page width and height

Hi @Hopding. Is it possible to know width and height of a page? For instance, when we iterate over pages got by const pages = pdfDoc.getPages();

Exception from drawText()

Hi again guys,
I'm getting an error back from drawText on a specific pdf file. The pdf itself is sensitive and I can't upload it, but I have a stack trace for you.

pdf-lib.min.js:1 Uncaught TypeError: Cannot read property '0' of undefined
    at s.i.normalizeCTM (pdf-lib.min.js:1)
    at s.i.addContentStreams (pdf-lib.min.js:1)
    at C.drawText (all-classes.js:1)

Here's my code calling drawText(). As far as I can tell all arguments are input correctly.

var pages = me.pdfDoc.getPages();
var page  = pages[pageIndex];

var toWidth = page.get('MediaBox').array[2].number;
var toHeight = page.get('MediaBox').array[3].number;

var embeddedFontRef = null;
var embeddedFont = null;
if(me.isStandardFont(fontFamily)){
  var arr = me.pdfDoc.embedStandardFont(fontFamily);
  embeddedFontRef = arr[0];
  embeddedFont = arr[1];
}
else{
  var arr = me.pdfDoc.embedNonstandardFont(me.getFontData(fontFamily));
  embeddedFontRef = arr[0];
  embeddedFont = arr[1];
}

fontSize = +fontSize.split('px')[0];
page.addFontDictionary(fontFamily, embeddedFontRef);

var encodedText = null;
if(embeddedFont && typeof embeddedFont.encodeText === "function"){
  console.log('encoding text', text);
  encodedText = embeddedFont.encodeText(text);
  console.log('text encoded', encodedText);
}
else{
  console.log('not encoding text');
  encodedText = text;
}

var contentStream = me.pdfDoc.createContentStream(
  window.PDFLib.drawText(encodedText, {
    x: (x / scale),
    y: toHeight - ((y + fontSize) / scale),
    size: (fontSize / scale),
    font: fontFamily,
    colorRgb: [0,0,0],
  })
);

page.addContentStreams(me.pdfDoc.register(contentStream));

Any thoughts?
Thanks for your help!
Kevin

Page's Y axis positioning

Hi, guys. That would be great if you to add support of both bottom and top positioning for Y axis on a page while adding texts or images.

Centering text

I am trying to setup a process to essentially stamp values at certain spots on an existing PDF file (a completion certificate for a user of our software). Pretty easy to get going and I have a basic working sample. What I have not been able to figure out is how to center text on the page (or right align) when the text is a variable length.

What is the best approach to handle this?

Thanks!

Error: Failed to parse dictionary key

Hi @Hopding
Got another pdf load error for you. It's not a really useful pdf, but I thought you might want to look at it. I'm on v0.6.1-rc2. Thanks!

Error: Failed to parse dictionary key
    at error (pdf-lib.js:8569)
    at parseDict (pdf-lib.js:46630)
    at parseDictOrStream (pdf-lib.js:46908)
    at parseIndirectObj (pdf-lib.js:46947)
    at parseBodySection (pdf-lib.js:47174)
    at parseDocument (pdf-lib.js:47226)
    at PDFParser.parse (pdf-lib.js:47257)
    at Function.PDFDocumentFactory.load (pdf-lib.js:47379)

giraffe.pdf

How to get/set Annot or Widget from pdf

Hey, is it possible to get/set Annot or Widget for existing pdf file?
I'm trying to replace this pdfkit code with your library

const signature = pdf.ref({
  Type: 'Sig',
  Filter: 'Adobe.PPKLite',
  SubFilter: 'adbe.pkcs7.detached',
  ByteRange: [
    0,
    DEFAULT_BYTE_RANGE_PLACEHOLDER,
    DEFAULT_BYTE_RANGE_PLACEHOLDER,
    DEFAULT_BYTE_RANGE_PLACEHOLDER,
  ],
  Contents: Buffer.from(String.fromCharCode(0).repeat(signatureLength)),
  Reason: new String(reason), // eslint-disable-line no-new-wrappers
  M: new Date(),
});

// Generate signature annotation widget
const widget = pdf.ref({
  Type: 'Annot',
  Subtype: 'Widget',
  FT: 'Sig',
  Rect: [0, 0, 0, 0],
  V: signature,
  T: new String('Signature1'), // eslint-disable-line no-new-wrappers
  F: 4,
  P: pdf._root.data.Pages.data.Kids[0], // eslint-disable-line no-underscore-dangle
});

// Include the widget in a page
pdf._root.data.Pages.data.Kids[0].data.Annots = [widget];

// Create a form (with the widget) and link in the _root
const form = pdf.ref({
  SigFlags: 3,
  Fields: [widget],
});
pdf._root.data.AcroForm = form;

Thanks!

Copying a page

This library is fantastic and easy to work with, however, I've run into a snag.
I am loading an existing 1 page PDF and would like to duplicate the first page multiple times before I start adding text and images.

I can get a reference to the first page and then use:
this.pdfDoc.addPage(this.pages[0]);
or even
this.pdfDoc.insertPage(1, this.pages[0]);

This will successfully copy the page, however, when I then add the content stream to page 0,
this.pages[0].addContentStreams...etc.
...it also adds the identical content stream to the second page. It seems like my pages are the same instance of the page. How can I modify these pages separately?

Thanks again for the amazing library!
-mike

Combine multiple PDFs bug?

Hi, I'm trying to combine multiple similar PDFs.

All 4 input files are nearly identical, except for a text with some unique number.
All PDFs have a single page.
The output PDF has 4 pages, yet all pages are identical.

const PDFLib = require("pdf-lib");

/**
 * Combines multiple PDFs into one.
 * 
 * @param {Buffer[]} arrBuffers 
 */
async function combine(arrBuffers)
{
	if(!arrBuffers.length)
	{
		throw new Error("arrBuffers is empty. Need at least one PDF to do something right.");
	}
	
	const finalPDF = PDFLib.PDFDocumentFactory.load(arrBuffers.shift());

	while(arrBuffers.length)
	{
		const extraPDF = PDFLib.PDFDocumentFactory.load(arrBuffers.shift());

		for(const page of extraPDF.getPages())
		{
			finalPDF.addPage(page);
		}
	}

	return await PDFLib.PDFDocumentWriter.saveToBytes(finalPDF);
};

Error: Invalid Stream!

Hi @Hopding
I've got one more for you. I'm on v0.6.1-rc2. I'm unable to attach the pdf here because it has some private information in it, however I could send it to you privately. Please let me know the best way to do this. Thanks again!

Error: Invalid Stream!
    at error (pdf-lib.js:8569)
    at parseStream (pdf-lib.js:46840)
    at parseStream$1 (pdf-lib.js:46870)
    at parseDictOrStream (pdf-lib.js:46913)
    at parseIndirectObj (pdf-lib.js:46947)
    at parseBodySection (pdf-lib.js:47174)
    at parseDocument (pdf-lib.js:47226)
    at PDFParser.parse (pdf-lib.js:47257)
    at Function.PDFDocumentFactory.load (pdf-lib.js:47379)

Dimensions and aligning issues when trying to draw a rectangle

Hi Hopding,
Thanks for the good work, we are using this library to add a redact feature on the PDF.
So we have used the translate to set the axis as (0, pageheight). Whenever we increase the width of the box, the position of our box does appear in the place where we actually placed it in our frontend editor, it works perfectly fine for a square box.

Feeding PDFKit into pdf-lib

I'm using PDFKit/Svg-to_PDF to convert SVG maps to a GeoPDF aalong with the sajjad-shirazy/pdfkit.js fork of PDFKit to insert SPOT colors. Works great. But I also have a requirement to output PDF Version 1.4 or greater files. PDFKit only produces v1.3 PDFs.

Your library is outputting v1.7 PDFs. I can work with that, but it doesn't have all of the SVG and SPOT color features.

So what I am trying to do it take the completed PDFKit:PDFDocument, convert it to a byte array and use it with PDFLib.PDFDocumentFactory and PDFLib.PDFDocumentWriter to try to output a v1.7 document.

But every time I try to invoke PDFLib.PDFDocumentFactory it throws an error.

var pdfDoc = PDFLib.PDFDocumentFactory.load(pdfByteArray);

[undefined] - TypeError: e.subarray is not a function

Obviously I'm doing something wrong, I just can't figure out what it is.

I'm testing in Chrome 67.

Any help would be appreciated. I can provide code snippets if you need it.

load .pdf from browser

Hi,
I'm stuck with this explanation :

// This should be a Uint8Array.
// In the browser, you could make a fetch() call and use res.arrayBuffer().

Can someone explain a bit more about this ?
Can this be done with ajax request ?

EDIT
Almost got it with

fetch('docs/example.pdf')
      .then(function(response) {
            response.arrayBuffer().then(function(buffer) {
              const existingPdfDocBytes = buffer[""[[Uint8Array]]""]

But that opens the pdf in the window, don't know why...

Add metadata

Hello,

Is it possible to add metadata to the PDF?

Thanks!

Rotation of text / images when inserting

Thanks for this module. I was wondering if there was a way to rotate text that is being inserted on an existing document. I need to insert some text and images upside down. I know I could do image processing to make the images upside down, just wondering if rotation was built in.

Might there be parameters like rotate, rotateOrigin?

Thanks

Corrupt PDF issue

Hi,

I've got a complex PDF file that doesn't save correctly when run through pdf-lib - although it does load OK and renders with other libraries. If I simply load the file and then save it again through pdf-lib, the resultant file doesn't render correctly in Chrome's PDF viewer (it seems to stop drawing before everything is on-screen), and if I open it in Adobe Reader, I get the following error:

The font 'UZCHSP+Helvetica' contains a bad /BBox.

The PDF does contain the Helvetica font, but it doesn't contain a font called 'UZCHSP+Helvetica', so I'm not sure where this is coming from.

If I open the file in Adobe Acrobat and resave it, the resultant file is a bit smaller and then pdf-lib processes it just fine.

Unfortunately, I'm not 100% sure if I can share the PDF file publicly as it is copyrighted, so currently I'm just looking for any pointers or tips as to where I could look to find the problem - and I'll share my results here.

I was thinking maybe if I could find a list of fonts used in the PDF via pdf-lib, I could then also look up the bounding boxes for the font glyphs and that might shed some light on the matter. But, I can't work out how to see the fonts that are held in the file. Any ideas?

Thanks,

Chris.

_this.catalog.Pages.traverse is not a function

As the title, I got that error when attaching some text on my pdf file.
here is full error logs

Found Linearization param dict and cross reference index, but no associated trailer.
/Users/minhnhat/Documents/MN/test/pdf-lib/examples/document_modification/node/node_modules/pdf-lib/lib/core/pdf-document/PDFDocument.js:48
            _this.catalog.Pages.traverse(function (kid) {
                                ^

TypeError: _this.catalog.Pages.traverse is not a function
    at PDFDocument.getPages (/Users/minhnhat/Documents/MN/test/pdf-lib/examples/document_modification/node/node_modules/pdf-lib/lib/core/pdf-document/PDFDocument.js:48:33)
    at Object.<anonymous> (/Users/minhnhat/Documents/MN/test/pdf-lib/examples/document_modification/node/index.js:49:22)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Function.Module.runMain (module.js:694:10)
    at startup (bootstrap_node.js:204:16)
    at bootstrap_node.js:625:3

Could you guys help me find the problem?

Delete a page from pdf?

How we can delete a page from pdf and display the thumbnail using pdf-lib? Can you please help me?

Embedding emoji and other characters via drawText

Hi Guys,
I'm using drawText() to write user-inputted text to a pdf. It works great for most cases, but I'm noticing that embedding things like emoji and other special characters (eg. ΒΆ) aren't properly written to the document. Is it possible to support that?
Thanks again!

Adding transparent PNG image falls behind the PDF form elements.

When the .png transparent image is added to existing PDF Document with pdf form elements - it is rendered behind the pdf elements (like z-order problem). It should be possible to force any added image to be on top of all existing elements. I did it with iText (overlay) and it worked. Here is a piece of code I used to add image with pdf-lib:

const imgName = "Img_" + getUniqueNum();
const [img, imgDims] = pdfDoc.embedPNG(imageUint8Array);

  let contentStream = pdfDoc.createContentStream(
    drawImage(imgName, {
      x: posLeft,
      y: posBottom,
      width: tagWidth,
      height: tagHeight
    })
  );

  const pages = pdfDoc.getPages();
  const page  = pages[pageIndex];

  page.addImageObject(imgName, img).addContentStreams(pdfDoc.register(contentStream)).normalizeCTM();

The resulting screenshot is attached.

Thanks,
Andrei.


screenshot from 2018-10-08 12-20-56

"Uncaught (in promise) Error: Invalid Stream!"

at error (pdf-lib.js:17961)
at parseStream (pdf-lib.js:30748)
at parseStream$1 (pdf-lib.js:30777)
at parseDictOrStream (pdf-lib.js:30820)
at parseIndirectObj (pdf-lib.js:30853)
at parseBodySection (pdf-lib.js:31079)
at parseDocument (pdf-lib.js:31133)
at PDFParser.parse (pdf-lib.js:31162)
at Function.PDFDocumentFactory.load (pdf-lib.js:31272)
at fetch.then.then.buf (account.js:5)

My code:

fetch('receipt.pdf')
    .then(resp => resp.arrayBuffer())
    .then(buf => {
        PDFLib.PDFDocumentFactory.load(new Uint8Array(buf));
    })

receipt.pdf

PDF optimization

Hi! First of all, thanks a lot for this library.

I'd like to ask if you are planning on adding PDF optimization at some point. When I print a PDF with Acrobat, it processes the PDF for about 5 seconds (optimizing, flattening...) and then sends it to the printer quite fast. On the other hand, when I send the same PDF to the printer directly from the browser it takes a surprisingly large amount of time (without optimizations, I assume).

I've seen in the roadmap something like Consider detecting and removing duplicate objects to reduce file size but I'm not sure if that would improve printing time or it mostly depends on something else. Otherwise, if this is out of the scope of this library, would you have any pointers that could help speed up printing time?
Thansk again!

drawText() draws with the wrong orientation on specific file

Hi guys,
I have a file here that appears to be detected in the wrong orientation. If I view it, it shows in portrait mode. If I call drawText() on it, it draws my text in the doc as if it had been rotated 90 degrees. So it draws text at the proper coordinates, but from the bottom left of the page, and rotated vertically.

If I view the file in finder on a mac, it views in portrait mode, but I can see that the pixel height/width is flipped. If I re-save the file this gets fixed. I'm unable to share this file, as it has sensitive information in it.

It definitely looks like there's a problem with the file, is there any way I can detect this scenario and possibly correct for it?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.