Snippets Collections
//---------------------------------------------------------
// REST service to add an image to a PDF document
//---------------------------------------------------------
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');
const pdfLib = require('pdf-lib');

const app = express();
const port = process.env.PORT || 3000;

// Middleware
app.use(cors());
app.use(bodyParser.json());

// Routes
app.post('/api/addImageToPDF', async function(req, res) {
	const { pdfPath, imagePath, outputName } = req.body;

	// Read PDF file
	const pdfData = await fs.promises.readFile(pdfPath);

	// Read image file
	const imageData = await fs.promises.readFile(imagePath);

	// Load PDF document
	const pdfDoc = await pdfLib.PDFDocument.load(pdfData);

	// Embed image in PDF
	const image = await pdfDoc.embedPng(imageData);
	const page = pdfDoc.getPages()[0];
	const { width, height } = page.getSize();
	page.drawImage(image, {
		x: 0,
		y: height - image.height,
		width: image.width,
		height: image.height,
	});

	// Save modified PDF
	const outputPath = path.join(__dirname, 'modified', outputName);
	const modifiedPdfBytes = await pdfDoc.save();
	await fs.promises.writeFile(outputPath, modifiedPdfBytes);

	// Send response
	res.json({ success: true, message: 'Image added to PDF', url: `http://localhost:${port}/api/getModifiedPDF/${outputName}` });
});

app.get('/api/getModifiedPDF/:fileName', async function(req, res) {
	const { fileName } = req.params;
	const filePath = path.join(__dirname, 'arhiviran', `${fileName}-arhivirano-${new Date().toISOString().replace(/[^\d]/g, '')}.pdf`);
	
	// Read modified PDF file
	const pdfData = await fs.promises.readFile(filePath);

	// Create blob from PDF data
	const blob = new Blob([pdfData], { type: 'application/pdf' });

	// Set response headers
	res.setHeader('Content-Type', 'application/pdf');
	res.setHeader('Content-Disposition', 'attachment; filename=modified.pdf');
	res.setHeader('Content-Length', pdfData.length);

	// Send response
	res.send(blob);
});

// Listen command
app.listen(port, function() {
	console.log(`Server is running on port ${port}`);
});
//---------------------------------------------------------


//---------------------------------------------------------
// How to call the service (client side) with a file name
//---------------------------------------------------------
// Create a FormData object to send the file data
var fileData = new FormData();
fileData.append('file', 'sample.pdf');

// Send the AJAX request to modify the PDF file
$.ajax({
	url: '/modify-pdf',
	method: 'POST',
	data: fileData,
	processData: false,
	contentType: false,
	success: function(data) {
		console.log('File modified successfully. Modified file URL:', data.url);
	},
	error: function() {
		console.error('Error modifying file.');
	}
});

//---------------------------------------------------------
// Send the AJAX request to get the modified PDF file as a blob
//---------------------------------------------------------
$.ajax({
	url: '/get-modified-pdf',
	method: 'GET',
	success: function(data) {
		// Create a blob URL from the received blob
		var blobUrl = URL.createObjectURL(data);
		
		// Create an anchor element to download the file
		var downloadLink = $('<a>')
			.attr('href', blobUrl)
			.attr('download', 'modified.pdf')
			.text('Download modified PDF file');
			
		// Add the anchor element to the page
		$('body').append(downloadLink);
	},
	error: function() {
		console.error('Error getting modified file.');
	}
});
//---------------------------------------------------------
// add this to functions.php
//register acf fields to Wordpress API
//https://support.advancedcustomfields.com/forums/topic/json-rest-api-and-acf/

function acf_to_rest_api($response, $post, $request) {
    if (!function_exists('get_fields')) return $response;

    if (isset($post)) {
        $acf = get_fields($post->id);
        $response->data['acf'] = $acf;
    }
    return $response;
}
add_filter('rest_prepare_post', 'acf_to_rest_api', 10, 3);
const express = require('express');
const router = express.Router();

// this is our crud route so it'll have the most routes
// SIGNTAURE TYPE ENDPOINT
// @route       GET api/contacts
// @desc        get user's contacts
// @access      private (theses are all private to user so all private)
// we said anything that goes to this file is coming from /api/auth so we just need a slash
router.get('/', (req, res) => {
    res.send(`Get all the user's contacts`)
})

// SIGNTAURE TYPE ENDPOINT
// @route       POST api/contacts
// @desc        add a new contact
// @access      private 
router.post('/', (req, res) => {
    res.send(`Add a new contact`)
})

// SIGNTAURE TYPE ENDPOINT
// @route       PUT api/contacts/:id (we need to id which contact is getting updated)
// @desc        update contact
// @access      private 
router.put('/:id', (req, res) => {
    res.send(`Update a contact`)
})

// SIGNTAURE TYPE ENDPOINT
// @route       DELETE api/contacts/:id (we need to id which contact is getting deleted)
// @desc        delete contact
// @access      private 
router.delete('/:id', (req, res) => {
    res.send(`DESTROY a contact`)
})

// export router so we can access ittttt
module.exports = router
star

Fri May 12 2023 11:15:35 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs #rest
star

Wed Nov 30 2022 17:21:52 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/56473929/how-to-expose-all-the-acf-fields-to-wordpress-rest-api-in-both-pages-and-custom

#php #wp #acf #rest
star

Thu Jul 15 2021 09:01:59 GMT+0000 (Coordinated Universal Time)

#nodejs #api #routing #rest
star

Thu Jul 16 2020 13:01:21 GMT+0000 (Coordinated Universal Time) https://github.com/an-tao/drogon

#c++ #web #rest

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension