Hello everyone, I have created a custom Suitelet w...
# ask-stanley-ai
v
Hello everyone, I have created a custom Suitelet where users can select a Sales Order and submit it to generate a PDF using an advanced PDF template. However, when executing the script, I encounter an “Invalid XML” error. If there are two Sales Orders, I want both in a single PDF, with the first Sales Order on the first page and the second Sales Order on the second page
Copy code
/**
 * @NApiVersion 2.1
 * @NScriptType Suitelet
 */
define(['N/render', 'N/record', 'N/file', 'N/log'], function (render, record, file, log) {
    function onRequest(context) {
        if (context.request.method === 'GET') {
            var orderIds = JSON.parse(context.request.parameters.orders || '[]');
            if (!orderIds.length) {
                context.response.write('No orders selected.');
                return;
            }
            log.debug('Order IDs', orderIds);
            var xmlContent = '<?xml version="1.0″ encoding="UTF-8″?>\n<pdfset>';
            orderIds.forEach(function (soId) {
                try {
                    var salesOrder = record.load({ type: record.Type.SALES_ORDER, id: soId });
                    var singleRenderer = render.create();
                    singleRenderer.setTemplateById(102); // Update with your actual PDF template ID
                    singleRenderer.addRecord('record', salesOrder);
                    var pdfBody = singleRenderer.renderAsString();
                    pdfBody = cleanXml(pdfBody);
                    xmlContent += `<pdf>${pdfBody}</pdf>\n`;
                } catch (e) {
                    log.error('Error loading Sales Order or rendering PDF', e);
                }
            });
            xmlContent += `</pdfset>`;
 log.debug('Final XML Content', xmlContent);
            try {
                // Ensure the XML content is valid before converting to PDF
                if (!isValidXml(xmlContent)) {
                    context.response.write('Error: Invalid XML structure. Check logs for details.');
                    log.error('Invalid XML structure', xmlContent);
                    return;
                }
                var finalPdf = render.xmlToPdf({ xmlString: xmlContent });
                saveAndServePdf(finalPdf, context);
            } catch (e) {
                log.error('Error rendering final PDF', e);
                context.response.write('Error generating PDF: ' + e.message);
            }
        }
    }
    function cleanXml(xmlString) {
        return xmlString
            .replace(/<\?xml.*?\?>/g, ") // Remove XML declaration inside content
            .replace(/<!DOCTYPE[^>]*>/g, ") // Remove DOCTYPE declaration
            .replace(/[\u0000-\u001F\u007F-\u009F]/g, ") // Remove control characters
            .replace(/&(?!amp;|lt;|gt;|quot;|apos;)/g, '&') // Escape unencoded ampersands
            .replace(/>/g, '>') // Escape greater than symbol
            .replace(/</g, '<'); // Escape less than symbol
    }
    function isValidXml(xmlString) {
        try {
            var parser = new DOMParser();
            var xmlDoc = parser.parseFromString(xmlString, 'application/xml');
            return !xmlDoc.querySelector('parsererror'); // Returns true if XML is valid
        } catch (e) {
            return false;
        }
    }
    function saveAndServePdf(finalPdf, context) {
        var mergedPdfFile = file.create({
            name: 'Merged_SalesOrders.pdf',
            fileType: file.Type.PDF,
            contents: finalPdf.getContents(),
            folder: 2552, // Update with your actual folder ID
            isOnline: true
        });
        var mergedFileId = mergedPdfFile.save();
        var fileRecord = file.load({ id: mergedFileId });
        context.response.write(`<script>window.open('${fileRecord.url}', '_blank');</script>`);
    }
    return { onRequest: onRequest };
});
c
AI generated answer (using internal Slack threads):
Based on the provided Slack threads, it seems like you are encountering an "Invalid XML" error when trying to generate a PDF from a custom Suitelet. This error is typically caused by invalid characters or incorrect XML structure in the data being processed. Here are some suggestions to resolve this issue: 1. Check for Invalid Characters: Ensure that the data being processed does not contain any invalid characters that could be causing the XML parsing to fail. This includes characters like ampersands (&), less than (<), greater than (>), etc. These characters need to be properly escaped in XML. 2. Check XML Structure: Make sure that the XML structure being used is correct. Any missing or extra tags could cause the XML parsing to fail. 3. Clean the XML: In your code, you have a
cleanXml
function that cleans the XML string. Make sure this function is working correctly and is properly cleaning the XML string. 4. Validate the XML: Before converting the XML content to PDF, you are checking if the XML content is valid with the
isValidXml
function. Make sure this function is correctly validating the XML. 5. Check the Data: If you are using any data in the XML, make sure the data is correct and does not contain any characters that could cause the XML parsing to fail. 6. Check the Renderer: Make sure the renderer is correctly set up and is able to render the PDF. If you are still encountering issues, you may need to debug your code to find the exact cause of the issue. You can use
log.debug
to log any variables or data that could be causing the issue. ****** Disclaimer: This response was generated by an artificial intelligence assistant based on previous conversations from multiple Slack channels, and may contain inaccuracies or mistakes. ******
Slack thread 1: here (available only if the original thread was posted in the last 90 days)
Similarity score: 0.887575269
Slack thread 2: here (available only if the original thread was posted in the last 90 days)
Similarity score: 0.868519
Slack thread 3: here (available only if the original thread was posted in the last 90 days)
Similarity score: 0.864346206
Please provide your feedback on this answer.
v
i got the error in below field var finalPdf = render.xmlToPdf({ xmlString: xmlContent });
c
Thank you for your feedback