Create Word to Pdf Converter in Blogger
Create Word to Pdf Converter in Blogger
To convert a Word document to PDF in a Blogger post, you can utilize the Google Drive API and embed the converted PDF into your blog post. Here's an example of how you can achieve this using JavaScript:
- Set up the Google Drive API:
- Go to the Google Cloud Console.
- Create a new project and enable the Google Drive API.
- Generate credentials (OAuth 2.0 client ID) and download the JSON file.
- Add the required script tags to your Blogger template:
Script Code:-
<script src="https://apis.google.com/js/api.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Create an HTML container for the file input and conversion button:
HTML Code
<div>
<input type="file" id="file-input">
<button id="convert-button">Convert to PDF</button>
</div>
Implement the JavaScript code:
// Load the Google Drive API
function loadDriveApi() {
gapi.load('client', initDriveApi);
}
// Initialize the Google Drive API
function initDriveApi() {
gapi.client.init({
apiKey: 'YOUR_API_KEY',
clientId: 'YOUR_CLIENT_ID',
discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest'],
scope: 'https://www.googleapis.com/auth/drive.file'
}).then(function () {
// Attach event listener to the conversion button
$('#convert-button').click(uploadAndConvert);
});
}
// Upload the file and convert to PDF
function uploadAndConvert() {
var file = $('#file-input')[0].files[0];
var metadata = {
name: file.name,
mimeType: 'application/vnd.google-apps.document'
};
var reader = new FileReader();
reader.onload = function(e) {
var content = e.target.result;
// Upload file to Google Drive
var fileData = new Blob([content], { type: file.type });
var accessToken = gapi.auth.getToken().access_token;
var form = new FormData();
form.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' }));
form.append('file', fileData);
$.ajax({
url: 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart',
type: 'POST',
headers: { 'Authorization': 'Bearer ' + accessToken },
data: form,
processData: false,
contentType: false,
success: function(data) {
// Convert uploaded file to PDF
var fileId = data.id;
var convertedFileName = file.name.replace(/\.[^/.]+$/, "") + '.pdf';
var requestBody = { 'targetMimeType': 'application/pdf' };
gapi.client.drive.files.export({ fileId: fileId, mimeType: 'application/pdf', requestBody: requestBody })
.then(function(response) {
var pdfUrl = response.result.webContentLink;
var embedHtml = '<embed src="' + pdfUrl + '" width="100%" height="600px" type="application/pdf">';
// Display the PDF in the blog post
$('#pdf-container').html(embedHtml);
});
},
error: function(error) {
console.error('Error uploading file:', error);
}
});
};
reader.readAsArrayBuffer(file);
}
// Initialize the Google Drive API on page load
function handleClientLoad() {
gapi.load('client:auth2', loadDriveApi);
}
Replace `'YOUR_API_KEY'