Converting docx files to PDF in Angular 15 using the "docxjs" library: A step-by-step guide

I am currently utilizing the to generate some docx files and enable downloading, but I am faced with the challenge of converting these files into PDF format.

This is my current process:

public download(data: any): void {
    const documentCreator = new DocumentCreator();
    const doc = documentCreator.create(data);

    Packer.toBlob(doc).then((blob) => {
      console.log(blob);
      saveAs(
        blob,
        `Contract ${data.place} ${_moment(data.dateEvent).format('LL')}.docx`
      );
      console.log('Document created successfully');
      this.closeModalExport();
    });
  }

export class DocumentCreator {
  // tslint:disable-next-line: typedef
  public create(diary): Document {
   //Some paragraph and text
return document;
  }
}

However, I am seeking guidance on how to convert the generated blob into a PDF file.

I have attempted to directly convert it and change the blob type, but unfortunately, it did not yield the desired outcome:

let pdf = new Blob([blob], {type: 'application/pdf'});
saveAs(
        pdf,
        `Contract ${data.place} ${_moment(data.dateEvent).format('LL')}.pdf`
      );

Answer №1

Regrettably, the docx.js tool does not come equipped with a function to directly change a docx file into a PDF format. To achieve this conversion, you will have to leverage another library or API.

Answer №2

Converting between binary formats without using files can be a challenge, but there are ways to achieve it. One method involves utilizing an endpoint from the quoted question API, which is displayed on the left side of the screen. While the layout may seem a bit simplistic (with a hint of humor in its Roman Font), an alternative approach is presented on the right side – a single line conversion using Windows' own command line that unfortunately results in some loss of fidelity due to font substitutions.

https://i.sstatic.net/lYiYd.png

To perform a similar conversion from DocX to PDF while maintaining both layouts and styles, consider using a DocX reader/writer. Among the most versatile options available (aside from genuine MS Office or its interop) are Open Office/Libre Office, serving as a cost-effective alternative.

Most methods for producing PDFs necessitate access to a file system, even if temporarily stored in memory. It's important to note that direct blob-to-blob conversions aren't feasible without involving a DocX reader and PDF writer in the process.

An API might support blob conversion by accepting and decompressing a File.docX, printing it to a compressed FILE.PDF, converting it back to a blob through another process. This procedure takes time but is achievable.

Various services offer such capabilities; one example is https://github.com/unoconv/unoconv.

HOWEVER

When comparing online Word and Libre Office conversions, pay close attention to the differences in details.

https://i.sstatic.net/tvbd5.png

The Libre Office rendition lacks bullet points, alters the layout to span 2 pages rather than 1, and incorporates new fonts instead of the original ones. These discrepancies raise concerns, particularly regarding the file's reduced size and unexpected font replacements!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a dependency resolution issue in Angular application while executing npm install command

My Angular 9 (* UPDATE, should be Angular 11) project was developed on Ubuntu and Mac machines. The command npm install works perfectly fine in these environments. Now, I need to deploy it to a Linux Centos 7 server, so I decided to Dockerize the project. ...

Checking email format in Angular

I am currently facing an issue where users are able to successfully submit a form even after entering an invalid email format. Despite receiving an error message, the form still gets submitted. It is important to note that I am not using formGroup. Below ...

Global Inertia Headers

How can I ensure that a custom header (Accept-Content-Language) is sent with every request, including Inertia manual visits? Below is the code snippet where I define and set the header: import axios from 'axios'; const lang = localStorage.getIt ...

Executing a single insert statement in a TypeScript Express application using PostgreSQL is taking over 240 milliseconds to complete

Seeking assistance with optimizing a db insert operation test using mocha for a node.js express app that utilizes fp-ts and pg npm package. The tests run successfully, but the insert test is taking over 240 ms to complete. The database table has a maximum ...

Module not found: vueform.config

For my current project, I decided to integrate Vueforms into the codebase. However, when I pasted their installation code into both my .ts and .js files, I encountered errors during the import of vueformconfig and builderconfig. This is a snippet of my ma ...

When using react-chartjs-2 with NextJS and typescript to create a bar chart, an error occurred: TypeError - Attempting to access properties of an undefined object (specifically 'map

Encountering a console error stating TypeError: Cannot read properties of undefined (reading 'map') . As I am new to NextJS & Typescript, I am attempting to build a simple bar chart. Error message: react-dom.development.js?03cb:22839 Uncaugh ...

Decorator in React that automatically sets the display name to match the class name

Is there a way to create a decorator that will automatically set the static property displayName of the decorated class to the name of the class? Example usage would be: @NamedComponent class Component extends React.Component { \* ... *\ } ...

Enroll in a stream of data while iterating through a loop in an Angular application

I encounter a situation where I must subscribe to an Observable, iterate through the response, and then subscribe to another Observable using data from the initial Observable. getTasks(taskType: Observable<any>): void { taskType // Subscribing ...

Troubleshooting: Vee-validate useResetForm not functioning properly during submission in Vue 3 with Typescript

I've been struggling to reset form data after submission, and it seems like the useResetForm hook isn't working as expected. Code Section <script setup lang="ts"> import CircularProgress from "@/components/CircularProgress. ...

Extracting changes from a ValueChange event in Angular Forms

Currently, I am utilizing Angular's Reactive Forms and I am in the process of incorporating an Undo/Redo functionality. My goal is to combine consecutive modifications on the same field into a single undo action. To achieve this, I believe I will nee ...

When `strictNullChecks` is turned on, how does the `void` type differ from the `undefined` literal type?

When strictNullChecks is turned on: (u: undefined, v: void, n: null) => { v = u; u = v; // type error: Type 'void' is not assignable to type 'undefined' v = n; // type error: Type 'null' is not assignable to type &ap ...

get a duplicate of an object

Is this the proper method for creating a duplicate of an object? class ObjectWrapper { private _obj; /*** * Copy object passed as argument to this._obj */ constructor (_obj: Object) { this._obj = _obj; } /** Return copy of this._ ...

Updating the state in React Native does not occur

I'm facing an issue where I can't seem to update the state using useState while coding in React Native. The component in question is a styled TextInput named SearchField. Can anyone help me figure out what I might be doing wrong that's preve ...

The number of columns does not align with the number of values in the first row in Angular 8

Currently, I am in the process of adding a new Vendor to my database by sending a POST request through my Angular App. Here is the code snippet from vendor.service.ts: addVendor(data) { return this.http.post<any>(this.apiUrl + `vendormanagemen ...

How to Use an Object Created from a Different Class in TypeScript

Scenario In the development process, I am using an auth.service.ts. This service is responsible for fetching user information from the database upon login. The retrieved data is then used to create a new user object. Here is a snippet of the code: user: ...

Can the return type of a function be determined dynamically at runtime by analyzing a function parameter value?

Let's delve into this concept with an illustrative example! interface Query { foo: any; } interface Mutation { bar: any; } type OperationName = keyof Query | keyof Mutation; const request = async <T>(args, operationName: OperationName): P ...

A guide on determining the number of rows in an ag-grid with TypeScript and Protractor

I am currently working on extracting the number of rows in an ag-grid. The table is structured as follows: <div class="ag-body-container" role="presentation" style="height: 500px; top: 0px; width: 1091px;"> <div role="row" row-index="0" row-id="0 ...

Is there a way to change routerLink to href?

I am struggling with converting routerLink to href. <a [routerLink]="['/choose',{id:sizzle.parameter,type:dish}]" I attempted it, but I keep getting an error <a [href]="'/choose'+id:sizzle.parameter+type:dish" ...

When building with Angular using the "ng build" command, the JavaScript file names are altered

I'm currently learning Angular and I've noticed that when creating a new project with Angular CLI, files like runtime.js, polyfills.js, main.js, styles.css are generated. However, after running the ng build command, similar files can be found in ...

What steps can I take to troubleshoot and fix the issue of a Duplicate identifier 'DateType' error during the React/Typescript building process

Utilizing the MUI library, I have also installed the @mui/x-date-pickers library. In order for my datepicker component to function properly, I need to install the @date-io/date-fns/ library as well. However, upon running yarn build, I encountered the fol ...