Search code examples
htmlcsspdfgroovyflying-saucer

FlyingSaucer: convert an HTML document to PDF ignoring external CSS?


I'm using the following to convert HTML to PDF:

InputStream convert(InputStream fileInputStream) {

        PipedInputStream inputStream = new PipedInputStream()
        PipedOutputStream outputStream = new PipedOutputStream(inputStream)
        new Thread({
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(false);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(fileInputStream)

            ITextRenderer renderer = new ITextRenderer()
            renderer.setDocument(document, "")
             renderer.layout()
            renderer.createPDF(outputStream)
        }).start()

        return inputStream
    }

From the documentation, apparently I should be able to set a "User Agent" resolver somewhere, but I'm not sure where, exactly. Anyone know how to ignore external CSS in a document?


Solution

  • Not the same question but my answer for that one will work here too: Resolving protected resources with Flying Saucer (ITextRenderer)

    Override this method:

    public CSSResource getCSSResource(String uri) {
        return new CSSResource(resolveAndOpenStream(uri));
    }
    

    with

    public CSSResource getCSSResource(String uri) {
        return new CSSResource(new ByteArrayInputStream([] as byte[]));
    }