Giter Club home page Giter Club logo

hummusrecipe's Introduction

Hummus Recipe

All Contributors

npm version Build Status Donate

This is an easy recipe for HummusJS with a high level class.

I hope this repo will bring more attentions from the community to help HummusJS to grow faster.

Feel free to open issues to help us!

Features

  • Javascript with C++ library.
  • High performance creation, modification and parsing of PDF files and streams.
  • Easy to create and modify PDF files.
  • Reusable components.
  • Support Basic HTML elements to text

Documentation

Instructions

GetStarted

npm i hummus-recipe --save

Coordinate System

In order to make things easier, I use Left-Top as center [0,0] instead of Left-Bottom. You may write and edit the pdf like you write things on papers from the left top corner. It is similar to the Html Canvas

pdfDoc
    .text('start from here', 0, 0)
    .text('next line', 0, 20)
    .text('some other texts', 100, 100)
    ...

Create a new PDF

const HummusRecipe = require('hummus-recipe');
const pdfDoc = new HummusRecipe('new', 'output.pdf',{
    version: 1.6,
    author: 'John Doe',
    title: 'Hummus Recipe',
    subject: 'A brand new PDF'
});

pdfDoc
    .createPage('letter-size')
    .endPage()
    .endPDF();
const HummusRecipe = require('hummus-recipe');
const pdfDoc = new HummusRecipe('new', 'output.pdf');
pdfDoc
    // 1st Page
    .createPage('letter-size')
    .circle('center', 100, 30, { stroke: '#3b7721', fill: '#eee000' })
    .polygon([ [50, 250], [100, 200], [512, 200], [562, 250], [512, 300], [100, 300], [50, 250] ], {
        color: [153, 143, 32],
        stroke: [0, 0, 140],
        fill: [153, 143, 32],
        lineWidth: 5
    })
    .rectangle(240, 400, 50, 50, {
        stroke: '#3b7721',
        fill: '#eee000',
        lineWidth: 6,
        opacity: 0.3
    })
    .moveTo(200, 600)
    .lineTo('center', 650)
    .lineTo(412, 600)
    .text('Welcome to Hummus-Recipe', 'center', 250, {
        color: '#066099',
        fontSize: 30,
        bold: true,
        font: 'Helvatica',
        align: 'center center',
        opacity: 0.8,
        rotation: 180
    })
    .text('some text box', 450, 400, {
        color: '#066099',
        fontSize: 20,
        font: 'Courier New',
        strikeOut: true,
        highlight: {
            color: [255, 0, 0]
        },
        textBox: {
            width: 150,
            lineHeight: 16,
            padding: [5, 15],
            style: {
                lineWidth: 1,
                stroke: '#00ff00',
                fill: '#ff0000',
                dash: [20, 20],
                opacity: 0.1
            }
        }
    })
    .comment('Feel free to open issues to help us!', 'center', 100)
    .endPage()
    // 2nd page
    .createPage('A4', 90)
    .circle(150, 150, 300)
    .endPage()
    // end and save
    .endPDF(()=>{ /* done! */ });

Modify an existing PDF

const HummusRecipe = require('hummus-recipe');
const pdfDoc = new HummusRecipe('input.pdf', 'output.pdf');
pdfDoc
    // edit 1st page
    .editPage(1)
    .text('Add some texts to an existing pdf file', 150, 300)
    .rectangle(20, 20, 40, 100)
    .comment('Add 1st comment annotaion', 200, 300)
    .image('/path/to/image.jpg', 20, 100, {width: 300, keepAspectRatio: true})
    .endPage()
    // edit 2nd page
    .editPage(2)
    .comment('Add 2nd comment annotaion', 200, 100)
    .endPage()
    // end and save
    .endPDF();

Page Info

const pdfDoc = new HummusRecipe('input.pdf', 'output.pdf');
console.log(pdfDoc.metadata);

Print the pdf structure

const pdfDoc = new HummusRecipe('input.pdf', 'output.pdf');
recipe
    .structure('pdf-structure.txt')
    .endPDF(done);

Append PDF

const HummusRecipe = require('hummus-recipe');
const pdfDoc = new HummusRecipe('input.pdf', 'output.pdf');
const longPDF = '/longPDF.pdf';
pdfDoc
    // just page 10
    .appendPage(longPDF, 10)
    // page 4 and page 6
    .appendPage(longPDF, [4, 6])
    // page 1-3 and 6-20
    .appendPage(longPDF, [[1, 3], [6, 20]])
    // all pages
    .appendPage(longPDF)
    .endPDF();

Insert PDF

const HummusRecipe = require('hummus-recipe');
const pdfDoc = new HummusRecipe('input.pdf', 'output.pdf');

pdfDoc
    // insert page3 from longPDF to current page 2
    .insertPage(2, '/longPDF.pdf', 3)
    .endPDF();

Overlay PDF

const HummusRecipe = require('hummus-recipe');
const pdfDoc = new HummusRecipe('input.pdf', 'output.pdf');

pdfDoc
    .overlay('/overlayPDF.pdf')
    .endPDF();

Split PDF

const HummusRecipe = require('hummus-recipe');
const pdfDoc = new HummusRecipe('input.pdf');
const outputDir = path.join(__dirname, 'output');

pdfDoc
    .split(outputDir, 'prefix')
    .endPDF();

Encryption

const HummusRecipe = require('hummus-recipe');
const pdfDoc = new HummusRecipe('input.pdf', 'output.pdf');

pdfDoc
    .encrypt({
        userPassword: '123',
        ownerPassword: '123',
        userProtectionFlag: 4
    })
    .endPDF();

Contributors

Thanks goes to these wonderful people (emoji key):

thebenlamm
thebenlamm

💻
Matthias Nagel
Matthias Nagel

💻
Pavlo Blazhchuk
Pavlo Blazhchuk

💻
shaehn
shaehn

💻
John Huang
John Huang

💻
Andrej Sýkora
Andrej Sýkora

💻
soeyi
soeyi

💻
Dan Halliday
Dan Halliday

💻
Nikhil Pai
Nikhil Pai

💻
Erik Berreßem
Erik Berreßem

💻

This project follows the all-contributors specification. Contributions of any kind welcome!

hummusrecipe's People

Contributors

allcontributors[bot] avatar amejiarosario avatar chunyenhuang avatar danhalliday avatar dependabot[bot] avatar gios avatar landerson6678 avatar matthiasnagel avatar neonerd avatar nikhilpi avatar phynweb avatar puneet-mehta avatar shaehn avatar she11sh0cked avatar sjaakieb avatar thebenlamm avatar toissei avatar tranad2 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

hummusrecipe's Issues

Cannot save PDF (Exited from signal: SIGSEGV)

I am using hummus-recipe in a Meteor app to mark some PDF's but some PDF's are failing. The pdfs are also made using hummus-recipe and the ones that are failing are specifically the ones that are made only by adding images to a pdf. When i try to mark those i get Exited from signal: SIGSEGV.
I can provide you with an example PDF in private since it contains some personal information.
This is the code i use to mark the PDF's:

            const pdfDoc = new HummusRecipe(pdfPath, pdfPath);
            console.log('marking pdf')
            pdfDoc
                .editPage(1)
                .text(`Anlage K${k}`, 375, 35, {
                    color: '#000000',
                    fontSize: 24,
                    bold: true,
                    align: 'center center',
                    textBox: {
                        width: 162,
                        minHeight: 32,
                        lineHeight: 18,
                        textAlign: 'center center',
                        padding: [5, 15],
                        style: {
                            lineWidth: 5,
                            stroke: '#020202'
                        }
                    }
                })
                .endPage()
                .endPDF(() => appendPage(pdfPath));
        } catch (err) {
            console.log(`didnt append K${k}}`)
        }

Is it possible to add multi-line text?

Hi,

Thanks for creating a great module which makes it super-easy to edit PDFs!!

I'm trying to add multi-line text into a PDF, but it doesn't seem to work - one '\n' gets ignored, and two seems to corrupt the text.

Any guidance would be greatly appreciated!

Thank you.

In-place edit an existing pdf

I want to in-place edit a pdf page, but want to save changes to the existing pdf not create a new pdf, what do you suggest I go about doing this? thank you in advance

Can I use font form file path instead of a string?

In Hummus I can use my font with a font file like this:

var pdfFontPath = './fonts/msyh.ttf';

var pdfWriter = hummus.createWriterToModify('input.pdf', {
        modifiedFilePath: 'output.pdf'
    });

var pageModifier = new hummus.PDFPageModifier(pdfWriter,0);
    pageModifier.startContext().getContext().writeText(
        '我的文字',
        75, 805,
        {
            font:pdfWriter.getFontForFile(pdfFontPath),
            size:14,
            colorspace:'white',
            color:0x00
        }
    );

How can I do this in hummus recipe? Anyone can help? Many Thanks.

TypeError: Unable to end PDF

Here is my code

const pdfDoc = new HummusRecipe('output.pdf', 'output2.pdf')
  pdfDoc
    // edit 1st page
    .editPage(1)
    .text('Add some texts to an existing pdf file', 50, 50)
    // end and save
    .endPDF();

Here is the error log

TypeError: Unable to end PDF
    at Recipe.endPDF (/Users/chris/development/theVelops/solstar-api/node_modules/hummus-recipe/lib/Recipe.js:173:21)
    at addContractIdInPdf (/Users/chris/development/theVelops/solstar-api/functions/insertContractIdInPdf.js:19:6)
    at Object.<anonymous> (/Users/chris/development/theVelops/solstar-api/functions/insertContractIdInPdf.js:24:1)
    at Module._compile (module.js:635:30)
    at loader (/Users/chris/.nvm/versions/node/v8.9.2/lib/node_modules/babel-cli/node_modules/babel-register/lib/node.js:144:5)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/chris/.nvm/versions/node/v8.9.2/lib/node_modules/babel-cli/node_modules/babel-register/lib/node.js:154:7)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Function.Module.runMain (module.js:676:10)

What am I doing wrong?

Link annotations?

I'm still working through understanding PDF structures so forgive me if I'm not quite there but as I understand it links within the document are created using special link annotations, which are provided a URL action ('A') and height and width of the rectangle of the link. This could then be placed over an image for example.

Do you have any plans to support link annotations? From what I can see there isn't the necessary fields available in your API to support them?

Cannot save PDF created by HummusJS

We have a script that creates PDFs using HummusJS. Our new application is using hummus-recipe to add content onto the PDF. For some reason we cannot call endPdf() on a PDF created by Hummus. Below is a simple example:

const HummusRecipe = require('hummus-recipe');
const hummus = require('hummus');

let pdfWriter = hummus.createWriter('/tmp/hummus.pdf');
let page = pdfWriter.createPage(0,0,595,842);
pdfWriter.writePage(page);
pdfWriter.end();

const test = new HummusRecipe('/tmp/hummus.pdf', '/tmp/hummus-recipe.pdf');
test.endPDF();
console.log('Not hit because of: exit code 139 (interrupted by signal 11: SIGSEGV ');

Overlay PDF with multiple pages

Is it possible to overlay more than one page from one pdf to another? I have a ten pages background pdf and a ten pages pdf for content each page is different.

Thanks

npm installation fail

Hi, i'd like to try this awesom library, but i get an error during npm installation
I'm under Windows 10 64 bit OS.

It seems to fail to find a downloadable file (404)

node-pre-gyp WARN Tried to download(404): https://hummus.s3-us-west-2.amazonaws.com/hummus/v1.0.87/node-v48-win32-x64.tar.gz and then failing fallback

Anyway i attach pastebin of complete log: https://pastebin.com/cWsMswNQ

thanks

Can't load font via options.fontSrcPath

this._setParameters(options = {});
const fontSrcPath = options.fontSrcPath || path.join(__dirname, '../fonts');

At this point, options will be {}. Tried to use this.options.fontSrcPath instead of options.fontSrcPath, but got this Segmentation fault: 11 in the console.

Hightlight text in PDF

Hi,

Found couple of issues with "annot" function in the annotation.js.

  1. it doesn't pass in the "text" parameter which will cause the call to fail.
  2. (after adding the text parameter), the passed text is not being highlighted. This is the unit test I have created.
    it('Highlight text', (done) => {
        const src = path.join(__dirname, 'materials/compressed.tracemonkey-pldi-09.pdf')
        const output = path.join(__dirname, 'output/highlight text.pdf');
        const recipe = new HummusRecipe(src, output);
        recipe
            .editPage(1)
            .annot(0, 0, 'Highlight', 'Trace-based Just-in-Time Type Specialization for Dynamic Languages', 
            {text: 'Trace-based Just-in-Time Type Specialization for Dynamic Languages'})
            .endPage()
            .endPDF(done);
    });

Having inspected the PDF markup, the highlight is added and also the correct content, but still not highlighting.

Regards,

Mohammed

split example

I have a pdf doc and would like to split it into one pdf per page,
Is this a use case of the split? can you show an example!

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because we are using your CI build statuses to figure out when to notify you about breaking changes.

Since we did not receive a CI status on the greenkeeper/initial branch, we assume that you still need to configure it.

If you have already set up a CI for this repository, you might need to check your configuration. Make sure it will run on all new branches. If you don’t want it to run on every branch, you can whitelist branches starting with greenkeeper/.

We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

Once you have installed CI on this repository, you’ll need to re-trigger Greenkeeper’s initial Pull Request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper integration’s white list on Github. You'll find this list on your repo or organiszation’s settings page, under Installed GitHub Apps.

Access calculateTextDimensions

Thanks for the repo, it's been a big help in understanding Hummus!

I need to access calculateTextDimensions() in order to set text precisely above the line below — is there a way to access it from hummusRecipe?

Crash when used in electron

  • Version: electron-builder@^19.19.1
  • Target: both Mac and windows7 32

My electron App run well by use:
yarn dev

but it crash after I built the app, and run it.

code cause crash:

 const HummusRecipe = require('hummus-recipe')
 const pdfDoc = new HummusRecipe('new', '/Users/zhouwenhan/workspace/yunmao/yunmao-kit/output4.pdf')
 pdfDoc
          // edit 1st page
 .createPage()
            // .text('Add some texts to an existing pdf file', 150, 300)
 .image(img, 150, 300)
 .overlay(pdf, 0, 0)
 .endPage()
 .endPDF()

I have use humus-recipe

 "rebuild": "electron-rebuild -f -w hummus-recipe"

 "dependencies": {
    "axios": "^0.16.1",
    "hummus-recipe": "^1.6.9",
    "vue": "^2.3.3",
    "vue-electron": "^1.0.6",
    "vue-router": "^2.5.3",
    "vuex": "^2.3.1"
  },

the crash log from MAC system:

yunmao-kit_2018-04-30-195058_zhoudeMacBook-Pro.crash.log

Insert page fail when final PDF is >= 20 pages

const finalPdf = new HummusRecipe(pdf, outputPdf);
    let repeat = 1;
    while (repeat < repeats + 1) {
        finalPdf.insertPage(repeat, otherPdf, 1);
        repeat += 1;
    }
finalPdf.endPDF();

I'm not sure where the issue comes from, when repeats > 9, I get this TypeError: unable to append page, make sure it's fine error.

The primary pdf is an 11-page pdf file, I was trying to insert one identical page after each page in the primary pdf file.

Draw image using base64 representation of image

Is there option to draw image using base64 representation of image?

"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAAEsCAYAAADtt+XCAAAgAElEQVR4nNS6Z1xVaZbvv/c+CVOZc6mYEMlJMZRizgljGRARs6AgOSMGQATBSM5ZyTkoOQkSzJWrp3t6etLt6Z7pmf/c++L7f3EOiBZW2dM9dz73xfdzztl7n3Oe/Txrrd9a69mCTC4gkwvIZAKSTECUBARRQBA+jii+46f ...."

oldInfo.Author.toText is not a function

I'm running into an error when I try to add an annotation to an existing PDF that has Title or Author metadata. For example, this file.

This code throws on endPDF() because it can't copy infoDictionary entries from the source document.

  const pdfDoc = new HummusRecipe(`${__dirname}/data/test.pdf`, `${__dirname}/data/test_out.pdf`);
  pdfDoc.editPage(page).rectangle(100, 100, 200, 200).endPage();
  pdfDoc.endPDF();

Insert first page not working

When I try to insert the first page into a PDF it fails with unable to append page, make sure it's fine.

recipe.insertPage(0, '/tmp/other.pdf', 1).endPDF();

I'm fairly sure the offending code is in here - something about when you're constructing the new PDF, it might be trying to get a page -1 from the original?

At the moment I'm fairly sure insertPage only works for page 2 onwards.

Overlay example incomplete + opaque error information

The overlay example in the README.md looks like this:

const HummusRecipe = require('hummus-recipe')
const pdfDoc = new HummusRecipe('./input.pdf', './output.pdf')

pdfDoc
    .overlay('/overlay.pdf')
    .endPDF()

However, to actually get it to work, I needed:

const HummusRecipe = require('hummus-recipe')
const pdfDoc = new HummusRecipe('./input.pdf', './output.pdf')

pdfDoc
    .editPage(1) // without this line, it errors trying to destructure the metadata since there is no current page being edited; see below
    .overlay('./overlay.pdf')
    .endPage() // without this line the call to endPDF throws `Unable to end PDF`
    .endPDF()

Additionally, both of these issues could have better information:

  • in the case of a missing page number instead of crashing when trying to access the metadata, a precondition could throw an error saying Not currently editing a page; are you missing a call to editPage?

  • in the case of the opaque Unable to end PDF I think this is probably being thrown up from the underlying APIs, so it might be better bounced back to Hummus. It looks like this could be improved with another precondition checking to see if the current page has been ended.

If you're open to PRs from outside, I'd be happy to contribute.

Thanks for this library - it makes the underlying Hummus library a lot more approachable using Node.

EDIT: additionally, if you'd like the stack traces from the two errors I saw, I'd be happy to provide them.

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because we are using your CI build statuses to figure out when to notify you about breaking changes.

Since we did not receive a CI status on the greenkeeper/initial branch, we assume that you still need to configure it.

If you have already set up a CI for this repository, you might need to check your configuration. Make sure it will run on all new branches. If you don’t want it to run on every branch, you can whitelist branches starting with greenkeeper/.

We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

Once you have installed CI on this repository, you’ll need to re-trigger Greenkeeper’s initial Pull Request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper integration’s white list on Github. You'll find this list on your repo or organiszation’s settings page, under Installed GitHub Apps.

Question: Rotation of pages

Is it possible to rotate a page or entire file?
I stumbled upon this function but haven't figured out how this works - sorry if this is trivial but I'm new to Javascript

getting info from existing pdf

how can we get number of pages and also size of each page?
I couldn't find it in repo
for example, say I want to add a text on top of all pages of current pdf file, how can I approach this problem?

Location problem

When try to call a script that use this library from other script using require fail, it throw a Segmentation fault (core dumped), is only allow if both script are in the same folder.
Same thing happend using the terminal, example:

/path/to/pdf-script/ $node generate-pdf.js
it work fine.

/path/to/ $node /pdf-script/generate-pdf.js
a directory up, throw Segmentation fault (core dumped)

using require in node get the same problem.

overlay() not showing on output

I'm using the following code to overlay one pdf to a blank page (final goal is to make some imposition software). But the output is always empty. Files are attached.

const pdfDoc = new HummusRecipe('input.pdf', 'output.pdf');

    pdfDoc
        .editPage(1)
        .overlay('overlayPDF.pdf')
        .endPage()
        .endPDF();

output.pdf
overlayPDF.pdf
input.pdf

Windows 10 x64 Node 9.5.0

Request: Text Rotate

Came across Issue #167 on HummusJS (galkahana/HummusJS#167) and chunyenHuang's implementation for rotating text.

Could we also add this feature to the options in HummusRecipe?
Example:

let pdfDoc = new HummusRecipe(...)
          pdfDoc.text(watermark, xOffset, yOffset, {
            color: 'ff0000',
            opacity: 0.3,
            fontSize: 48,
            bold: true,
            font: 'Helvetica',
            align: 'center top',
            rotateText: 90 // 0 - 360 degrees
          })

Installing on AWS elastic beanstalk

Not sure where to put this, as it isn't an issue, just some lessons learned of what I did to get hummus-recipe to work within a NodeJS instance on AWS elastic beanstalk. Hopefully it saves someone some time. There may be advice for handling it better, which I would appreciate.

To install the package I simply ran npm install --save hummus-recipe

When I then deployed to amazon AWS, I got an error when it was trying to install npm that looked like this: (visible in var/log/eb-activity.log)

> [email protected] install /tmp/deployment/application/node_modules/hummus
> node-pre-gyp install --fallback-to-build
  
  node-pre-gyp WARN Pre-built binaries not installable for [email protected] and [email protected] (node-v57 ABI, glibc) (falling back to source compile with node-gyp) 
  node-pre-gyp WARN Hit error EACCES: permission denied, mkdir '/tmp/deployment/application/node_modules/hummus/binding' 
  gyp ERR! configure error 
  gyp ERR! stack Error: EACCES: permission denied, mkdir '/tmp/deployment/application/node_modules/hummus/build'

It seems that node-pre-gyp is run as the default user rather than root so didn't have the ability to mkdir. See:

To provide permissions I added a .ebextensions config file: 01_npmrc.config (make sure indentation is correct for YAML file)

files:
    # This is the npm user config file path.
    "/tmp/.npmrc":
        mode: "000755"
        owner: root
        group: root
        content: |
            # Force npm to run node-gyp also as root, preventing permission denied errors
            unsafe-perm=true

When I submitted this change, it was able to install npm but crashed my server with the error here:

stack: 
   [ 'Error: Cannot find module \'jpgjs\'',
     '    at Function.Module._resolveFilename (module.js:513:15)',
     '    at Function.Module._load (module.js:463:25)',
     '    at Module.require (module.js:556:17)',
     '    at require (internal/module.js:11:18)',
     '    at /var/app/current/node_modules/utif/UTIF.js:10:74',
     '    at Object.<anonymous> (/var/app/current/node_modules/utif/UTIF.js:911:3)',
     '    at Module._compile (module.js:612:30)',
     '    at Object.Module._extensions..js (module.js:623:10)',
     '    at Module.load (module.js:531:32)',
     '    at tryModuleLoad (module.js:494:12)',
     '    at Function.Module._load (module.js:486:3)',
     '    at Module.require (module.js:556:17)',
     '    at require (internal/module.js:11:18)',
     '    at Object.<anonymous> (/var/app/current/node_modules/jimp/dist/utils/image-bitmap.js:22:36)',
     '    at Module._compile (module.js:612:30)',
     '    at Object.Module._extensions..js (module.js:623:10)' ] }
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `node server.js`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

AWS kept trying to restart node, so this message continually popped up. (as seen in /var/log/nodejs/nodejs.log. I checked the node_modules folder on the ec2 instance and sure enough the jpgjs folder was missing. This package is required by the utif library used by hummus which is used by hummus-recipe as shown in the package-lock.json after installing hummus-recipe

"utif": {
      "version": "2.0.0",
      "resolved": "https://registry.npmjs.org/utif/-/utif-2.0.0.tgz",
      "integrity": "sha512-9fl1Md7tUTsgjhWCLOra+nalQnDxWme+h0OB7WQsUBZbhrxEmzL6/suCPxI4ujrFAvv6KSu7B/74HhxfydVpfw==",
      "requires": {
        "jpgjs": "github:makr28/jpgjs#c83f107ad725b476a3441d20680a02590d8752cc",
        "pako": "^1.0.5"
      },
...
"jpgjs": {
      "version": "github:makr28/jpgjs#c83f107ad725b476a3441d20680a02590d8752cc",
      "from": "github:makr28/jpgjs"
    },

I am uncertain as to why it didn't install that package? However, to solve that issue, I downloaded the jpgjs folder from https://github.com/makr28/jpgjs and added it to a libs folder in my own repository. Then I added this postinstall script (within the scripts section of package.json) to copy the folder to node_modules.

"postinstall": "cp -R libs/jpgjs node_modules"

Perhaps not so elegant a solution ... but alas, it deploys to AWS elastic beanstalk without any issues! Yay!

Is it possible to edit scanned PDF files?

I'm pretty pleased to use this awesome library! Thank you so much @chunyenHuang
Nevertheless I'm having trouble to edit a scanned PDF file.
I keep getting Segmentation fault: 11
I do not have any other log from the project

My current code is

const projectExample = {
	socinal_contract_id: '222222222'
};


/**
 * addContractIdInPdf - this function is responsible for adding the CCB Number
 * into an already signed and scanned contract
 * It will return the path of the new pdf file
 * @param  {Object} project  - a project object from MongoDB
 * @param  {String} inputPath - the path of the pdf file that will be processed
 * @return {String} outputPath - the path to the new pdf file
 */
function addContractIdInPdf (project, inputPath) {
	return new Promise((resolve) => {
		const pathWithoutExtension = inputPath.replace(/\.[^/.]+$/, '');
		const newFilePath = `${pathWithoutExtension}_with_contract_id.pdf`;
		const pdfDoc = new HummusRecipe(inputPath, newFilePath);
		pdfDoc
		// edit 1st page
			.editPage(1)
		// add text to pdf
			.text(project.socinal_contract_id, 420, 64)
		// we MUST use endPage!!
			.endPage()
			.editPage(7)
			.text(project.socinal_contract_id, 200 , 343)
			.text(project.socinal_contract_id, 285, 392)
			.endPage()
		// end and save
			.endPDF(() => resolve(newFilePath));
	});
}

addContractIdInPdf(projectExample, '/tmp/02121402.pdf')
.then((path) => console.log(path))

It works perfectly for digital pdf files, and it doesn't work for scanned pdf files.
Thank you so much for your help

annotations are not working inside for loop

const pdfDoc = new HummusRecipe(input.pdf,output.pdf);    
        for(var a=0;a<annotations[0].annotation.length;a++)
        {
            pdfDoc.editPage(annotations[0].annotation[a].page);  
            if(annotations[0].annotation[a].type == 'area')
            {
                var areaX = annotations[0].annotation[a].x;
                var areaY = annotations[0].annotation[a].y;
                var areaWidth = annotations[0].annotation[a].width;
                var areaHeight = annotations[0].annotation[a].height;
                pdfDoc.rectangle(areaX,areaY,areaWidth,areaHeight, {
                stroke: '#000000',
                lineWidth: 2
              });
            }  
           pdfDoc.endPage(); 
}
 pdfDoc.endPDF(); 

I am storing all of my annotations in the database. While downloading pdf I am fetching the annotation from the database. Using hummus recipe I am placing the annotations in the pdf and then downloading the pdf. Here is my collection.

{
    "_id" : ObjectId("5b56d0e9581875a279e8095b"),
    "annotation" : [ 
        {
            "page" : 1,
            "class" : "Annotation",
            "rotation" : 0,
            "height" : 130,
            "width" : 201.666666666667,
            "y" : 236.666666666667,
            "x" : 190,
            "color" : "#000000",
            "type" : "area"
        }, 
        {
            "page" : 1,
            "class" : "Annotation",
            "rotation" : 0,
            "height" : 43.3333333333333,
            "width" : 123.333333333333,
            "y" : 426.666666666667,
            "x" : 460,
            "color" : "#000000",
            "type" : "area"
        }
    ]
}

What is the mistake here I am doing. Only the last rectangle is showing. I need to show all the annotations.Only the last annotation is showing.

Text Alignment centre centre not working

I am trying to render a text in a text box but the vertically centred. Only I have been trying the following for a text only it keeps left aligned:

         {
             "x": 158,
             "y":  80,
             "style": {
                 "color": "592982",
                 "fontSize": 24,
                 "bold": true,
                 "font": "Helvetica",
                 "textBox": {
                    "textAlign": "left center",
                    "minHeight": 30,
                     "width": 400,
                    "lineHeight": 24,
                     "padding": [0, 0]
                 }
             }
         }

What am I doing wrong?

add option for SVG

Hello,

I want to be able to insert an svg in the PDF file I want to modify.

Are you able to get this feature?

Fill in a PDF

I'm currently running with a HummusJS example code snippet for filling out PDF forms, but I've hit some quirks (https://github.com/galkahana/HummusJSSamples/blob/master/filling-form-values/pdf-form-fill.js). Feel like it'd be nice to incorporate filling out forms into HummusRecipe so folks can collaborate and refine the approach. Seems like a common action people would be taking!

Here's the PDF I'm trying to fill in if you're curious and want to play with something:
BankruptcyForm.pdf

A way to not wrap text within textbox?

Just wondering if there is a way to prevent text wrapping, for example, I sent in this text
"company\nmore test\nmore test that is something really long and annoying\nsomething else to see\ncountry", with a width of 1.5" (1.5 * 72).

I expected:
Company
more test
more test that is something re ... <-- This line clipped
something else to see
country

Instead I got this results
final-small-folded-landscape_pdf__page_3_of_24_

My overall goal is that I need to limit the output to 5 printed lines. and a fixed width.

As a side question, any idea why the 'g's are getting cut off in the above picture? I've tried setting lineHeight, but that didn't seem to have an effect.

Any suggestions?
Thanks!

Deploying to elastic beanstalk instance breaks pdf read functionality

I'm trying to deploy my express node application that contains hummus-recipe to an elastic beanstalk instance but it seems to be stopping the read functionality. Running the application locally works absolutely fine and I have no issues whatsoever. When I try an run my PDF editing function I get

Error: TypeError: Unable to start parsing PDF file
    at Recipe.read (/var/app/current/node_modules/hummus-recipe/lib/Recipe.js:165:19)
    at Recipe._createWriter (/var/app/current/node_modules/hummus-recipe/lib/Recipe.js:61:18)
    at new Recipe (/var/app/current/node_modules/hummus-recipe/lib/Recipe.js:49:14)
    at /var/app/current/functions/pdf-functions.js:10:20
    at new Promise (<anonymous>)
    at Object.annotateDoc (/var/app/current/functions/pdf-functions.js:8:10)
    at /var/app/current/index.js:112:18
    at Layer.handle [as handle_request] (/var/app/current/node_modules/express/lib/router/layer.js:95:5)
    at next (/var/app/current/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/var/app/current/node_modules/express/lib/router/route.js:112:3)

I have tried a few possible fixes including:

  • Verifying that the pdf is indeed in the location I am trying to read from
  • Using a preprocessed version of hummus-recipe from another EC2 box with the same setup as my elastic beanstalk
    The code below is the snippet that I am trying to get working:
const HummusRecipe = require("hummus-recipe");

var annotateDoc = (fileVersion, ip, emailAddress, country) => {
    console.log("Using " + fileVersion + " to create new pdf called " +
        "public/documents/whitepaper_" + ip + "_" + country + ".pdf");

  return new Promise(function(resolve, reject) {

    const pdfDoc = new HummusRecipe(
        fileVersion,
        "public/documents/whitepaper_" + ip + "_" + country + ".pdf"
    );
    var text =
      "This document was produced for viewing by " +
      (ip || "") +
      " " +
      emailAddress +
      " in " +
      (country || "") +
      " region";

    pdfDoc
      // edit 1st page
      .editPage(1)
      .text(text, 30, 10, {
        color: "#000000",
        size: 12
      })
      .endPage()
      // end and save
      .endPDF(function(e) {
        console.log(e)
        resolve("documents/whitepaper_" + ip + "_" + country + ".pdf");
      });
  });
};

module.exports = {
  annotateDoc
};

I may be missing something very basic but any help on this would be great

Background of page

I need to create different background for each page? What is the way to do this?

Overlay issue

Usage:

const HummusRecipe = require('hummus-recipe')
const pdfDoc = new HummusRecipe('input.pdf', 'output.pdf')
const pdfOverlay = 'overlay.pdf'
pdfDoc
    .editPage(1)
    .overlay(pdfOverlay, 0, 0)
    .endPage()
    .endPDF()

hummus-error.log:

[ 06/02/2018 16:57:15 ] UnicodeString::FromUTF16BE, fault string - high surrogat encountered without a low surrogate
[ 06/02/2018 16:57:15 ] UnicodeString::FromUTF16BE, fault string - high surrogat encountered without a low surrogate

Result:

PDF file was not changed, just copied from input to output.

Question:

Can you please help me out with this?

app crashes on pdfDoc.endPDF()

Could use a little help here. Looks like a perfect library for what I need, just haven't been able to get it working. I'm running this code:

    const pdfDoc = new HummusRecipe('./input.pdf', './output.pdf');
    pdfDoc.editPage(1)
        .text('adding test text', 10, 10)
        .endPage()
        .endPDF();

When I trace the issue, it is failing inside this block of code, specifically in the call to queryDictionaryObject:

    const options = this.toWriteInfo_ || {};
    let oldInfo;
    if (!this.isNewPDF) {
        // reuse copyCtx?
        const copyCtx = this.writer.createPDFCopyingContext(this.src);
        oldInfo = copyCtx.getSourceDocumentParser().queryDictionaryObject(
            copyCtx.getSourceDocumentParser().getTrailer(), "Info"
        ).toJSObject();

If I comment out this block of code, it works, but it doesn't feel like the right way to handle this ... any suggestions?

Error in `node': corrupted double-linked list

Hello,
I tried to split an array of pdfs in a promise sync loop.

This is my code:

Promise.mapSeries(pdfArr, function(pdf) {
  return new Promise( (resolve) => {
    var pdfDoc = new HummusRecipe(pdfpath + pdf);
    pdfDoc
      .split(pdfpath, pdf + "_split")
      .endPDF(function () {
        resolve();
      });
    });
  });

It split the first 20-30 files (tried multiple times, got different results) and throw this error:
*** Error in 'node': corrupted double-linked list: 0x000000000505e330 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x777e5)[0x7f4d2c2147e5]
/lib/x86_64-linux-gnu/libc.so.6(+0x82970)[0x7f4d2c21f970]
/lib/x86_64-linux-gnu/libc.so.6(__libc_malloc+0x54)[0x7f4d2c221184]
/usr/lib/x86_64-linux-gnu/libstdc++.so.6(_Znwm+0x18)[0x7f4d2cd30e78]
/node_modules/hummus/binding/hummus.node(_ZN24OutputStringBufferStreamC1Ev+0x22)[0x7f4d29d64d62]
...

Thanks if you have any idea why this memory error happens.

moveDown() function

Hi @chunyenHuang thanks for the plugin. How can we move next line if we use textbox with dynamic height ?

Is there are kind of moveDown() function for this purpose ?

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.