Skip to content

Added img to pdf and docx to pdf file #166

New issue

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

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

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: Roadmap-2023
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions src/Plugins/docsx-input-plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import * as path from 'path';
import * as mammoth from 'mammoth';
import * as puppeteer from 'puppeteer';
import { PluginOutput } from './pdf-plugin.interfaces';

export class DocxInputPlugin {
public async convertDocxToPdf(docxFilePath: string): Promise<PluginOutput> {
try {
const outputPdfPath = path.join(__dirname, './generatedPdfDocument.pdf');
const htmlContent = await this.convertDocxToHtml(docxFilePath);
await this.htmlToPdf(htmlContent, outputPdfPath);

console.log('PDF file generated successfully');
return { file: outputPdfPath };
} catch (error) {
console.error('Error generating PDF:', error);
throw new Error('Failed to convert DOCX to PDF');
}
}

private async convertDocxToHtml(docxFilePath: string): Promise<string> {
const result = await mammoth.convertToHtml({ path: docxFilePath });
return result.value;
}

private async htmlToPdf(htmlContent: string, pdfPath: string): Promise<void> {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setContent(htmlContent);
await page.pdf({ path: pdfPath, format: 'A4' });

await browser.close();
}
}
42 changes: 42 additions & 0 deletions src/Plugins/image-output-plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import * as fs from 'fs';
import * as path from 'path';
import { createCanvas } from 'canvas'; //
import { PluginOutput } from './pdf-plugin.interfaces';

export class ImageOutputPlugin {
public async generateImage(outputType: string): Promise<PluginOutput> {
if (outputType.toUpperCase() === 'IMG') {
const canvas = createCanvas(400, 200);
const context = canvas.getContext('2d');

context.fillStyle = '#FF0000';
context.fillRect(0, 0, 400, 200);

// Draw text on the image //
context.fillStyle = '#FFFFFF';
context.font = '20px Arial';
context.fillText('Hello Image!', 50, 100);

const pdfFilePath = path.join('./generatedImage.png');

return new Promise<PluginOutput>((resolve, reject) => {
const stream = fs.createWriteStream(pdfFilePath);
const streamOutput = canvas.createPNGStream();

streamOutput.pipe(stream);

stream.on('finish', () => {
console.log('Image generated successfully');
resolve({ file: 'generatedImage.png' });
});

stream.on('error', (error) => {
console.error('Error generating image:', error);
reject(error);
});
});
} else {
throw new Error('Unsupported output type');
}
}
}
4 changes: 4 additions & 0 deletions src/Plugins/officegen.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
declare module 'officegen' {
const officegen: any;
export default officegen; //
}
4 changes: 4 additions & 0 deletions src/Plugins/pdf-poppler.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
declare module 'pdf-poppler' {
export function info(filePath: string): Promise<any>; //
export function convert(filePath: string, options: any): Promise<string[]>;
}
126 changes: 126 additions & 0 deletions src/Plugins/plugin.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import { Controller, Post, Get, Param, Dependencies } from '@nestjs/common';
import * as fs from 'fs';
import { PluginService } from './pdf-plugin.service';
import { PluginOutput } from './pdf-plugin.interfaces';
import { PdfOutputPlugin } from './pdf-output-plugin';
import { PdfInputPlugin } from './pdf-input-plugin';
import { DocxOutputPlugin } from './docsx-output-plugin';
import { DocxInputPlugin } from './docsx-input-plugin';
import { ImageOutputPlugin } from './image-output-plugin'; // Import the ImageOutputPlugin
import { ImageInputPlugin } from './image-input-plugin';

@Controller('plugin')
@Dependencies(PluginService)
export class PluginController {
private pdfOutputPlugin!: PdfOutputPlugin;
private pdfInputPlugin!: PdfInputPlugin;
private docxOutputPlugin!: DocxOutputPlugin;
private docxInputPlugin!: DocxInputPlugin;
private imageOutputPlugin!: ImageOutputPlugin; // Add the ImageOutputPlugin
private imageInputPlugin!: ImageInputPlugin;
constructor(private readonly pluginService: PluginService) {}

onModuleInit() {
this.pdfOutputPlugin = new PdfOutputPlugin();
this.pdfInputPlugin = new PdfInputPlugin();
this.docxOutputPlugin = new DocxOutputPlugin();
this.docxInputPlugin = new DocxInputPlugin();
this.imageOutputPlugin = new ImageOutputPlugin(); // Initialize the ImageOutputPlugin
this.imageInputPlugin = new ImageInputPlugin();
}

@Post('generate-doc/:outputType')
async generateDocument(
@Param('outputType') outputType: string,
): Promise<PluginOutput> {
try {
if (outputType === 'PDF') {
return this.pdfOutputPlugin.generateDoc(outputType);
} else if (outputType === 'DOCX') {
return this.docxOutputPlugin.generateDoc(outputType);
} else if (outputType === 'IMG') {
// Add this condition for image generation
return this.imageOutputPlugin.generateImage(outputType);
} else {
throw new Error('Unsupported output type');
}
} catch (error: any) {
console.error('Error generating document:', error.message);
throw new Error('Failed to generate document');
}
}

@Get('convert-img-to-pdf')
async convertImageToPdf(): Promise<PluginOutput> {
try {
const imageFilePath = './generatedImage.png'; // Replace with the actual path to the image
const pdfFilePath = './generatedImage.pdf';

await this.imageInputPlugin.convertImageToPdf(imageFilePath, pdfFilePath);

return { file: 'generatedImage.pdf' };
} catch (error: any) {
console.error('Error converting image to PDF:', error.message);
throw new Error('Failed to convert image to PDF');
}
}

@Get('convert-docx-to-pdf')
async convertDocxToPdf(): Promise<PluginOutput> {
try {
const docxFilePath = './generatedDocxDocument.docx'; // Adjust the path accordingly
const pdfFilePath = './generated-document.pdf';

const pluginOutput = await this.docxInputPlugin.convertDocxToPdf(
docxFilePath,
);

if (!pluginOutput.file) {
throw new Error('Generated PDF file not found.');
}

fs.renameSync(pluginOutput.file, pdfFilePath);

return { file: 'generated-document.pdf' };
} catch (error: any) {
console.error('Error converting DOCX to PDF:', error.message);
throw new Error('Failed to convert DOCX to PDF');
}
}
@Get()
getPluginStatus(): string {
return 'Plugin is running!';
}

@Get('/pdf-to-image')
async convertPdfToImage(): Promise<{ images?: { url: string }[] }> {
const pdfFilePath = './generatedDocument.pdf';
try {
const pluginOutput = await this.pdfInputPlugin.transformPdfToImage(
pdfFilePath,
);

if (pluginOutput.images) {
const images = pluginOutput.images;
images.forEach((image: { url: string }) => {
console.log('Image URL:', image.url);
});
}

return { images: pluginOutput.images };
} catch (error) {
console.error('Error converting PDF to image:', error);
throw new Error('PDF to image conversion failed');
}
}

@Post('create-default-pdf')
async createDefaultPdf(): Promise<PluginOutput> {
try {
return this.pdfOutputPlugin.createDefaultPdf();
} catch (error: any) {
console.error('Error creating default PDF:', error.message);
throw new Error('Failed to create default PDF');
}
}
}