【问题标题】:Inline external CSS with HTML使用 HTML 内联外部 CSS
【发布时间】:2012-10-29 17:47:27
【问题描述】:

我正在寻找一个 java 库,它可以根据其 ID/类属性将外部 CSS 文件与 HTML 文档内联。

我找到了jStyleParser,但我不确定这是否适合我。我似乎无法理解它是否可以完成在 HTML 元素上内联 CSS 的工作。文档和示例不是我所期望的。

有没有人可以回答这个问题,或者是否有其他图书馆可以解决这个问题?

谢谢

【问题讨论】:

    标签: java html css parsing jstyleparser


    【解决方案1】:

    我对@9​​87654321@ (v1.5.2) 非常满意。我有这样的方法:

     public static String inlineCss(String html) {
        final String style = "style";
        Document doc = Jsoup.parse(html);
        Elements els = doc.select(style);// to get all the style elements
        for (Element e : els) {
          String styleRules = e.getAllElements().get(0).data().replaceAll("\n", "").trim();
          String delims = "{}";
          StringTokenizer st = new StringTokenizer(styleRules, delims);
          while (st.countTokens() > 1) {
            String selector = st.nextToken(), properties = st.nextToken();
            if (!selector.contains(":")) { // skip a:hover rules, etc.
              Elements selectedElements = doc.select(selector);
              for (Element selElem : selectedElements) {
                String oldProperties = selElem.attr(style);
                selElem.attr(style,
                    oldProperties.length() > 0 ? concatenateProperties(
                        oldProperties, properties) : properties);
              }
            }
          }
          e.remove();
        }
        return doc.toString();
      }
    
      private static String concatenateProperties(String oldProp, @NotNull String newProp) {
        oldProp = oldProp.trim();
        if (!oldProp.endsWith(";"))
          oldProp += ";";
        return oldProp + newProp.replaceAll("\\s{2,}", " ");
      }
    

    【讨论】:

    • 我认为你缺少concatenateProperties函数:)
    • 感谢@zozelfelfo - 我添加了缺少的功能
    • 从 mandrill 切换到 amazon ses - 你拯救了我的一天 :) Mandrill 自己做这个内联
    • @Nic Cottrell 不确定这对外部 CSS 文档如何工作?
    • @JustinR 你只需要将内容加载到 styleRules 变量中
    【解决方案2】:

    你可以试试CSSBox。只需查看包中包含的 ComputeStyles 演示(有关运行演示的信息,请参阅分发包中的 doc/examples/README 文件)。它计算所有样式并使用相应的内联样式定义创建一个新的 HTML 文档(由 DOM 表示)。

    源代码在 src/org/fit/cssbox/demo/ComputeStyles.java 中,而且很短。实际上,它使用 jStyleParser 来完成主要工作,CSSBox 只是为此提供了一个更好的界面。

            //Open the network connection 
            DocumentSource docSource = new DefaultDocumentSource(args[0]);
    
            //Parse the input document
            DOMSource parser = new DefaultDOMSource(docSource);
            Document doc = parser.parse();
    
            //Create the CSS analyzer
            DOMAnalyzer da = new DOMAnalyzer(doc, docSource.getURL());
            da.attributesToStyles(); //convert the HTML presentation attributes to inline styles
            da.addStyleSheet(null, CSSNorm.stdStyleSheet(), DOMAnalyzer.Origin.AGENT); //use the standard style sheet
            da.addStyleSheet(null, CSSNorm.userStyleSheet(), DOMAnalyzer.Origin.AGENT); //use the additional style sheet
            da.getStyleSheets(); //load the author style sheets
    
            //Compute the styles
            System.err.println("Computing style...");
            da.stylesToDomInherited();
    
            //Save the output
            PrintStream os = new PrintStream(new FileOutputStream(args[1]));
            Output out = new NormalOutput(doc);
            out.dumpTo(os);
            os.close();
    
            docSource.close();
    

    【讨论】:

    • 确认!它在 AppEngine 中不起作用!诅咒你的谷歌!
    • @radkovo 如果源是 String input = "..."(而不是 URL),如何修改此示例?顺便说一句,干得好!
    • @athspk 您必须编写自己的 DocumentSource 实现,从字符串而不是 URL 创建输入流。这应该很简单,看一下原始的 DefaultDocumentSource 实现即可。 Here 你可能会发现如何从字符串创建输入流。
    • 是的,最后我就是这样做的。再次感谢!
    • 你能创建一个例子来从 html 创建一个 DocumentSource 吗?直到现在我才找到方法。我没有一个文件来读取一个文件来输出。我想读取一个字符串并输出一个字符串...
    猜你喜欢
    • 1970-01-01
    • 2018-10-24
    • 2021-06-10
    • 1970-01-01
    • 2013-05-24
    • 2010-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多