如何在HTML生成的Word文档中调整图像大小并保持纵横比?

11

我根据这些非常好的stackoverflow资源之一从HTML构建了一个Word文档:

对于那些想要尝试的人来说,准备好承受一些痛苦吧,因为在处理CSS时,Word的可靠性很差。如果你想要多列布局,你确实需要回到使用表格来布置。

我一直在努力让一个图片按比例缩放 - 用户上传的图像将用于此Word文档,并且我希望根据“高度”属性调整它们的大小 - 至50px高,然后按比例缩放宽度。

似乎没有任何关于如何完成这项任务的文档。

我还使用了一些html2canvas代码,将一个漂亮的(基于CSS的)条形图转换为图像,然后可以直接在Word文档中使用,如http://www.kubilayerdogan.net/?p=304所述。

这个图片打印出来效果不好,所以我计划在运行html2canvas代码之前(使用jQuery)将源HTML放大在屏幕上(在内存中隐藏) - 这样我就会有一张更大的图片,然后我可以缩小它并获得更高的DPI值。

首先,我了解到CSS的宽度和高度对Word中的图像没有影响。同样,以下内容也不起作用。

<img class="cobrandedlogo" src="' . $logourl . '" height="50px" />';

但我发现使用“points”是这样工作的:

<img class="cobrandedlogo" src="' . $logourl . '" height="50" />';

但这会产生一个非常拉伸的图像(当然,这取决于源材料)。我希望它按照原始图像进行缩放。

我正在使用PHP。

我发现了这篇SO文章,它似乎会有所帮助:计算调整图像大小的比例

这是我一直在使用的一些代码:

jQuery代码来生成div的图像,稍微修改显示的HTML并将其提交到PHP文件:

var wordreport = jQuery('#container').clone();
jQuery(wordreport).find('#stats').html('<img src="http://improvedemployees.com/assets/teamstats/' + jQuery('#imgname').val() + '" />');
jQuery(wordreport).find('.columncontainer').each(function() {
    jQuery(this).children().wrapAll('<table><tr>');
});
// these were 3 columns on the screen - converted to a table and tds for Word
jQuery(wordreport).find('.memberstrengths').wrap('<td valign=top>'); 
jQuery(wordreport).find('.membercommunication').wrap('<td valign=top>');
jQuery(wordreport).find('.memberimproving').wrap('<td valign=top>');

jQuery(wordreport).find('#generateword').remove();
jQuery(wordreport).find('script').remove();             

var htmlpluscss = jQuery(wordreport).html();
htmlpluscss = '<style>.reportsection {border:1px solid #fff!important; padding:0px; margin-bottom:0px;}</style>' + htmlpluscss;
jQuery('#dochtml').val(htmlpluscss);
jQuery('#rawhtml').val(htmlpluscss);
jQuery('#stats').html2canvas({
    onrendered: function (canvas) {
        //Set hidden field's value to image data (base-64 string)
        jQuery('#img_val').val(canvas.toDataURL("image/png"));
        //Submit the form manually
        document.getElementById("getword").submit();
    }
});         

还有这个HTML用于生成Word文档的按钮:

<div id="generateword">
<form method="post" action="/createword.php" target="_blank" id="getword"> 
<input type="hidden" name="docname" id="docname" />
<input type="hidden" name="dochtml" id="dochtml" />
<input type="hidden" name="orientation" id="orientation" value="landscape" />
<input type="hidden" name="logourl" value="<?php echo get_user_meta(get_current_user_id(), 'reportlogourl', true); ?>" />
<input type="hidden" name="img_val" id="img_val" value="" />
<input type="hidden" name="imgname" id="imgname" value="<?php echo $_GET['teamid']; ?>.png" />
<input type="button" value="View in Word" id="createword" />
</form>
</div>

最后 - 这是我使用的 PHP 文件:

<?php

header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=" . $_POST['docname'] . ".doc");

$filteredData=substr($_POST['img_val'], strpos($_POST['img_val'], ",")+1);
//Decode the string
$unencodedData=base64_decode($filteredData);
//Save the image
$imgfile = $_POST['imgname'];
//file_put_contents("/assets/teamstats/" . $imgfile, $unencodedData);
file_put_contents("assets/teamstats/" . $imgfile, $unencodedData);

$orientation = 'portrait';
if(isset($_POST['orientation'])) {
$orientation = 'landscape';
}
$logourl = '';
if(isset($_POST['logourl'])) {
$logourl = $_POST['logourl'];
}

echo '<html xmlns:v="urn:schemas-microsoft-com:vml"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:w="urn:schemas-microsoft-com:office:word"
xmlns:m="http://schemas.microsoft.com/office/2004/12/omml"
xmlns="http://www.w3.org/TR/REC-html40">
<head><meta http-equiv=Content-Type content="text/html; charset=utf-8"><title></title>
<style>
v\:* {behavior:url(#default#VML);}
o\:* {behavior:url(#default#VML);}
w\:* {behavior:url(#default#VML);}
.shape {behavior:url(#default#VML);}
</style>
<style>
@page
{
';
if ($orientation == 'landscape') {
    echo 'mso-page-orientation: landscape;
    size:29.7cm 21cm;    margin:1cm 1cm 1cm 1cm;';
}
else {
    echo 'mso-page-orientation: portrait;
    size:21cm 29.7cm;    margin:1cm 1cm 1cm 1cm;';
}
echo '
}
@page Section1 {
    mso-header-margin:.5in;
    mso-footer-margin:.5in;
    mso-header: h1;
    mso-footer: f1;
    }
div.Section1 { page:Section1; 
font-family:Helvetica; 
';
if ($orientation == 'landscape') {
    echo 'font-size:12px; ';
}
else {
    echo 'font-size:14px; line-height:20px;';
}
echo '
text-align:left;}
table#hrdftrtbl
{
    margin:0in 0in 0in 900in;
    width:1px;
    height:1px;
    overflow:hidden;
}
p.MsoHeader {
';
if ($orientation == 'landscape') {
    echo '    tab-stops:right 29.0cm;';
}
else {
    echo '    tab-stops:right 21.0cm;';
}
echo '
}
p.MsoFooter, li.MsoFooter, div.MsoFooter
{
    margin:0in;
    margin-bottom:.0001pt;
    mso-pagination:widow-orphan;
';
if ($orientation == 'landscape') {
    echo 'tab-stops:center 14.5cm right 29.0cm;';
}
else {
    echo 'tab-stops:center 10.5cm right 21.0cm;';
}
echo '
    font-size:12px;
}

</style>
<xml>
<w:WordDocument>
<w:View>Print</w:View>
<w:Zoom>100</w:Zoom>
<w:DoNotOptimizeForBrowser/>
</w:WordDocument>
</xml>
</head>';
echo "<body>";
echo '<div class="Section1">';
echo $_POST['dochtml'];
echo '<style>h3, table {
margin-top:0px!important;
}
div.membername {
margin-bottom:0px!important;
margin-top:0px!important;
height:39px!important;
line-height:25px!important;
}
div.membername, span.membershape, span.membertraits {
height:39px!important;
line-height:25px!important;
padding:0px!important;
margin:0px!important;
}
h2.membername {
margin-top:0px!important;
margin-bottom:0px!important;
padding-top:0px!important;
padding-bottom:0px!important;
line-height:25px;
height:25px!important;
font-size:24px!important;
}
table.tdmembername, table.tdmembername tr, table.tdmembername td, table.tdmembername span {
background-color:black!important;
}
div.columncontainer {
margin-top:0px!important;
}
img.cobrandedlogo {
max-height:50px;
height:50px;
}
</style>
';
echo '
<br/>
    <table id="hrdftrtbl" border="0" cellspacing="0" cellpadding="0">
    <tr><td>        <div style="mso-element:header" id=h1 >
            <p class=MsoHeader ><img src="http://improvedemployees.com/img/logo-x50.png" style="height:50px" height="50px"/><span style=mso-tab-count:1"></span>';
if ($logourl != "") {
    $newheight = 50;
    list($originalwidth, $originalheight) = getimagesize($logourl);
    $ratio = $originalheight / $newheight;
    $newwidth = $originalwidth / $ratio;
    echo '<img class="cobrandedlogo" src="' . $logourl . '" height="50" width="' . $newwidth . '" />';

}
echo '</p>
        </div>
    </td>
    <td>
    <div style="mso-element:footer" id=f1><span style="position:relative;z-index:-1"> 
        <p class=MsoFooter>
           <span style=mso-tab-count:1"></span>
            www.improvedemployees.com
           <span style=mso-tab-count:1"></span>
           Page <span style="mso-field-code: PAGE "><span style="mso-no-proof:yes"></span> of <span style="mso-field-code: NUMPAGES "></span></span>
        </p>
    </div>



    <div style="mso-element:header" id=fh1>
        <p class=MsoHeader><span lang=EN-US style="mso-ansi-language:EN-US">&nbsp;<o:p></o:p></span></p>
        </div>
        <div style="mso-element:footer" id=ff1>
        <p class=MsoFooter><span lang=EN-US style="mso-ansi-language:EN-US">&nbsp;<o:p></o:p></span></p>
    </div>

    </td></tr>
    </table>
</div>';
echo "</body>";
echo "</html>";

?>

我该如何使用HTML将插入到Word文档中的图片按照高度或宽度进行调整大小,以便Word可以保持图片的长宽比?


如果你正在使用PHP,那么就不能使用jQuery。并且,将图像放大,再缩小不会改善什么。整个问题都有点混乱,请重新表述,并包含一些示例代码,以便我们了解你正在做什么。 - user1864610
我正在使用jQuery在向用户呈现报告的页面上 - 还有一个在线版本的报告可用。 - Dave Hilditch
我使用.clone()方法克隆包含报告的div,然后根据需要添加和删除元素,然后将它们发布到PHP文件。这也是我将图像二进制文件发布到PHP文件的方式,以便可以在服务器端保存图像,然后在Word文档中使用。如果您尝试使用Word HTML,您就会明白。 - Dave Hilditch
关于将图像放大再缩小的问题 - 你确定吗?我非常肯定,如果我将一个1000x500像素的图像加载到Word中,并将其调整为100x50像素,那么打印出来的DPI会比我使用直接的100x50像素图像更好,因为我知道后者会产生锯齿状边缘。 - Dave Hilditch
1个回答

12

我自己解决了这个问题:

如果你想使用 HTML 在 Word 中根据其中一侧缩放图像,则可以使用以下代码:

$newheight = 50;
list($originalwidth, $originalheight) = getimagesize($logourl);
$ratio = $originalheight / $newheight;
$newwidth = $originalwidth / $ratio;
echo '<img class="cobrandedlogo" src="' . $logourl . '" height="50" width="' . $newwidth . '" />';

如果您希望根据宽度缩放,请交换newheight和newwidth。


5
我发现对于Word文件,您不需要使用引号。例如:width=166 height=170。 - ImaginedDesign

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接