<div id="mainDiv" class="watermark" style="font-family: Calibri; padding: 10px; border: 1px solid lightgrey;">
<script type="text/javascript">
(function () {
var watermarkImage = "url(../../Resources/Watermark/" + @Model.Watermark + ".png)";
var x = document.getElementsByClassName("watermark");
x.setAttribute('background-image', watermarkImage);
x.setAttribute('background-repeat', 'repeat-y')
})();
</script>
我正在使用mvc + rotativa将cshtml转换为pdf。我从控制器传递了图像名称。但是当生成pdf时,水印不会出现。我想使用javascript将div属性添加到css属性。
答案 0 :(得分:1)
如果要将CSS添加到具有唯一ID的单个块,请尝试以下代码:
<script type="text/javascript">
(function () {
var watermarkImage = "url(../../Resources/Watermark/" + @Model.Watermark + ".png)";
document.getElementById("mainDiv").style.background-image = watermarkImage;
document.getElementById("mainDiv").style.background-repeat = 'repeat-y';
})();
</script>
希望这会对你有帮助!
答案 1 :(得分:1)
这可能对您有所帮助
x.style.background-image= watermarkImage;
x.style.background-repeat = repeat-y;
有关详细信息,您可以使用此链接 https://www.w3schools.com/jsref/met_element_setattribute.asp
答案 2 :(得分:0)
使用rotativa生成pdf时,“@”符号在<script>
标记和<style>
标记中使用时会删除其余代码。所以我们不能在变量中设置background-image url或者不能从控制器传递。我通过以下方式解决了
@if (Model.IsArchieved == true && !string.IsNullOrEmpty(Model.ArchivedVersion))
{
<style type="text/css">
.watermark {
background-image: url(../../Resources/Watermark/Archived.png);
background-repeat: repeat;
background-size: 600px 300px;
}
</style>
}
@if (Model.IsPublished == false)
{
<style type="text/css">
.watermark {
background-image: url(../../Resources/Watermark/Draft5.png);
background-repeat: repeat;
background-size: 500px 275px;
}
</style>
}