首页 > 解决方案 > 如何在打印时正确对齐文本

问题描述

我有一个只有一行的 HTML 表,当用户从中选择任何项目时,第一列会自动完成。

我正在填充相应的字段,因此在填充所有数据后,我试图在用户单击时将表的某些列数据对齐print

我正在使用@media print,但它没有做任何事情

请看看这个小提琴

console.clear()

const data = [ //data to populate Item Name search input field
  {
    "ItemName": "Butter"
  },
  {
    "ItemName": "Rice"
  },
  {
    "ItemName": "Milk"
  },
  {
    "ItemName": "Ice Cream"
  },
  {
    "ItemName": "Curd"
  }
]

const data1 = { // this data will be dynamic but for now to test i am using this single data
  butter: {
    "ItemName": "Butter",
    "ItemCode": 400564,
    "PurRate": 8,
    "DiscAmt": 6,
    "gstPercentage": 35,
    "gstAmt": 5
  },
  rice: {
    "ItemName": "Rice",
    "ItemCode": 400565,
    "PurRate": 3,
    "DiscAmt": 2,
    "gstPercentage": 20,
    "gstAmt": 8
  },
  milk: {
    "ItemName": "Milk",
    "ItemCode": 200569,
    "PurRate": 1,
    "DiscAmt": 1,
    "gstPercentage": 50,
    "gstAmt": 2
  },
  'ice cream': {
    "ItemName": "Ice cream",
    "ItemCode": 800002,
    "PurRate": 16,
    "DiscAmt": 2,
    "gstPercentage": 15,
    "gstAmt": 2
  },
  curd: {
    "ItemName": "Curd",
    "ItemCode": 100289,
    "PurRate": 9,
    "DiscAmt": 1,
    "gstPercentage": 12,
    "gstAmt": 4
  },
}

var totalAmount = "";
var unitQuantity = "";


function rowappend(tbody) { // this one is appending row{

  const markup =
    `<tr>
  <td>
    <input type="text" class="form-control commantd" name="itemNametd">
  </td>
  <td name="itemCodetd" class="commantd"></td>
  <td>
    <input type="text" class="form-control commantd" name="unitQtytd">
  </td>
  <td name="purRatetd" class="commantd"></td>
  <td>
    <input type="text" class="form-control commantd" name="discPercentagetd">
  </td>
  <td name="discAmttd" class="commantd"></td> 
  <td name="gstPercentagetd" class="commantd"></td>
  <td name="gstAmttd" class="commantd"></td>
  <td name="totalAmttd" class="commantd"></td>
  
</tr>`

  $(tbody).append(markup);
  setTimeout(() => $("[name=itemNametd]", tbody).last().focus(), 100);

  const itemName = data.map(value => { //using autocomplete to for searching input field
    return value.ItemName;
  });
  $("[name=itemNametd]", tbody).last().autocomplete({
    source: itemName,
    autoSelectFirst: true,
    autoFocus: true
  });
}
rowappend($('tbody', '#tableInvoice'))


function getValues(row) {
  const search = ($('[name=itemNametd]', row).val()).toString()
  const value = data1[search.toLowerCase()];
  if (value) {
    $(row).find("[name=itemCodetd]").text(value.ItemCode);
    $(row).find("[name=purRatetd]").text(value.PurRate);
    $(row).find("[name=discAmttd]").text(value.DiscAmt);
    $(row).find("[name=gstPercentahgetd]").text(value.gstPercentage);
    $(row).find("[name=gstAmttd]").text(value.gstAmt);
  }
}



function calc(row) {
  const unitQuantity = $(row).find("[name=unitQtytd]").val();
  const purchaseRate = $(row).find("[name=purRatetd]").text();
  const totalAmount = (parseInt(unitQuantity) * parseInt(purchaseRate));

  $(row).find("[name=totalAmttd]").text(totalAmount);

}

document.addEventListener("keydown", function(e) {
  const row = e.target.parentElement.parentElement


  if (e.target.matches('[name=unitQtytd]')) {
    calc(e.target.parentElement.parentElement)
  }

  if (e.target.matches("[name=itemNametd]")) {
    getValues(e.target.parentElement.parentElement)
  }

});


$(document).keypress(function(event) {
  const row = event.target.parentElement.parentElement

  var keycode = event.keyCode || event.which;
  if (keycode == '13') {
    if (!$(event.target).val()) {
      e.preventDefault();
      return;
    }
    if (event.target.matches('[name=discPercentagetd]')) {

      if ($(row).parent().find('tr').length - $(row).index() === 1) {
        rowappend(event.target.parentElement.parentElement.parentElement)
      }
    }
  }
});


function printData() {
  var divToPrint = document.getElementById("printFull");
  var newWin = window.open();
  // add style
  newWin.document.write(`<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" rel="stylesheet" />`);
  // add A4 layout style
  newWin.document.write(`<style>#printFull{ padding: 1cm; width: 19cm }</style>`);
  // turn inputs into text
  $('td input').each(function() {
    $(this).parent().empty().text($(this).val());
  });
  newWin.document.write(divToPrint.outerHTML);
  newWin.print();
  newWin.close();
}


$('#print').on('click', function() {

  document.getElementById("printCompAdd").innerHTML = "Some Address PVT LTD BANGALORE-560037 Mobile : 1234567893/9876543212/	";
  document.getElementById("printSupplAdd").innerHTML = "Some More Address NO.34 2ND CROSSS<br>";
  document.getElementById("printGrnNo").innerHTML = "<b></b> GRN No: 55<br>";
  document.getElementById("printGrnDate").innerHTML = "<b>GRN Date</b> : 04/07/19<br>";
  document.getElementById("printSupplName").innerHTML = "<b>Suppl Name</b> : ALPINE PRODUCTS<br>";



  printData();
  //	window.location = 'Header.html';
})
 #tableInvoice {
   text-align: right;
 }

 @media print {
   #tableInvoice tr td:nth-child(2),
   #tableInvoice tr td:nth-child(3),
   #tableInvoice tr td:nth-child(4),
   #tableInvoice tr td:nth-child(5),
   #tableInvoice tr td:nth-child(6) {
     text-align: right;
   }
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />

<div class="container commonDivInvoice">
  <div id="printFull">
    <span id="printCompAdd" class="show-on-print"></span> <span id="printSupplAdd" class="show-on-print"></span> <span id="printGrnNo" class="show-on-print"></span> <span id="printGrnDate" class="show-on-print"></span> <span id="printSupplName" class="show-on-print"></span>
    <table class="table table-bordered" id="tableInvoice">
      <thead>
        <tr>
          <th id="itemNameth" class="commanth">Item Name</th>
          <th id="itemCodeth" class="commanth">Item Code</th>
          <th id="unitQtyth" class="commanth">Unit Qty</th>
          <th id="purRateth" class="commanth">Pur.Rate</th>
          <th id="discPercentageth" class="commanth">Disc%</th>
          <th id="discAmtth" class="commanth">Disc Amt</th>
          <th id="gstPercentageth" class="commanth">Gst%</th>
          <th id="gstAmtth" class="commanth">Gst Amt</th>
          <th id="totalAmtth" class="commanth">Total Amount</th>
        </tr>
      </thead>
      <tbody>

      </tbody>

    </table>
  </div>
  <button type="button" id="print" class="commonButton">Print
						</button>
</div>

标签: javascriptcsshtml-table

解决方案


您编写的所有 CSS 都没有被应用,因为您在新窗口中创建了发票,newWin没有使用任何给定的样式。

因此,当您为打印文档添加引导 css 以设置样式table时,然后在下一行添加更多 CSS,添加对齐样式,如下所示:

newWin.document.write(`<style>#tableInvoice {text-align: right !important; } #printFull{ padding: 1cm; width: 19cm }</style>`);

推荐阅读