How to Use Weglot to Automatically Translate PDFs Created with Gravity Forms and Gravity PDF

 

Weglot is a popular plugin that automatically translates website content. It’s a powerful tool for creating multilingual WordPress sites with ease.

More interestingly, Weglot can also be used to translate the dynamic content of PDFs generated with Gravity Forms and Gravity PDF.

To achieve this, you need to add a specific code snippet to the `functions.php` file of your active theme. Note: This method will not work if the code is placed in a must-use plugin (`mu-plugin`).

<?php
/*
*	Allow Weglot to dynamically translate Gravity PDF
*
*/
function get_entry_meta( $entry_meta, $form_id ) {
	$entry_meta['weglot_language']   = array(
		'label'                      => 'Weglot language',
		'is_numeric'                 => false,
		'is_default_column'          => true,
		'update_entry_meta_callback' => array( $this, 'update_entry_meta' ),
	);
	return $entry_meta;
}
function update_entry_meta( $key, $lead, $form ) {
	return ""; // return the value of the entry meta
}
add_action( 'gform_after_submission', 'after_submission' );
function after_submission( $entry ) {
	$request_url_services = weglot_get_service( 'Request_Url_Service_Weglot' );
	$current_language = $request_url_services->get_current_language()->getExternalCode();
  gform_update_meta( $entry['id'], 'weglot_language', $current_language );
}
add_filter( 'gfpdf_pdf_html_output', function( $html, $form, $entry, $settings, $Helper_PDF ) {
	$weglot_language = gform_get_meta( $entry['id'], 'weglot_language' );
	if($weglot_language === weglot_get_original_language()){
		return $html;
	}
	$qp = new GFPDF\Helper\Helper_QueryPath();
	$wrapper = $qp->html5( $html );
	$pdf_translate_service = weglot_get_service( 'Pdf_Translate_Service_Weglot' );
	$html = $pdf_translate_service->translate_pdf( $html, $weglot_language );
	$wrapper = $qp->html5( $html['content'] );	
	return $wrapper->top( 'html' )->innerHTML5();
}, 10, 5 );
?>

1 Comment

  1. Love the tutorial! Just wanted to add that Gravity PDF generates PDF documents on demand. To prevent excessive calls to Weglot’s API, consider saving the results of `$pdf_translate_service->translate_pdf()` to the entry meta with `gform_update_meta()`. You can then check if the meta exists and, if it does use, load the saved HTML instead of hitting the API again. 👍

    Reply

Submit a Comment

Your email address will not be published. Required fields are marked *