Git Product home page Git Product logo

node-latex's Introduction

node-latex

A small wrapper for generating PDFs with LaTeX in Node.

Requirements

LaTeX must be installed on your machine. You can download it here.

Install

npm install node-latex

Usage

const latex = require('node-latex')
const fs = require('fs')

const input = fs.createReadStream('input.tex')
const output = fs.createWriteStream('output.pdf')
const pdf = latex(input)

pdf.pipe(output)
pdf.on('error', err => console.error(err))
pdf.on('finish', () => console.log('PDF generated!'))

View more examples here.

API

latex(doc[, options])

doc [ReadableStream|String] Required - The (La)TeX document you want to use.

options.inputs [String|Array] - The path (or an array of paths) to the directory which contains the assets necessary for the doc.

options.precompiled [String|Array] - The path (or an array of paths) to the directory which contains the precompiled files necessary for the doc.

options.fonts [String|Array] - The path (or an array of paths) to the directory which contains the fonts necessary for the doc (you will most likely want to use this option if you're working with fontspec).

options.cmd [String] - The command to run for your document (pdflatex, xetex, etc). pdflatex is the default.

options.args [Array] - Arguments passed to cmd. Defaults to ['-halt-on-error'].

options.passes [Number] - The number of times to run options.cmd. Some documents require multiple passes. Only works when doc is a String. Defaults to 1.

options.errorLogs [String] - The path to the file where you want to save the contents of the error log to.

License

MIT

node-latex's People

Contributors

benjaminvanryseghem avatar georgyfarniev avatar jamesqquick avatar patrickdawson avatar paultopia avatar quantumsheep avatar rpadaki avatar rwestlund avatar saadq avatar urshofer 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

Watchers

 avatar  avatar  avatar  avatar

node-latex's Issues

! LaTeX Error: File `awesome-cv.cls' not found.

Error: LaTeX Syntax Error
! LaTeX Error: File `awesome-cv.cls' not found.
Enter file name: \fontdir[fonts/] % Specify the location of the included fonts
! Undefined control sequence.
\fontdir
at ReadStream. (E:\resumePDF\node_modules\node-latex\index.js:60:21)
at ReadStream.emit (node:events:527:28)
at ReadStream.emit (node:domain:475:12)
at endReadableNT (node:internal/streams/readable:1345:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)

EPIPE when source begins with comment line

I ran into a weird issue. When the first non-blank line in my LaTeX file is a % comment, it causes node to crash with EPIPE and texput.log complains about an invalid character. If I swap my comment line and \documentclass declaration so that \documentclass comes first, it works just fine.

I can't reproduce this from the command line: pdflatex -halt-on-error < source.tex works just fine. I'd be curious to know whether anyone else sees this behavior.

when using \input can't compile

I have troubles when compiling this tex

test.tex

\input{share.sty}

\begin{document}
  Hello World!
\end{document}

share.sty:

\documentclass[11pt]{article}

Using \RequirePackage{share} is a nice workaround proposed by Saad, but anyway sometimes we need to struture code using \input directive

! Package pdftex.def Error: file `image.png` not found: using draft setting.

The image which is referenced within the .tex template is not being found, even though it is present in the directory which also has template. If I use MiKTeX to check if there are any issues with the template, i find none. Can you please help with this issue: ! Package pdftex.def Error: file image.png not found: using draft setting.

Error creating the pdf

I am getting this error here:

Error: Error: Unable to run pdflatex command.
    at ChildProcess.<anonymous> (D:\Programming\JavaScript\Kotlin Series\node_modules\node-latex\index.js:171:22)
    at ChildProcess.emit (node:events:376:20)
    at Process.ChildProcess._handle.onexit (node:internal/child_process:282:12)
    at onErrorNT (node:internal/child_process:476:16)
    at processTicksAndRejections (node:internal/process/task_queues:80:21)

Error: No error log file

The file I used to generate pdf is:

import latex from "node-latex";
import * as fs from "fs";

const input = fs.createReadStream("template.tex");
const output = fs.createWriteStream("output.pdf");
const pdf = latex(input);

pdf.pipe(output);
pdf.on("error", err => console.error(err));
pdf.on("finish", () => console.log("PDF generated!"));

When I run this file, I get the following error:

Error: No error log file.
    at /home/*/node_modules/node-latex/index.js:38:36
    at FSReqCallback.oncomplete (node:fs:199:21)

Please look into this issue @saadq.

Ability to provide more context to errors

It would be nice to provide an options parameter to allow more context to be given in the case of an error. In my scenario, I'm providing users with the feedback, and right now, in a long LaTeX document, it may be hard to spot the occurence of the error, without additional context to where the error occurred.

I believe this is the part that needs to be configurable within the code:

node-latex/index.js

Lines 55 to 63 in 780c588

lines.forEach((line, i) => {
if (line.startsWith('! Undefined control sequence.')) {
errors.push(lines[i - 1])
errors.push(lines[i])
errors.push(lines[i + 1])
} else if (line.startsWith('!')) {
errors.push(line)
}
})

node-latex not creating any files in temp path

Kind of the same thing as #21, but this time, node-latex isn't creating any files in the temp directory at all causing an issue with the error log.
Here is the files logging when using the dev version of node-latex.
Screen Shot 2021-12-06 at 8 54 40 PM

Table of contents is empty.

I am trying to create a pdf for a sample tex file. It creates pdf file successfully ,but table of contents is empty. I also observed that files like .toc, .aux does not get created. Am I missing something? I have used the simple example from git.
function generatePDF( ) {
const input = fs.createReadStream("new.tex","utf-8");
const output = fs.createWriteStream("output.pdf");
const pdf = latex(input)

pdf.pipe(output)
pdf.on('error', err => console.error(err))
pdf.on('finish', () => console.log('PDF generated!'))
}
new .txt
output.pdf

[BUG] - fs.mkdir is not a function

Unhandled Rejection (TypeError): fs.mkdir is not a function

const pdf = latex('\\documentclass{article}\n' + '\\begin{document}\n' + ' Hello World!\n' + '\\end{document}');

Error Catch

Hi –

I needed to write the code like this in order to catch Err on the output pipe:

var outputPath = "/path/to/pdf.pdf";
var tex = "\\example string with error";
const oStream  = fs.createWriteStream(outputPath);
const lStream  = latex(tex, texsettings);
lStream.on('error', function(err) {
  console.log(`Error Creating PDF ${err}`)
})
lStream.pipe(oStream);
oStream.on('error', function(err) {
  console.log(`Error Creating PDF ${err}`)
})

Otherwise, the script crashed with an uncaught error in the pipe.
Maybe worth documenting.
Best,
Urs Hofer

Is the LaTeX Call Asynchronous

This is not necessarily an issue, but didn't know of a better place for it. Is the following call synchronous or asynchronous?

latex(texDoc, opts)

From the looks of it, it's synchronous, but I would think this is potentially a long enough running function for it to make since to be asynchronous...?

Path seperator ':' in windows

Windows doesn't like the : path separator very much, resulting in it not using the inputs directories. replace it with a ; for windows.

    const joinPaths = inputs => {
      var separator = (process.platform.indexOf('win') != -1) ? ";" : ":"
      return Array.isArray(inputs)
        ? `${inputs.join(separator)}` + separator
        : `${inputs}` + seperator
    }

Cannot read property 'type' of undefined in rollup-commonjs-plugin

Hi,
I am using node-latex package in my project. when I bundle my code using rollup i am getting an error

TypeError: Cannot read property 'type' of undefined in rollup-commonjs-plugin

this is my rollup config.

rollup({
            input: module.entry,
            treeshake: true,
            external:[],
            plugins: [
                postCss({
                    extract: true,
                    plugins: []
                }),
                commonjs({
                    include: path.resolve(__dirname, "./node_modules/**"),
                    namedExports: {
                        react: [
                            'PropTypes',
                            'createElement', 'Component', 'PureComponent', 'Fragment', 'createContext',
                            'forwardRef',
                            'useContext',
                            'useLayoutEffect',
                            'useEffect',
                            'useRef', "isValidElement", "useReducer", "useImperativeHandle",
                            'useState', 'useMemo', 'useCallback', "Children", "cloneElement", "createRef"
                        ],
                        "react-transition-group": ["CSSTransition"],
                        "react-dom": ["unmountComponentAtNode", "render"],
                        "react/jsx-runtime": ["jsxs", "jsx", "Fragment"],
                        "node-latex": []
                    }
                }),
                resolve({
                    mainFields: ["module", "main"],
                    customResolveOptions: {
                        moduleDirectory: path.resolve(__dirname, './node_modules')
                    }
                }),
                babel({
                    babelrc: false,
                    externalHelpers: false,
                    presets: babelPresets,
                    plugins: babelPlugins
                }),
                json(),
                replace({
                    "process.env.NODE_ENV": JSON.stringify("production")
                })
            ]
        })
            .then( (bundle) => {
                bundle.write({
                    name: "__rollupModule",
                    format: "iife",
                    file: module.dest,
                    // footer: "window.__rollupModule = undefined;",
                    // dest: module.dest,
                    sourcemap: 'inline'
                }).then(() => {
                    if (i === modules.length - 1) {
                        callback();
                    }
                });
            })
            .catch((err) => log(err));
    });

I tried some ways. But, i couldn't resolve this issue..!

problem on a windows 10 machine when it is generated the tmp file

Hi there, hoping you are ok, I want to request you a little help with your library...Ammmm, Im facing a issue on a windows 10 x64 bits machine related to the tmp file generated before of the output, to be more exact, this is the error
[Error: ENOENT: no such file or directory, open 'C:\Users\kris9\AppData\Local\Temp\node-latex2020614-19172-16jm2k.8og2b\texput.pdf'] { errno: -4058, code: 'ENOENT', syscall: 'open', path: 'C:\\Users\\kris9\\AppData\\Local\\Temp\\node-latex2020614-19172-16jm2k.8og2b\\texput.pdf' }

I would really appreciate as soon as possible your help
Thanks in advance

Run LaTeX multiple times

Most non-trivial LaTeX documents require multiple passes. For example, anything using section references, table of contents, longtable, lastpage, etc.

It's difficult to automatically determine how many passes a document needs at compile time. I think the easiest solution is to have a parameter options.passes that determines how many times LaTeX is invoked before the document is returned.

Unable to run pdfLatex

I've copied over the simple example from the repo, and tried to run it but I get an unhandled 'error' each time. Not getting insightful feedback from this, so not sure how to debug...


events.js:163
      throw er; // Unhandled 'error' event
      ^

Error: Error: Unable to run pdflatex command.
    at ChildProcess.tex.on (/Users/jamesquick/Desktop/latex-sample/node_modules/node-latex/index.js:146:22)
    at emitOne (events.js:96:13)
    at ChildProcess.emit (events.js:191:7)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:213:12)
    at onErrorNT (internal/child_process.js:367:16)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickCallback (internal/process/next_tick.js:104:9)

Unable to use inside docker container.

I am trying to use the package inside docker container. But since the package needs latex to be installed in the machine, I am getting errors. Can someone help with installing latex on docker container?

Support relative paths in options?

Hi there,

Would it be terribly difficult to have the options support relative paths? I'm trying to include a font in a complicated build that involves using a mustache template to generate a tex file and then building it with node-latex, but having to supply an absolute path for the fonts directory in the options is totally blowing up the build process. If there isn't some complex latex-related reason why this won't work, I'm happy to try to implement it myself if you're interested...

Error: ENOENT: no such file or directory

Hello,
I'm getting this error:

events.js:173
      throw er; // Unhandled 'error' event
Error: ENOENT: no such file or directory, open 'C:\Users\username\AppData\Local\Temp\node-latex11943-4516-s5hath.2iall\texput.log'

Here is my code:

Latex string is passed as body param.

'use strict';
const latex = require('node-latex');
const fs = require('fs');
const path = require('path');
module.exports = {
  pdf: ({ request, response }) => {
    const output = fs.createWriteStream(path.resolve('public', 'cv.pdf'));
    const options = {
      inputs: [
        path.resolve('assets', 'latex', 'inputs'),
        path.resolve('assets', 'latex', 'images'),
      ],
      fonts: path.resolve('assets', 'latex', 'fonts', 'itcavantgardestd'),
      cmd: 'xetex',
      errorLogs: path.resolve('public')
    };
    const pdf = latex(request.body.latex, options)
    pdf.pipe(output);
    pdf.on('error', error => {
      console.log(error);
    });
    pdf.on('finish', () => console.log(pdf));
    return null;
  }
};

Any idea why I'm getting this unhandled error ?

usage of options

Dear saadq, I find that there exist several options to be loaded, but I cannot find any documentations about the usage of these options (a concrete example like how to set fonts will be great).
Thx!

I can't write on file texput.pdf

Hi, I have some "random" problems with the pfd generation.
I get the following error message sometimes and sometimes not.

LaTeX Syntax Error
! I can't write on file `texput.pdf'.
! Emergency stop.

The latex document as such is syntactically ok. And under the /tmp directory the log and aux files are created. The error seems totally random ?
Maybe it depends on the environment? I use a LXC Container with Ubuntu 16.10

I would appreciate any help!

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.