Skip to content

Instantly share code, notes, and snippets.

@Qubadi
Last active July 24, 2024 21:34
Show Gist options
  • Save Qubadi/e3a04065c01f67907715d17d180d8698 to your computer and use it in GitHub Desktop.
Save Qubadi/e3a04065c01f67907715d17d180d8698 to your computer and use it in GitHub Desktop.
Jetformbuilder convert email form to PDF ( Custom code )
1. Download the dompdf file, and add the file to wp-content and extract it after.
https://github.com/dompdf/dompdf/releases/download/v2.0.3/dompdf_2-0-3.zip
2. Dont forget to add subject line text in Jetformbuilder, and add it to this line:
$expected_subject_line = 'YOUR SUBJECT LINE TEXT, Or the form will not work. Cause its integrated by subject line text.
3. Change the url link for company logo to yours logo
4. Used hidden field for media, dont forget to add your on field name, and classname too.
Or u can use the same name i have added in allready. u have used fieldname: mediafield and classname: mediafield_classname
5. You dont need to add all the field name manually in Jetformbuilder sendmail content, u can add a text something like that only:
Hello,
Thank you for your message. Please find the friends list attached for your reference.
Best regards.
Importent to add some text there, but not the fieldname, add any text there u want.
More information here:
Jetformbuilder convert the form to a PDF file, email. It modifies the behavior of the wp_mail function to attach a PDF
to emails generated by a specific form submission.
Here's a brief explanation:
Email Filter Addition: First, it checks if a filter named 'attach_pdf_to_wp_mail_v2' is not already added to 'wp_mail'.
If not, it adds this filter.
Function Definition: Then, it defines the function attach_pdf_to_wp_mail_v2. This function is triggered when an email is
being sent using wp_mail.
PDF Creation and Attachment: Inside this function, it checks if the Jetformbuilder form email subject matches a specific
form submission Exemple ('Book car | Contact form'). If it does, the function generates a PDF document using the Dompdf library.
This PDF includes the form submission data and a logo fetched via cURL. The PDF is then attached to the email.
Form Data Retrieval: There's a separate function get_form_submission_data to retrieve and sanitize the form data.
Media Upload Field: Finally, the script includes a function to add a media upload field to the form.
It uses JavaScript to enforce file type and size restrictions on this field.
In summary, this script customizes how emails are sent from a WordPress site, specifically for a certain form,
by attaching a dynamically generated PDF and adding a media upload field to the form.
Last, In Jetformbuilder form recommend to toggle on Enable csrf protection.
Add the custom code to your snippet plugins. Run everywhere.
// Add a filter to wp_mail to modify the email before sending
if (!has_filter('wp_mail', 'attach_pdf_to_wp_mail_v2')) {
add_filter('wp_mail', 'attach_pdf_to_wp_mail_v2', 10, 1);
}
if (!function_exists('attach_pdf_to_wp_mail_v2')) {
function attach_pdf_to_wp_mail_v2($args) {
// Define the subject line you set in JetFormBuilder for your form submission emails
$expected_subject_line = 'YOUR SUBJECT LINE TEXT'; // Replace with your form's subject line
// Check if the email is the result of a JetFormBuilder form submission by subject
if (strpos($args['subject'], $expected_subject_line) !== false) {
// Include the Dompdf library
require_once WP_CONTENT_DIR . '/dompdf/autoload.inc.php';
// Retrieve the form submission data
$form_data = get_form_submission_data(); // Dynamic field retrieval
// Handle media file upload
$media = $_FILES['mediafield'];
$file_url = '';
if ($media['error'] === UPLOAD_ERR_OK) {
$upload = wp_handle_upload($media, ['test_form' => false]);
$file_url = $upload['url'];
$form_data['mediafield'] = $file_url; // Add the media URL to form data
}
// Initialize Dompdf and generate the PDF
$dompdf = new \Dompdf\Dompdf();
// Get the logo image data using cURL
$logo_url = 'YOUR URL LOGO';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $logo_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$logo_data = curl_exec($ch);
curl_close($ch);
// Generate a data URL for the logo image
$logo_data_uri = 'data:image/webp;base64,' . base64_encode($logo_data);
// Define CSS for the HTML content
$css = "
<style>
body { font-family: 'Helvetica', 'Arial', sans-serif; }
h1 { color: #333; margin-top: 20px; }
p { color: #555; font-size: 14px; margin-bottom: 10px; }
.content-wrapper { padding: 20px; }
.header img { width: 150px; height: auto; margin-bottom: 10px; }
.media-img { max-width: 100%; height: auto; margin-top: 10px; }
</style>
";
// Generate the HTML content for the PDF with the form data
$html_content = $css . "
<div class='header'>
<img src='{$logo_data_uri}' alt='Company Logo'>
</div>
<div class='content-wrapper'>
<h1>Submission Details</h1>";
foreach ($form_data as $field_name => $value) {
if ($field_name === 'mediafield' && !empty($value)) {
// Embed the media image
$media_data = base64_encode(file_get_contents($value));
$media_src = 'data:image/' . pathinfo($value, PATHINFO_EXTENSION) . ';base64,' . $media_data;
$html_content .= "<img src='" . $media_src . "' alt='Uploaded Media' class='media-img'>";
} else {
// Convert line breaks to <br> tags and preserve HTML formatting
$formatted_value = nl2br($value);
$html_content .= "<p><strong>" . ucfirst(str_replace('_', ' ', $field_name)) . ":</strong> " . $formatted_value . "</p>";
}
}
$html_content .= "</div>";
// Load the HTML content
$dompdf->loadHtml($html_content);
// Set paper size and orientation
$dompdf->setPaper('A4', 'portrait');
// Render the PDF
$dompdf->render();
// Save the PDF to a file
$pdf_output = $dompdf->output();
$pdf_file_path = sys_get_temp_dir() . '/form_submission_' . time() . '.pdf';
file_put_contents($pdf_file_path, $pdf_output);
// Attach the PDF to the email
$args['attachments'] = array($pdf_file_path);
}
// Return the modified email arguments
return $args;
}
// Function to dynamically retrieve form submission data
function get_form_submission_data() {
$form_data = array();
// Criteria to exclude non-user-added fields
$excluded_patterns = array(
'/^wp_/', // WordPress specific fields
'/^jet_/', // JetFormBuilder specific fields
'/_id$/', // Fields ending with '_id'
'/^_/', // Hidden or internal fields
);
foreach ($_POST as $key => $value) {
// Skip fields that match the exclusion criteria
foreach ($excluded_patterns as $pattern) {
if (preg_match($pattern, $key)) {
continue 2;
}
}
// Allow HTML tags for specific fields (e.g., text areas)
$allowed_html_tags = array(
'a' => array(
'href' => array(),
'title' => array()
),
'br' => array(),
'em' => array(),
'strong' => array(),
'i' => array(),
'b' => array(),
'p' => array(),
'h1' => array(),
'h2' => array(),
'h3' => array(),
'h4' => array(),
'h5' => array(),
'h6' => array(),
);
// Sanitize the field based on its type
switch (true) {
case filter_var($value, FILTER_VALIDATE_EMAIL):
$form_data[$key] = sanitize_email($value);
break;
case is_string($value):
$form_data[$key] = wp_kses($value, $allowed_html_tags);
break;
}
}
return $form_data;
}
// Add the media upload field to the form
function add_media_upload_field_to_form() {
?>
<style>
input#mediafield {
padding: 30px;
border-style: solid;
border-width: 1px;
border-radius: 10px;
margin: 10px;
width: 400px;
}
.media-upload-field {
margin-bottom: 20px; /* Adjust as needed */
}
.media-upload-field label {
display: block;
margin-bottom: 10px;
}
@media only screen and (max-width: 768px) {
input#mediafield {
margin-bottom: 15px; /* Adjusted for smaller screens */
width: 80% !important;
}
</style>
<script type="text/javascript">
jQuery(document).ready(function($) {
// Function to add the media upload field
function addMediaField() {
// Check if the media upload field already exists to avoid duplicates
if ($('#mediafield').length === 0) {
// Create the media upload field
var mediaField = '<div class="media-upload-field"><label for="mediafield">Media (Max: 1 file, 4MB):</label><input type="file" name="mediafield" id="mediafield" required></div>';
// Insert the media upload field before the specified class
$('.mediafield_class').before(mediaField);
// Add file upload restrictions
$('#mediafield').on('change', function(e) {
var file = e.target.files[0];
if (file) {
// Check file size
if (file.size > 4194304) { // 4MB in bytes
alert('Maximum file size: 4MB');
e.target.value = ''; // Clear the file input
}
// Check file type
if (!['image/png', 'image/jpeg', 'image/webp', 'image/gif'].includes(file.type)) {
alert('Allowed file types: png, jpg, webp, gif');
e.target.value = ''; // Clear the file input
}
}
});
}
}
// Try to add the media field immediately
addMediaField();
// Retry adding the media field after a short delay to handle any timing issues
setTimeout(addMediaField, 500);
});
</script>
<?php
}
add_action('wp_footer', 'add_media_upload_field_to_form');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment