简体   繁体   English

如何在 HTML 字符串中将正确的 url 嵌入到自定义字体中

[英]How to embed the right url to custom font in HTML string

How to embed the right url to custom font in my HTML string.如何在我的 HTML 字符串中嵌入正确的 url 到自定义字体。

I do the following:我执行以下操作:

   string exeFile = (new System.Uri(Assembly.GetEntryAssembly().CodeBase)).AbsolutePath;
   string path4 = Path.Combine(Regex.Escape(exeDir), "\\..\\\\..\\\\CSS\\\\majalla.ttf");
   string arabicFont = @"@font-face {
                      font-family: 'sakkal_majallaregular';
                      src: url(" + "'" + path4 + "'" + @"), url('majalla-webfont.woff2') format('woff2'), url('majalla-webfont.woff') format('woff');}";

This doesn't work(doesn't take effect).这不起作用(不生效)。 After debugging path4 =调试后path4 =

C:\\\\Users\\\\AA\\\\Desktop\\\\PrintingStatement\\\\PrintingStatement\\\\bin\\\\Debug\\\\..\\\\..\\\\CSS\\\\majalla.ttf

When I try the constant absolute url like this:当我尝试这样的常量绝对 url 时:

url('C:\\Users\\AA\\Desktop\\PrintingStatement\\PrintingStatement\\CSS\\majalla.ttf') 

It works fine.它工作正常。 How to convert my url to the previous one in production environment.如何在生产环境中将我的 url 转换为上一个。

MY Updated HTML Method我更新的 HTML 方法

   protected string StyleStatementDoc(SingleStatement statementToPrint)
        {
            string path1 = "CSS/StatementVerifacation.css";
            string path2 = "CSS/Statement.css";
            string path3 = "CSS/print.min.css";
            string path4 = "CSS/majalla.ttf"; 

            string arabicFont = @"@font-face {
                                            font-family: 'sakkal_majallaregular';
                                            src: url(" + "'" + path4 + "'" + @"), url('majalla-webfont.woff2') format('woff2'), url('majalla-webfont.woff') format('woff');
                                           }";
            string htmlData = @"<!DOCTYPE html>
                                <html>
                                <head>
                                    <title>Statement</title>
                                     <style>" + arabicFont + @"


                                            body {
                                            font-size: 20px;
                                            background-color: White;
                                            color: Black;
                                            font-family:'sakkal_majallaregular', Arial, Helvetica, sans-serif;
                                            text-align:right;
                                            direction:rtl;

                                             }
                                           p {
                                              line-height: 32px;   /* within paragraph */
                                              margin-bottom: 30px; /* between paragraphs */
                                              }
                                    </style>
                                    <link href = '" + path1 + "'" + " rel='stylesheet' />" + @"

                                   <link href = '" + path3 + "'" + " rel='stylesheet' />" + @"

                                        </head>
                                <body>
                                    <div class='my' id='editor1'>" + statementToPrint.StatementBeforePrint + @"

                                    </div>
                                </body>
                                </html>
                                ";

           // htmlData = htmlData.Replace(@"<head>", $@"<head><base href=""{new Uri(Application.StartupPath)}/""/>");
            return htmlData;
        }
       System.Windows.Forms.WebBrowser webBrowser = new System.Windows.Forms.WebBrowser();
        protected void Print(string htmlData)
        {

            webBrowser.SetHtmlContent(htmlData, $@"{new Uri(Application.StartupPath)}/");

            webBrowser.Print();
        }

My project structure:我的项目结构:

在此处输入图片说明

To resolve relative addresses you have the following options:要解析相对地址,您有以下选项:

  1. Using a placeholder in html and replace it with bin folder address.在 html 中使用占位符并将其替换为 bin 文件夹地址。 (Works for everything but fonts) (适用于除字体外的所有内容)
  2. Injection <base> tag in head.在头部注入<base>标签。 (Works for everything but fonts) (适用于除字体外的所有内容)
  3. Implementing IMoniker to set base url for document.实现IMoniker以设置文档的基本 URL。 (Works for everything as well as fonts) I've implemented an extension method for WebBrowser1.SetHtmlContent(html, url) (适用于所有字体以及字体)我已经为WebBrowser1.SetHtmlContent(html, url)实现了一个扩展方法

Example例子

Assuming you have an html like this:假设你有一个这样的 html:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <title>Sample</title>
    <style>
        @font-face {
            font-family: "MyFont";
            src: url('./Contents/MyFont.ttf') format('truetype');
        }

        body {
            background-image: url('./Contents/Image.jpeg');
            font-family: 'MyFont';
            font-weight: normal;
            font-style: normal;
            font-size: 30px;
            color: red;
        }
    </style>
</head>
<body>
    Something
</body>
</html>

I assume you have Contents folder containing Image.jpeg and MyFont.ttf files in your project output directory.我假设您的项目输出目录中有包含Image.jpegMyFont.ttf文件的Contents文件夹。 (If you have them in your project, them in your project, to copy them into output directory into the right folder structure, just in the properties window of those files in solution explorer, set Copy to output directory to Copy Always .) (如果你的项目中有它们,它们在你的项目中,将它们复制到输出目录到正确的文件夹结构中,只需在解决方案资源管理器中这些文件的属性窗口中,将Copy to output directory设置为Copy Always 。)

Solution 1 - use a placeholder in HTML file and replace it with bin path解决方案 1 - 在 HTML 文件中使用占位符并将其替换为 bin 路径

So instead of ./ use $ROOT$/ , for example: background-image:url('$ROOT$/Resources/Sample.jpeg');所以代替./使用$ROOT$/ ,例如: background-image:url('$ROOT$/Resources/Sample.jpeg'); Then when setting document text of the browser, replace it with start up path of the application:然后在设置浏览器的文档文本时,将其替换为应用程序的启动路径:

this.webBrowser1.DocumentText = yourHtmlContent.Replace("$ROOT$", 
    new Uri(Application.StartupPath).ToString());

Solution 2 - Injectting html <base> tag解决方案 2 - 注入 html <base>标签

Assuming you don't have any placeholder in the html content.假设您在 html 内容中没有任何占位符。 Then it's enough to inject a <base> tag into <head> like this:然后像这样将<base>标记注入<head>就足够了:

var html = System.IO.File.ReadAllText("HTMLPage1.html");
html = html.Replace(@"<head>", $@"<head><base href=""{new Uri(Application.StartupPath)}/""/>");
webBrowser1.DocumentText = html;

It means all the relative addresses will be resolved using <base> href attribute.这意味着将使用<base> href 属性解析所有相对地址。

Solution 3 - Implemeting IMoniker解决方案 3 - 实施IMoniker

You can implement IMoniker interface and using IWebBrowser2 from SHDocVw load the html content and set a base url for that.您可以实现IMoniker接口并使用来自SHDocVw IWebBrowser2加载 html 内容并为其设置基本 url。 I used this method for relative address of @font-face as well as relative address for other stuff in html content and it worked well.我将此方法用于@font-face相对地址以及 html 内容中其他内容的相对地址,并且效果很好。

You find an Implementation which I shared in this post: Set URL of custom HTML loaded in webbrowser and easily use it like this:您会找到我在这篇文章中分享的实现:设置 webbrowser 中加载的自定义 HTML 的 URL,并像这样轻松使用它:

webBrowser1.SetHtmlContent(html, 
    $@"{new Uri(Application.StartupPath)}/");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM