最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to align text right on print - Stack Overflow

programmeradmin4浏览0评论

I have an HTML table which has only one row and the first column is auto plete when user selects any item from it.

I am populating respective fields so after populating all the data I am trying to align some column's data of my table to right when user clicks on print.

I am using @media print but it is not doing anything

Please check out this fiddle

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 mantd" name="itemNametd">
  </td>
  <td name="itemCodetd" class="mantd"></td>
  <td>
    <input type="text" class="form-control mantd" name="unitQtytd">
  </td>
  <td name="purRatetd" class="mantd"></td>
  <td>
    <input type="text" class="form-control mantd" name="discPercentagetd">
  </td>
  <td name="discAmttd" class="mantd"></td> 
  <td name="gstPercentagetd" class="mantd"></td>
  <td name="gstAmttd" class="mantd"></td>
  <td name="totalAmttd" class="mantd"></td>
  
</tr>`

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

  const itemName = data.map(value => { //using autoplete to for searching input field
    return value.ItemName;
  });
  $("[name=itemNametd]", tbody).last().autoplete({
    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=".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=".3.1/jquery.min.js"></script>
<script src=".12.1/jquery-ui.js"></script>
<link href=".1.2/css/bootstrap.min.css" rel="stylesheet" />
<link href=".12.1/themes/base/jquery-ui.css" rel="stylesheet" />

<div class="container monDivInvoice">
  <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="manth">Item Name</th>
          <th id="itemCodeth" class="manth">Item Code</th>
          <th id="unitQtyth" class="manth">Unit Qty</th>
          <th id="purRateth" class="manth">Pur.Rate</th>
          <th id="discPercentageth" class="manth">Disc%</th>
          <th id="discAmtth" class="manth">Disc Amt</th>
          <th id="gstPercentageth" class="manth">Gst%</th>
          <th id="gstAmtth" class="manth">Gst Amt</th>
          <th id="totalAmtth" class="manth">Total Amount</th>
        </tr>
      </thead>
      <tbody>

      </tbody>

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

I have an HTML table which has only one row and the first column is auto plete when user selects any item from it.

I am populating respective fields so after populating all the data I am trying to align some column's data of my table to right when user clicks on print.

I am using @media print but it is not doing anything

Please check out this fiddle

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 mantd" name="itemNametd">
  </td>
  <td name="itemCodetd" class="mantd"></td>
  <td>
    <input type="text" class="form-control mantd" name="unitQtytd">
  </td>
  <td name="purRatetd" class="mantd"></td>
  <td>
    <input type="text" class="form-control mantd" name="discPercentagetd">
  </td>
  <td name="discAmttd" class="mantd"></td> 
  <td name="gstPercentagetd" class="mantd"></td>
  <td name="gstAmttd" class="mantd"></td>
  <td name="totalAmttd" class="mantd"></td>
  
</tr>`

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

  const itemName = data.map(value => { //using autoplete to for searching input field
    return value.ItemName;
  });
  $("[name=itemNametd]", tbody).last().autoplete({
    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./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./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery./ui/1.12.1/jquery-ui.js"></script>
<link href="https://stackpath.bootstrapcdn./bootstrap/4.1.2/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://code.jquery./ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />

<div class="container monDivInvoice">
  <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="manth">Item Name</th>
          <th id="itemCodeth" class="manth">Item Code</th>
          <th id="unitQtyth" class="manth">Unit Qty</th>
          <th id="purRateth" class="manth">Pur.Rate</th>
          <th id="discPercentageth" class="manth">Disc%</th>
          <th id="discAmtth" class="manth">Disc Amt</th>
          <th id="gstPercentageth" class="manth">Gst%</th>
          <th id="gstAmtth" class="manth">Gst Amt</th>
          <th id="totalAmtth" class="manth">Total Amount</th>
        </tr>
      </thead>
      <tbody>

      </tbody>

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

Share Improve this question edited Jul 23, 2019 at 6:50 manish thakur asked Jul 23, 2019 at 6:29 manish thakurmanish thakur 82010 gold badges43 silver badges82 bronze badges 6
  • you have to create a minimal working example in your question and also post the code here. – cloned Commented Jul 23, 2019 at 6:48
  • Could the problem be with using document.write? (developer.mozilla/en-US/docs/Web/API/Document/write) – Cat Commented Jul 23, 2019 at 6:52
  • @Cat I don't know is there any other approach to print? – manish thakur Commented Jul 23, 2019 at 6:56
  • @manishthakur doesn't answer your issue exactly but adding inline style in td work if external css won't work :) – cjmling Commented Jul 23, 2019 at 7:26
  • @cjmling I have already doing check this jsfiddle/draj8126/rds6tyg5/9 fiddle I am doing it like ` #tableInvoice { text-align: right; }` which is aligning all the elements to right but still it is aligning left – manish thakur Commented Jul 23, 2019 at 7:28
 |  Show 1 more ment

5 Answers 5

Reset to default 3

All the CSS you wrote is not getting applied because you created the invoice in new window newWin, which is not using any style given.

So, as you are adding bootstrap css for print document to style table and then in next line you are adding some more CSS, with that add your alignment style as shown below:

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

Please add this below code for each of the items in the table

HTML

<th style="text-align:right;"></th>

When you hit the print button, the print styles applies to your document, but you create the invoice in new window newWin, which has no align styles.

Move the print styles to line 168 of your javascript code in your fiddle (where you have newWin.document.write).

Try this code..

css

#print {
    float: right;
}

you could add this to your function printData:

function printData() {
    ...
    $('td').each(function() { $(this).attr("align","right"); });
    ...
}
发布评论

评论列表(0)

  1. 暂无评论